instance_id
stringlengths 10
57
| patch
stringlengths 261
37.7k
| repo
stringlengths 7
53
| base_commit
stringlengths 40
40
| hints_text
stringclasses 301
values | test_patch
stringlengths 212
2.22M
| problem_statement
stringlengths 23
37.7k
| version
int64 0
0
| environment_setup_commit
stringclasses 89
values | FAIL_TO_PASS
sequencelengths 1
4.94k
| PASS_TO_PASS
sequencelengths 0
7.82k
| meta
dict | created_at
unknown | license
stringclasses 8
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
xonsh__xonsh-4907 | diff --git a/news/fix-empty-gitstatus.rst b/news/fix-empty-gitstatus.rst
new file mode 100644
index 00000000..3a920da1
--- /dev/null
+++ b/news/fix-empty-gitstatus.rst
@@ -0,0 +1,23 @@
+**Added:**
+
+* <news item>
+
+**Changed:**
+
+* <news item>
+
+**Deprecated:**
+
+* <news item>
+
+**Removed:**
+
+* <news item>
+
+**Fixed:**
+
+* ``gitstatus`` Prompt-field would be empty on paths without git setup.
+
+**Security:**
+
+* <news item>
diff --git a/xonsh/prompt/gitstatus.py b/xonsh/prompt/gitstatus.py
index 683d8255..e3a41ca8 100644
--- a/xonsh/prompt/gitstatus.py
+++ b/xonsh/prompt/gitstatus.py
@@ -319,5 +319,11 @@ class GitStatus(MultiPromptField):
continue
yield frag
+ def _collect(self, ctx):
+ if not ctx.pick_val(repo_path):
+ # no need to display any other fragments
+ return
+ yield from super()._collect(ctx)
+
gitstatus = GitStatus()
| xonsh/xonsh | 86e4f004e30529f7ef210da9f03ac3223518f85c | diff --git a/tests/prompt/test_gitstatus.py b/tests/prompt/test_gitstatus.py
index 9e13628b..ce20044e 100644
--- a/tests/prompt/test_gitstatus.py
+++ b/tests/prompt/test_gitstatus.py
@@ -1,3 +1,5 @@
+import os
+
import pytest
from xonsh.prompt import gitstatus
@@ -14,6 +16,7 @@ def prompts(xession):
fields = xession.env["PROMPT_FIELDS"]
yield fields
fields.clear()
+ fields.reset()
@pytest.fixture
@@ -71,3 +74,24 @@ def test_gitstatus_clean(prompts, fake_proc):
assert format(prompts.pick("gitstatus")) == exp
assert _format_value(prompts.pick("gitstatus"), None, None) == exp
assert _format_value(prompts.pick("gitstatus"), "{}", None) == exp
+
+
+def test_no_git(prompts, fake_process, tmp_path):
+ os.chdir(tmp_path)
+ err = b"fatal: not a git repository (or any of the parent directories): .git"
+ for cmd in (
+ "git status --porcelain --branch",
+ "git rev-parse --git-dir",
+ "git diff --numstat",
+ ):
+ fake_process.register_subprocess(
+ command=cmd,
+ stderr=err,
+ returncode=128,
+ )
+
+ exp = ""
+ assert prompts.pick_val("gitstatus.repo_path") == ""
+ assert format(prompts.pick("gitstatus")) == exp
+ assert _format_value(prompts.pick("gitstatus"), None, None) == exp
+ assert _format_value(prompts.pick("gitstatus"), "{}", None) == exp
| {gitstatus: {}} is no longer autohiding gitstatus
`{gitstatus: {}}` in my right prompt no longer hides itself when I'm not in a git repository.
## xonfig
<details>
```
$ xonfig
+------------------+---------------------+
| xonsh | 0.13.0 |
| Python | 3.10.5 |
| PLY | 3.11 |
| have readline | True |
| prompt toolkit | 3.0.30 |
| shell type | prompt_toolkit |
| history backend | sqlite |
| pygments | 2.12.0 |
| on posix | True |
| on linux | True |
| distro | unknown |
| on wsl | False |
| on darwin | False |
| on windows | False |
| on cygwin | False |
| on msys2 | False |
| is superuser | False |
| default encoding | utf-8 |
| xonsh encoding | utf-8 |
| encoding errors | surrogateescape |
| xontrib | [] |
| RC file 1 | /home/monk/.xonshrc |
+------------------+---------------------+
```
</details>
## Expected Behavior
```
$ xonsh --no-rc
monk@lychee ~ $ $RIGHT_PROMPT='<{gitstatus: {}}>'
monk@lychee ~ $ $PROMPT_FIELDS['gitstatus'].fragments = () <>
monk@lychee ~ $ <>
```
## Current Behavior
```
$ xonsh --no-rc
monk@lychee ~ $ $RIGHT_PROMPT='<{gitstatus: {}}>'
monk@lychee ~ $ $PROMPT_FIELDS['gitstatus'].fragments = () < |✓>
monk@lychee ~ $ < >
```
## Steps to Reproduce
see above
## For community
⬇️ **Please click the 👍 reaction instead of leaving a `+1` or 👍 comment**
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/prompt/test_gitstatus.py::test_no_git"
] | [
"tests/prompt/test_gitstatus.py::test_gitstatus_dirty[hidden0-{CYAN}gitstatus-opt\\u2191\\xb77\\u2193\\xb72{RESET}|{RED}\\u25cf1{RESET}{BLUE}+3{RESET}{BLUE}+49{RESET}{RED}-26{RESET}]",
"tests/prompt/test_gitstatus.py::test_gitstatus_dirty[hidden1-{CYAN}gitstatus-opt\\u2191\\xb77\\u2193\\xb72{RESET}|{RED}\\u25cf1{RESET}{BLUE}+3{RESET}]",
"tests/prompt/test_gitstatus.py::test_gitstatus_clean"
] | {
"failed_lite_validators": [
"has_added_files"
],
"has_test_patch": true,
"is_lite": false
} | "2022-08-03T06:26:56Z" | bsd-2-clause |
|
xonsh__xonsh-4916 | diff --git a/news/fix-term-title-update.rst b/news/fix-term-title-update.rst
new file mode 100644
index 00000000..88cf5453
--- /dev/null
+++ b/news/fix-term-title-update.rst
@@ -0,0 +1,24 @@
+**Added:**
+
+* <news item>
+
+**Changed:**
+
+* The terminal's title is updated with the current command's name even if the command is a captured command or a callable alias
+
+**Deprecated:**
+
+* <news item>
+
+**Removed:**
+
+* <news item>
+
+**Fixed:**
+
+* When using the sway window manager, ``swaymsg -t get_inputs`` no longer fails with the error "Unable to receive IPC response"
+* The ``current_job`` variable now works as expected when used in ``$TITLE``
+
+**Security:**
+
+* <news item>
diff --git a/xonsh/procs/pipelines.py b/xonsh/procs/pipelines.py
index f2c7dd5c..623b3a8f 100644
--- a/xonsh/procs/pipelines.py
+++ b/xonsh/procs/pipelines.py
@@ -757,17 +757,8 @@ class HiddenCommandPipeline(CommandPipeline):
return ""
-def pause_call_resume(p, f, *args, **kwargs):
- """For a process p, this will call a function f with the remaining args and
- and kwargs. If the process cannot accept signals, the function will be called.
-
- Parameters
- ----------
- p : Popen object or similar
- f : callable
- args : remaining arguments
- kwargs : keyword arguments
- """
+def resume_process(p):
+ """Sends SIGCONT to a process if possible."""
can_send_signal = (
hasattr(p, "send_signal")
and xp.ON_POSIX
@@ -776,15 +767,9 @@ def pause_call_resume(p, f, *args, **kwargs):
)
if can_send_signal:
try:
- p.send_signal(signal.SIGSTOP)
+ p.send_signal(signal.SIGCONT)
except PermissionError:
pass
- try:
- f(*args, **kwargs)
- except Exception:
- pass
- if can_send_signal:
- p.send_signal(signal.SIGCONT)
class PrevProcCloser(threading.Thread):
diff --git a/xonsh/procs/specs.py b/xonsh/procs/specs.py
index f1963690..dcd8be5e 100644
--- a/xonsh/procs/specs.py
+++ b/xonsh/procs/specs.py
@@ -22,7 +22,7 @@ from xonsh.procs.pipelines import (
STDOUT_CAPTURE_KINDS,
CommandPipeline,
HiddenCommandPipeline,
- pause_call_resume,
+ resume_process,
)
from xonsh.procs.posix import PopenThread
from xonsh.procs.proxies import ProcProxy, ProcProxyThread
@@ -857,14 +857,8 @@ def cmds_to_specs(cmds, captured=False, envs=None):
return specs
-def _should_set_title(captured=False):
- env = XSH.env
- return (
- env.get("XONSH_INTERACTIVE")
- and not env.get("XONSH_STORE_STDOUT")
- and captured not in STDOUT_CAPTURE_KINDS
- and XSH.shell is not None
- )
+def _should_set_title():
+ return XSH.env.get("XONSH_INTERACTIVE") and XSH.shell is not None
def run_subproc(cmds, captured=False, envs=None):
@@ -888,6 +882,23 @@ def run_subproc(cmds, captured=False, envs=None):
print(f"TRACE SUBPROC: {cmds}, captured={captured}", file=sys.stderr)
specs = cmds_to_specs(cmds, captured=captured, envs=envs)
+ if _should_set_title():
+ # context manager updates the command information that gets
+ # accessed by CurrentJobField when setting the terminal's title
+ with XSH.env["PROMPT_FIELDS"]["current_job"].update_current_cmds(cmds):
+ # remove current_job from prompt level cache
+ XSH.env["PROMPT_FIELDS"].reset_key("current_job")
+ # The terminal's title needs to be set before starting the
+ # subprocess to avoid accidentally answering interactive questions
+ # from commands such as `rm -i` (see #1436)
+ XSH.shell.settitle()
+ # run the subprocess
+ return _run_specs(specs, cmds)
+ else:
+ return _run_specs(specs, cmds)
+
+
+def _run_specs(specs, cmds):
captured = specs[-1].captured
if captured == "hiddenobject":
command = HiddenCommandPipeline(specs)
@@ -906,15 +917,12 @@ def run_subproc(cmds, captured=False, envs=None):
"pgrp": command.term_pgid,
}
)
- if _should_set_title(captured=captured):
- # set title here to get currently executing command
- pause_call_resume(proc, XSH.shell.settitle)
- else:
- # for some reason, some programs are in a stopped state when the flow
- # reaches this point, hence a SIGCONT should be sent to `proc` to make
- # sure that the shell doesn't hang. This `pause_call_resume` invocation
- # does this
- pause_call_resume(proc, int)
+ # For some reason, some programs are in a stopped state when the flow
+ # reaches this point, hence a SIGCONT should be sent to `proc` to make
+ # sure that the shell doesn't hang.
+ # See issue #2999 and the fix in PR #3000
+ resume_process(proc)
+
# now figure out what we should return
if captured == "object":
return command # object can be returned even if backgrounding
diff --git a/xonsh/prompt/base.py b/xonsh/prompt/base.py
index c0a44a59..2c6e379c 100644
--- a/xonsh/prompt/base.py
+++ b/xonsh/prompt/base.py
@@ -252,7 +252,7 @@ def _format_value(val, spec, conv) -> str:
and 'current_job' returns 'sleep', the result is 'sleep | ', and if
'current_job' returns None, the result is ''.
"""
- if val is None:
+ if val is None or (isinstance(val, BasePromptField) and val.value is None):
return ""
val = xt.FORMATTER.convert_field(val, conv)
@@ -331,7 +331,7 @@ class PromptFields(tp.MutableMapping[str, "FieldType"]):
_replace_home_cwd,
)
from xonsh.prompt.env import env_name, vte_new_tab_cwd
- from xonsh.prompt.job import _current_job
+ from xonsh.prompt.job import CurrentJobField
from xonsh.prompt.times import _localtime
from xonsh.prompt.vc import branch_bg_color, branch_color, current_branch
@@ -349,7 +349,7 @@ class PromptFields(tp.MutableMapping[str, "FieldType"]):
curr_branch=current_branch,
branch_color=branch_color,
branch_bg_color=branch_bg_color,
- current_job=_current_job,
+ current_job=CurrentJobField(name="current_job"),
env_name=env_name,
env_prefix="(",
env_postfix=") ",
@@ -403,6 +403,10 @@ class PromptFields(tp.MutableMapping[str, "FieldType"]):
"""the results are cached and need to be reset between prompts"""
self._cache.clear()
+ def reset_key(self, key):
+ """remove a single key from the cache (if it exists)"""
+ self._cache.pop(key, None)
+
class BasePromptField:
value = ""
diff --git a/xonsh/prompt/job.py b/xonsh/prompt/job.py
index 97313e0a..ceeec1d9 100644
--- a/xonsh/prompt/job.py
+++ b/xonsh/prompt/job.py
@@ -1,14 +1,30 @@
"""Prompt formatter for current jobs"""
-import xonsh.jobs as xj
+import contextlib
+import typing as tp
+from xonsh.prompt.base import PromptField
-def _current_job():
- j = xj.get_next_task()
- if j is not None:
- if not j["bg"]:
- cmd = j["cmds"][-1]
+
+class CurrentJobField(PromptField):
+ _current_cmds: tp.Optional[list] = None
+
+ def update(self, ctx):
+ if self._current_cmds is not None:
+ cmd = self._current_cmds[-1]
s = cmd[0]
if s == "sudo" and len(cmd) > 1:
s = cmd[1]
- return s
+ self.value = s
+ else:
+ self.value = None
+
+ @contextlib.contextmanager
+ def update_current_cmds(self, cmds):
+ """Context manager that updates the information used to update the job name"""
+ old_cmds = self._current_cmds
+ try:
+ self._current_cmds = cmds
+ yield
+ finally:
+ self._current_cmds = old_cmds
diff --git a/xonsh/readline_shell.py b/xonsh/readline_shell.py
index fce100b8..fb5fa48b 100644
--- a/xonsh/readline_shell.py
+++ b/xonsh/readline_shell.py
@@ -635,6 +635,8 @@ class ReadlineShell(BaseShell, cmd.Cmd):
return self.mlprompt
env = XSH.env # pylint: disable=no-member
p = env.get("PROMPT")
+ # clear prompt level cache
+ env["PROMPT_FIELDS"].reset()
try:
p = self.prompt_formatter(p)
except Exception: # pylint: disable=broad-except
| xonsh/xonsh | cb75d27300cd4e4898ff4bfe82c398080c0d19de | diff --git a/tests/prompt/test_base.py b/tests/prompt/test_base.py
index 1f102ed1..9b633633 100644
--- a/tests/prompt/test_base.py
+++ b/tests/prompt/test_base.py
@@ -4,7 +4,7 @@ from unittest.mock import Mock
import pytest
from xonsh.prompt import env as prompt_env
-from xonsh.prompt.base import PromptFields, PromptFormatter
+from xonsh.prompt.base import PromptField, PromptFields, PromptFormatter
@pytest.fixture
@@ -40,8 +40,10 @@ def test_format_prompt(inp, exp, fields, formatter, xession):
"a_string": "cats",
"a_number": 7,
"empty": "",
- "current_job": (lambda: "sleep"),
+ "a_function": (lambda: "hello"),
+ "current_job": PromptField(value="sleep"),
"none": (lambda: None),
+ "none_pf": PromptField(value=None),
}
],
)
@@ -49,7 +51,9 @@ def test_format_prompt(inp, exp, fields, formatter, xession):
"inp, exp",
[
("{a_number:{0:^3}}cats", " 7 cats"),
+ ("{a_function:{} | }xonsh", "hello | xonsh"),
("{current_job:{} | }xonsh", "sleep | xonsh"),
+ ("{none_pf:{} | }xonsh", "xonsh"),
("{none:{} | }{a_string}{empty:!}", "cats!"),
("{none:{}}", ""),
("{{{a_string:{{{}}}}}}", "{{cats}}"),
diff --git a/tests/prompt/test_job.py b/tests/prompt/test_job.py
new file mode 100644
index 00000000..d8c286cb
--- /dev/null
+++ b/tests/prompt/test_job.py
@@ -0,0 +1,13 @@
+def test_current_job(xession):
+ prompts = xession.env["PROMPT_FIELDS"]
+ cmds = (["echo", "hello"], "|", ["grep", "h"])
+
+ prompts.reset()
+ assert format(prompts.pick("current_job")) == ""
+
+ with prompts["current_job"].update_current_cmds(cmds):
+ prompts.reset()
+ assert format(prompts.pick("current_job")) == "grep"
+
+ prompts.reset()
+ assert format(prompts.pick("current_job")) == ""
diff --git a/tests/test_aliases.py b/tests/test_aliases.py
index b1e92b0c..3662e2b9 100644
--- a/tests/test_aliases.py
+++ b/tests/test_aliases.py
@@ -2,6 +2,7 @@
import inspect
import os
+import sys
import pytest
@@ -195,7 +196,7 @@ def test_exec_alias_args(xession):
def test_exec_alias_return_value(exp_rtn, xonsh_session, monkeypatch):
monkeypatch.setitem(xonsh_session.env, "RAISE_SUBPROC_ERROR", False)
stack = inspect.stack()
- rtn = ExecAlias(f"python -c 'exit({exp_rtn})'")([], stack=stack)
+ rtn = ExecAlias(f"{sys.executable} -c 'exit({exp_rtn})'")([], stack=stack)
assert rtn == exp_rtn
| Current job is not updated in terminal window's title
When I run `xonsh` is using its default settings, the `$TITLE` format string (responsible for setting the terminal window's title) is
```
{current_job:{} | }{user}@{hostname}: {cwd} | xonsh
```
The `current_job` variable in `$TITLE` means that when a foreground job is running, the terminal's title should be updated with the job's command.
For example, suppose my terminal's title is `yaxollum@fedora: ~ | xonsh` when no jobs are running.
When I launch the `cat` command, my terminal's title should be updated to `cat | yaxollum@fedora: ~ | xonsh`. However, under the current `main` version of xonsh, my terminal's title stays unchanged. `git bisect` shows that this was introduced by #4697.
Both this issue and #4034 appear to be related to setting the terminal's title, so I'll try to fix both of them in a PR.
## xonfig
<details>
```
+------------------+-------------------------+
| xonsh | 0.13.0 |
| Git SHA | f2ca59a2 |
| Commit Date | Aug 6 05:07:09 2022 |
| Python | 3.9.13 |
| PLY | 3.11 |
| have readline | True |
| prompt toolkit | 3.0.29 |
| shell type | prompt_toolkit |
| history backend | sqlite |
| pygments | 2.7.4 |
| on posix | True |
| on linux | True |
| distro | fedora |
| on wsl | False |
| on darwin | False |
| on windows | False |
| on cygwin | False |
| on msys2 | False |
| is superuser | False |
| default encoding | utf-8 |
| xonsh encoding | utf-8 |
| encoding errors | surrogateescape |
| xontrib | [] |
| RC file 1 | /home/yaxollum/.xonshrc |
+------------------+-------------------------+
```
</details>
## For community
⬇️ **Please click the 👍 reaction instead of leaving a `+1` or 👍 comment**
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/prompt/test_base.py::test_format_prompt_with_format_spec[{none_pf:{}",
"tests/prompt/test_job.py::test_current_job"
] | [
"tests/prompt/test_base.py::test_format_prompt[my",
"tests/prompt/test_base.py::test_format_prompt[{f}",
"tests/prompt/test_base.py::test_format_prompt_with_format_spec[{a_number:{0:^3}}cats-",
"tests/prompt/test_base.py::test_format_prompt_with_format_spec[{a_function:{}",
"tests/prompt/test_base.py::test_format_prompt_with_format_spec[{current_job:{}",
"tests/prompt/test_base.py::test_format_prompt_with_format_spec[{none:{}",
"tests/prompt/test_base.py::test_format_prompt_with_format_spec[{none:{}}--fields0]",
"tests/prompt/test_base.py::test_format_prompt_with_format_spec[{{{a_string:{{{}}}}}}-{{cats}}-fields0]",
"tests/prompt/test_base.py::test_format_prompt_with_format_spec[{{{none:{{{}}}}}}-{}-fields0]",
"tests/prompt/test_base.py::test_format_prompt_with_broken_template",
"tests/prompt/test_base.py::test_format_prompt_with_broken_template_in_func[{user]",
"tests/prompt/test_base.py::test_format_prompt_with_broken_template_in_func[{{user]",
"tests/prompt/test_base.py::test_format_prompt_with_broken_template_in_func[{{user}]",
"tests/prompt/test_base.py::test_format_prompt_with_broken_template_in_func[{user}{hostname]",
"tests/prompt/test_base.py::test_format_prompt_with_invalid_func",
"tests/prompt/test_base.py::test_format_prompt_with_func_that_raises",
"tests/prompt/test_base.py::test_format_prompt_with_no_env",
"tests/prompt/test_base.py::test_format_prompt_with_various_envs[env]",
"tests/prompt/test_base.py::test_format_prompt_with_various_envs[foo]",
"tests/prompt/test_base.py::test_format_prompt_with_various_envs[bar]",
"tests/prompt/test_base.py::test_format_prompt_with_various_prepost[)-(]",
"tests/prompt/test_base.py::test_format_prompt_with_various_prepost[)-[[]",
"tests/prompt/test_base.py::test_format_prompt_with_various_prepost[)-]",
"tests/prompt/test_base.py::test_format_prompt_with_various_prepost[)-",
"tests/prompt/test_base.py::test_format_prompt_with_various_prepost[]]-(]",
"tests/prompt/test_base.py::test_format_prompt_with_various_prepost[]]-[[]",
"tests/prompt/test_base.py::test_format_prompt_with_various_prepost[]]-]",
"tests/prompt/test_base.py::test_format_prompt_with_various_prepost[]]-",
"tests/prompt/test_base.py::test_format_prompt_with_various_prepost[-(]",
"tests/prompt/test_base.py::test_format_prompt_with_various_prepost[-[[]",
"tests/prompt/test_base.py::test_format_prompt_with_various_prepost[-]",
"tests/prompt/test_base.py::test_format_prompt_with_various_prepost[-",
"tests/prompt/test_base.py::test_format_prompt_with_various_prepost[",
"tests/prompt/test_base.py::test_noenv_with_disable_set",
"tests/prompt/test_base.py::TestPromptFromVenvCfg::test_determine_env_name_from_cfg[prompt",
"tests/prompt/test_base.py::TestPromptFromVenvCfg::test_determine_env_name_from_cfg[\\t",
"tests/prompt/test_base.py::TestPromptFromVenvCfg::test_determine_env_name_from_cfg[nothing",
"tests/prompt/test_base.py::TestPromptFromVenvCfg::test_determine_env_name_from_cfg[other",
"tests/prompt/test_base.py::TestEnvNamePrompt::test_no_prompt",
"tests/prompt/test_base.py::TestEnvNamePrompt::test_search_order",
"tests/prompt/test_base.py::test_custom_env_overrides_default[0]",
"tests/prompt/test_base.py::test_custom_env_overrides_default[1]",
"tests/prompt/test_base.py::test_promptformatter_cache",
"tests/prompt/test_base.py::test_promptformatter_clears_cache",
"tests/test_aliases.py::test_imports",
"tests/test_aliases.py::test_eval_normal",
"tests/test_aliases.py::test_eval_self_reference",
"tests/test_aliases.py::test_eval_recursive",
"tests/test_aliases.py::test_eval_recursive_callable_partial",
"tests/test_aliases.py::test_recursive_callable_partial_all",
"tests/test_aliases.py::test_recursive_callable_partial_handles",
"tests/test_aliases.py::test_recursive_callable_partial_none",
"tests/test_aliases.py::test_subprocess_logical_operators[echo",
"tests/test_aliases.py::test_subprocess_io_operators[echo",
"tests/test_aliases.py::test_subprocess_io_operators[cat",
"tests/test_aliases.py::test_subprocess_io_operators[COMMAND1",
"tests/test_aliases.py::test_dict_merging[alias0]",
"tests/test_aliases.py::test_dict_merging_assignment[alias0]",
"tests/test_aliases.py::test_dict_merging_assignment[alias1]",
"tests/test_aliases.py::test_exec_alias_args",
"tests/test_aliases.py::test_exec_alias_return_value[0]",
"tests/test_aliases.py::test_exec_alias_return_value[1]",
"tests/test_aliases.py::test_exec_alias_return_value[2]",
"tests/test_aliases.py::test_register_decorator"
] | {
"failed_lite_validators": [
"has_issue_reference",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-08-09T04:54:43Z" | bsd-2-clause |
|
xonsh__xonsh-5322 | diff --git a/news/fix-redirect-structure.rst b/news/fix-redirect-structure.rst
new file mode 100644
index 00000000..a84244a8
--- /dev/null
+++ b/news/fix-redirect-structure.rst
@@ -0,0 +1,23 @@
+**Added:**
+
+* <news item>
+
+**Changed:**
+
+* <news item>
+
+**Deprecated:**
+
+* <news item>
+
+**Removed:**
+
+* <news item>
+
+**Fixed:**
+
+* Redirect tokens in quotes (e.g. ">", "2>", "2>1") are now correctly passed to commands as regular arguments.
+
+**Security:**
+
+* <news item>
diff --git a/xonsh/lexer.py b/xonsh/lexer.py
index a0f55feb..ddebd59a 100644
--- a/xonsh/lexer.py
+++ b/xonsh/lexer.py
@@ -23,7 +23,8 @@ from xonsh.tokenize import (
ERRORTOKEN,
GREATER,
INDENT,
- IOREDIRECT,
+ IOREDIRECT1,
+ IOREDIRECT2,
LESS,
MATCH,
NAME,
@@ -101,7 +102,8 @@ def token_map():
}
for op, typ in _op_map.items():
tm[(OP, op)] = typ
- tm[IOREDIRECT] = "IOREDIRECT"
+ tm[IOREDIRECT1] = "IOREDIRECT1"
+ tm[IOREDIRECT2] = "IOREDIRECT2"
tm[STRING] = "STRING"
tm[DOLLARNAME] = "DOLLAR_NAME"
tm[NUMBER] = "NUMBER"
@@ -255,7 +257,7 @@ def handle_redirect(state, token):
key = (typ, st) if (typ, st) in token_map else typ
new_tok = _new_token(token_map[key], st, token.start)
if state["pymode"][-1][0]:
- if typ == IOREDIRECT:
+ if typ in (IOREDIRECT1, IOREDIRECT2):
# Fix Python mode code that was incorrectly recognized as an
# IOREDIRECT by the tokenizer (see issue #4994).
# The tokenizer does not know when the code should be tokenized in
@@ -310,7 +312,8 @@ def special_handlers():
LESS: handle_redirect,
GREATER: handle_redirect,
RIGHTSHIFT: handle_redirect,
- IOREDIRECT: handle_redirect,
+ IOREDIRECT1: handle_redirect,
+ IOREDIRECT2: handle_redirect,
(OP, "<"): handle_redirect,
(OP, ">"): handle_redirect,
(OP, ">>"): handle_redirect,
diff --git a/xonsh/parsers/base.py b/xonsh/parsers/base.py
index e5ede659..c4a6c524 100644
--- a/xonsh/parsers/base.py
+++ b/xonsh/parsers/base.py
@@ -3432,12 +3432,20 @@ class BaseParser:
def p_subproc_atom_redirect(self, p):
"""
- subproc_atom : GT
- | LT
- | RSHIFT
- | IOREDIRECT
- """
- p0 = ast.const_str(s=p[1], lineno=self.lineno, col_offset=self.col)
+ subproc_atom : GT WS subproc_atom
+ | LT WS subproc_atom
+ | RSHIFT WS subproc_atom
+ | IOREDIRECT1 WS subproc_atom
+ | IOREDIRECT2
+ """
+ operator = ast.const_str(s=p[1], lineno=self.lineno, col_offset=self.col)
+ elts = [operator] if len(p) == 2 else [operator, p[3]]
+ p0 = ast.Tuple(
+ elts=elts,
+ ctx=ast.Load(),
+ lineno=self.lineno,
+ col_offset=self.col,
+ )
p0._cliarg_action = "append"
p[0] = p0
@@ -3523,7 +3531,8 @@ class BaseParser:
"LT",
"LSHIFT",
"RSHIFT",
- "IOREDIRECT",
+ "IOREDIRECT1",
+ "IOREDIRECT2",
"SEARCHPATH",
"INDENT",
"DEDENT",
diff --git a/xonsh/parsers/completion_context.py b/xonsh/parsers/completion_context.py
index 04d34350..0984d967 100644
--- a/xonsh/parsers/completion_context.py
+++ b/xonsh/parsers/completion_context.py
@@ -330,7 +330,8 @@ class CompletionContextParser:
"LT",
"GT",
"RSHIFT",
- "IOREDIRECT",
+ "IOREDIRECT1",
+ "IOREDIRECT2",
}
used_tokens |= io_redir_tokens
artificial_tokens = {"ANY"}
diff --git a/xonsh/procs/specs.py b/xonsh/procs/specs.py
index 9a0c639f..7c538a1b 100644
--- a/xonsh/procs/specs.py
+++ b/xonsh/procs/specs.py
@@ -172,10 +172,6 @@ def _O2E_MAP():
return frozenset({f"{o}>{e}" for e in _REDIR_ERR for o in _REDIR_OUT if o != ""})
-def _is_redirect(x):
- return isinstance(x, str) and _REDIR_REGEX.match(x)
-
-
def safe_open(fname, mode, buffering=-1):
"""Safely attempts to open a file in for xonsh subprocs."""
# file descriptors
@@ -401,7 +397,7 @@ class SubprocSpec:
else:
safe_close(value)
msg = "Multiple inputs for stdin for {0!r}"
- msg = msg.format(" ".join(self.args))
+ msg = msg.format(self.get_command_str())
raise xt.XonshError(msg)
@property
@@ -417,7 +413,7 @@ class SubprocSpec:
else:
safe_close(value)
msg = "Multiple redirections for stdout for {0!r}"
- msg = msg.format(" ".join(self.args))
+ msg = msg.format(self.get_command_str())
raise xt.XonshError(msg)
@property
@@ -433,9 +429,14 @@ class SubprocSpec:
else:
safe_close(value)
msg = "Multiple redirections for stderr for {0!r}"
- msg = msg.format(" ".join(self.args))
+ msg = msg.format(self.get_command_str())
raise xt.XonshError(msg)
+ def get_command_str(self):
+ return " ".join(
+ " ".join(arg) if isinstance(arg, tuple) else arg for arg in self.args
+ )
+
#
# Execution methods
#
@@ -579,8 +580,7 @@ class SubprocSpec:
spec = kls(cmd, cls=cls, **kwargs)
# modifications that alter cmds must come after creating instance
# perform initial redirects
- spec.redirect_leading()
- spec.redirect_trailing()
+ spec.resolve_redirects()
# apply aliases
spec.resolve_alias()
spec.resolve_binary_loc()
@@ -590,26 +590,16 @@ class SubprocSpec:
spec.resolve_stack()
return spec
- def redirect_leading(self):
- """Manage leading redirects such as with '< input.txt COMMAND'."""
- while len(self.cmd) >= 3 and self.cmd[0] == "<":
- self.stdin = safe_open(self.cmd[1], "r")
- self.cmd = self.cmd[2:]
-
- def redirect_trailing(self):
- """Manages trailing redirects."""
- while True:
- cmd = self.cmd
- if len(cmd) >= 3 and _is_redirect(cmd[-2]):
- streams = _redirect_streams(cmd[-2], cmd[-1])
- self.stdin, self.stdout, self.stderr = streams
- self.cmd = cmd[:-2]
- elif len(cmd) >= 2 and _is_redirect(cmd[-1]):
- streams = _redirect_streams(cmd[-1])
+ def resolve_redirects(self):
+ """Manages redirects."""
+ new_cmd = []
+ for c in self.cmd:
+ if isinstance(c, tuple):
+ streams = _redirect_streams(*c)
self.stdin, self.stdout, self.stderr = streams
- self.cmd = cmd[:-1]
else:
- break
+ new_cmd.append(c)
+ self.cmd = new_cmd
def resolve_alias(self):
"""Sets alias in command, if applicable."""
@@ -667,8 +657,7 @@ class SubprocSpec:
else:
self.cmd = alias + self.cmd[1:]
# resolve any redirects the aliases may have applied
- self.redirect_leading()
- self.redirect_trailing()
+ self.resolve_redirects()
if self.binary_loc is None:
return
try:
diff --git a/xonsh/tokenize.py b/xonsh/tokenize.py
index 5127286c..a31fef8a 100644
--- a/xonsh/tokenize.py
+++ b/xonsh/tokenize.py
@@ -110,7 +110,8 @@ __all__ = token.__all__ + [ # type:ignore
"ATDOLLAR",
"ATEQUAL",
"DOLLARNAME",
- "IOREDIRECT",
+ "IOREDIRECT1",
+ "IOREDIRECT2",
"MATCH",
"CASE",
]
@@ -135,8 +136,11 @@ N_TOKENS += 3
SEARCHPATH = N_TOKENS
tok_name[N_TOKENS] = "SEARCHPATH"
N_TOKENS += 1
-IOREDIRECT = N_TOKENS
-tok_name[N_TOKENS] = "IOREDIRECT"
+IOREDIRECT1 = N_TOKENS
+tok_name[N_TOKENS] = "IOREDIRECT1"
+N_TOKENS += 1
+IOREDIRECT2 = N_TOKENS
+tok_name[N_TOKENS] = "IOREDIRECT2"
N_TOKENS += 1
DOLLARNAME = N_TOKENS
tok_name[N_TOKENS] = "DOLLARNAME"
@@ -335,10 +339,11 @@ _redir_map = (
)
IORedirect = group(group(*_redir_map), f"{group(*_redir_names)}>>?")
-_redir_check_0 = set(_redir_map)
-_redir_check_1 = {f"{i}>" for i in _redir_names}.union(_redir_check_0)
+_redir_check_map = frozenset(_redir_map)
+
+_redir_check_1 = {f"{i}>" for i in _redir_names}
_redir_check_2 = {f"{i}>>" for i in _redir_names}.union(_redir_check_1)
-_redir_check = frozenset(_redir_check_2)
+_redir_check_single = frozenset(_redir_check_2)
Operator = group(
r"\*\*=?",
@@ -1004,8 +1009,10 @@ def _tokenize(readline, encoding, tolerant=False, tokenize_ioredirects=True):
continue
token, initial = line[start:end], line[start]
- if token in _redir_check:
- yield TokenInfo(IOREDIRECT, token, spos, epos, line)
+ if token in _redir_check_single:
+ yield TokenInfo(IOREDIRECT1, token, spos, epos, line)
+ elif token in _redir_check_map:
+ yield TokenInfo(IOREDIRECT2, token, spos, epos, line)
elif initial in numchars or ( # ordinary number
initial == "." and token != "." and token != "..."
):
| xonsh/xonsh | 7461c507b210d1492cac6d2f517ba459ec86bea8 | diff --git a/tests/test_integrations.py b/tests/test_integrations.py
index 84cdecba..d689a291 100644
--- a/tests/test_integrations.py
+++ b/tests/test_integrations.py
@@ -886,6 +886,27 @@ aliases['echo'] = _echo
assert out == exp
+@skip_if_no_xonsh
[email protected](
+ "cmd, exp",
+ [
+ ("echo '>'", ">\n"),
+ ("echo '2>'", "2>\n"),
+ ("echo '2>1'", "2>1\n"),
+ ],
+)
+def test_redirect_argument(cmd, exp):
+ script = f"""
+#!/usr/bin/env xonsh
+def _echo(args):
+ print(' '.join(args))
+aliases['echo'] = _echo
+{cmd}
+"""
+ out, _, _ = run_xonsh(script)
+ assert out == exp
+
+
# issue 3402
@skip_if_no_xonsh
@skip_if_on_windows
diff --git a/tests/test_lexer.py b/tests/test_lexer.py
index c707c1cc..ad209655 100644
--- a/tests/test_lexer.py
+++ b/tests/test_lexer.py
@@ -415,11 +415,14 @@ def test_float_literals(case):
assert check_token(case, ["NUMBER", case, 0])
[email protected](
- "case", ["2>1", "err>out", "o>", "all>", "e>o", "e>", "out>", "2>&1"]
-)
-def test_ioredir(case):
- assert check_tokens_subproc(case, [("IOREDIRECT", case, 2)], stop=-2)
[email protected]("case", ["o>", "all>", "e>", "out>"])
+def test_ioredir1(case):
+ assert check_tokens_subproc(case, [("IOREDIRECT1", case, 2)], stop=-2)
+
+
[email protected]("case", ["2>1", "err>out", "e>o", "2>&1"])
+def test_ioredir2(case):
+ assert check_tokens_subproc(case, [("IOREDIRECT2", case, 2)], stop=-2)
@pytest.mark.parametrize("case", [">", ">>", "<", "e>", "> ", ">> ", "< ", "e> "])
| Unable to pass a single ">" as an argument
`echo spam ">" eggs` is handled and executed exactly the same as `echo spam > eggs`.
I think this is because of how data is sent to `cmd_to_specs()` eg both are passed as `['echo', 'spam', '>', 'eggs']`.
Also:
* `echo spam @(">") eggs`
## For community
⬇️ **Please click the 👍 reaction instead of leaving a `+1` or 👍 comment**
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_integrations.py::test_loading_correctly[True]",
"tests/test_integrations.py::test_loading_correctly[False]",
"tests/test_lexer.py::test_ioredir1[o>]",
"tests/test_lexer.py::test_ioredir1[all>]",
"tests/test_lexer.py::test_ioredir1[e>]",
"tests/test_lexer.py::test_ioredir1[out>]",
"tests/test_lexer.py::test_ioredir2[2>1]",
"tests/test_lexer.py::test_ioredir2[err>out]",
"tests/test_lexer.py::test_ioredir2[e>o]",
"tests/test_lexer.py::test_ioredir2[2>&1]",
"tests/test_lexer.py::test_pymode_not_ioredirect[2>1-exp0]",
"tests/test_lexer.py::test_pymode_not_ioredirect[a>b-exp1]",
"tests/test_lexer.py::test_pymode_not_ioredirect[3>2>1-exp2]",
"tests/test_lexer.py::test_pymode_not_ioredirect[36+2>>3-exp3]"
] | [
"tests/test_integrations.py::test_script[case0]",
"tests/test_integrations.py::test_script[case1]",
"tests/test_integrations.py::test_script[case2]",
"tests/test_integrations.py::test_script[case3]",
"tests/test_integrations.py::test_script[case4]",
"tests/test_integrations.py::test_script[case5]",
"tests/test_integrations.py::test_script[case6]",
"tests/test_integrations.py::test_script[case7]",
"tests/test_integrations.py::test_script[case8]",
"tests/test_integrations.py::test_script[case9]",
"tests/test_integrations.py::test_script[case10]",
"tests/test_integrations.py::test_script[case11]",
"tests/test_integrations.py::test_script[case12]",
"tests/test_integrations.py::test_script[case13]",
"tests/test_integrations.py::test_script[case14]",
"tests/test_integrations.py::test_script[case15]",
"tests/test_integrations.py::test_script[case16]",
"tests/test_integrations.py::test_script[case17]",
"tests/test_integrations.py::test_script[case18]",
"tests/test_integrations.py::test_script[case19]",
"tests/test_integrations.py::test_script[case20]",
"tests/test_integrations.py::test_script[case21]",
"tests/test_integrations.py::test_script[case22]",
"tests/test_integrations.py::test_script[case23]",
"tests/test_integrations.py::test_script[case24]",
"tests/test_integrations.py::test_script[case25]",
"tests/test_integrations.py::test_script[case27]",
"tests/test_integrations.py::test_script[case28]",
"tests/test_integrations.py::test_script_stderr[case0]",
"tests/test_integrations.py::test_single_command_no_windows[pwd-None-<lambda>]",
"tests/test_integrations.py::test_single_command_no_windows[echo",
"tests/test_integrations.py::test_single_command_no_windows[ls",
"tests/test_integrations.py::test_single_command_no_windows[$FOO='foo'",
"tests/test_integrations.py::test_eof_syntax_error",
"tests/test_integrations.py::test_open_quote_syntax_error",
"tests/test_integrations.py::test_atdollar_no_output",
"tests/test_integrations.py::test_empty_command",
"tests/test_integrations.py::test_printfile",
"tests/test_integrations.py::test_printname",
"tests/test_integrations.py::test_sourcefile",
"tests/test_integrations.py::test_subshells[\\nwith",
"tests/test_integrations.py::test_redirect_out_to_file[pwd-<lambda>]",
"tests/test_integrations.py::test_pipe_between_subprocs[cat",
"tests/test_integrations.py::test_negative_exit_codes_fail",
"tests/test_integrations.py::test_ampersand_argument[echo",
"tests/test_integrations.py::test_redirect_argument[echo",
"tests/test_integrations.py::test_single_command_return_code[import",
"tests/test_integrations.py::test_single_command_return_code[sh",
"tests/test_integrations.py::test_argv0",
"tests/test_integrations.py::test_exec_function_scope[x",
"tests/test_lexer.py::test_int_literal",
"tests/test_lexer.py::test_hex_literal",
"tests/test_lexer.py::test_oct_o_literal",
"tests/test_lexer.py::test_bin_literal",
"tests/test_lexer.py::test_indent",
"tests/test_lexer.py::test_post_whitespace",
"tests/test_lexer.py::test_internal_whitespace",
"tests/test_lexer.py::test_indent_internal_whitespace",
"tests/test_lexer.py::test_assignment",
"tests/test_lexer.py::test_multiline",
"tests/test_lexer.py::test_atdollar_expression",
"tests/test_lexer.py::test_and",
"tests/test_lexer.py::test_ampersand",
"tests/test_lexer.py::test_not_really_and_pre",
"tests/test_lexer.py::test_not_really_and_post",
"tests/test_lexer.py::test_not_really_and_pre_post",
"tests/test_lexer.py::test_not_really_or_pre",
"tests/test_lexer.py::test_not_really_or_post",
"tests/test_lexer.py::test_not_really_or_pre_post",
"tests/test_lexer.py::test_subproc_line_cont_space",
"tests/test_lexer.py::test_subproc_line_cont_nospace",
"tests/test_lexer.py::test_atdollar",
"tests/test_lexer.py::test_doubleamp",
"tests/test_lexer.py::test_pipe",
"tests/test_lexer.py::test_doublepipe",
"tests/test_lexer.py::test_single_quote_literal",
"tests/test_lexer.py::test_double_quote_literal",
"tests/test_lexer.py::test_triple_single_quote_literal",
"tests/test_lexer.py::test_triple_double_quote_literal",
"tests/test_lexer.py::test_single_raw_string_literal",
"tests/test_lexer.py::test_double_raw_string_literal",
"tests/test_lexer.py::test_single_f_string_literal",
"tests/test_lexer.py::test_double_f_string_literal",
"tests/test_lexer.py::test_single_unicode_literal",
"tests/test_lexer.py::test_double_unicode_literal",
"tests/test_lexer.py::test_single_bytes_literal",
"tests/test_lexer.py::test_path_string_literal",
"tests/test_lexer.py::test_path_fstring_literal",
"tests/test_lexer.py::test_regex_globs",
"tests/test_lexer.py::test_float_literals[0.0]",
"tests/test_lexer.py::test_float_literals[.0]",
"tests/test_lexer.py::test_float_literals[0.]",
"tests/test_lexer.py::test_float_literals[1e10]",
"tests/test_lexer.py::test_float_literals[1.e42]",
"tests/test_lexer.py::test_float_literals[0.1e42]",
"tests/test_lexer.py::test_float_literals[0.5e-42]",
"tests/test_lexer.py::test_float_literals[5E10]",
"tests/test_lexer.py::test_float_literals[5e+42]",
"tests/test_lexer.py::test_float_literals[1_0e1_0]",
"tests/test_lexer.py::test_redir_whitespace[>]",
"tests/test_lexer.py::test_redir_whitespace[>>]",
"tests/test_lexer.py::test_redir_whitespace[<]",
"tests/test_lexer.py::test_redir_whitespace[e>]",
"tests/test_lexer.py::test_redir_whitespace[>",
"tests/test_lexer.py::test_redir_whitespace[>>",
"tests/test_lexer.py::test_redir_whitespace[<",
"tests/test_lexer.py::test_redir_whitespace[e>",
"tests/test_lexer.py::test_lexer_split[-exp0]",
"tests/test_lexer.py::test_lexer_split[",
"tests/test_lexer.py::test_lexer_split[echo",
"tests/test_lexer.py::test_lexer_split[![echo",
"tests/test_lexer.py::test_lexer_split[/usr/bin/echo",
"tests/test_lexer.py::test_lexer_split[$(/usr/bin/echo",
"tests/test_lexer.py::test_lexer_split[C:\\\\Python\\\\python.exe",
"tests/test_lexer.py::test_lexer_split[print(\"\"\"I",
"tests/test_lexer.py::test_tolerant_lexer[()]",
"tests/test_lexer.py::test_tolerant_lexer[(]",
"tests/test_lexer.py::test_tolerant_lexer[)]",
"tests/test_lexer.py::test_tolerant_lexer[))]",
"tests/test_lexer.py::test_tolerant_lexer['string\\nliteral]",
"tests/test_lexer.py::test_tolerant_lexer['''string\\nliteral]",
"tests/test_lexer.py::test_tolerant_lexer[string\\nliteral']",
"tests/test_lexer.py::test_tolerant_lexer[\"]",
"tests/test_lexer.py::test_tolerant_lexer[']",
"tests/test_lexer.py::test_tolerant_lexer[\"\"\"]"
] | {
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2024-04-04T22:34:32Z" | bsd-2-clause |
|
xonsh__xonsh-5326 | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 9f429925..0ec50cb0 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -14,7 +14,7 @@ repos:
pass_filenames: false
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
- rev: 'v0.3.4'
+ rev: 'v0.3.5'
hooks:
- id: ruff
args: [., --fix, --exit-non-zero-on-fix]
@@ -41,7 +41,7 @@ repos:
additional_dependencies:
- types-ujson
- repo: https://github.com/pre-commit/pre-commit-hooks
- rev: v4.5.0
+ rev: v4.6.0
hooks:
- id: trailing-whitespace
exclude: |
diff --git a/news/brackets-in-args.rst b/news/brackets-in-args.rst
new file mode 100644
index 00000000..1478e6c5
--- /dev/null
+++ b/news/brackets-in-args.rst
@@ -0,0 +1,23 @@
+**Added:**
+
+* Square brackets can now be used in command arguments without quotes (e.g. `echo a[b]`)
+
+**Changed:**
+
+* <news item>
+
+**Deprecated:**
+
+* <news item>
+
+**Removed:**
+
+* <news item>
+
+**Fixed:**
+
+* <news item>
+
+**Security:**
+
+* <news item>
diff --git a/xonsh/parsers/base.py b/xonsh/parsers/base.py
index c4a6c524..76c2ba4f 100644
--- a/xonsh/parsers/base.py
+++ b/xonsh/parsers/base.py
@@ -1,5 +1,6 @@
"""Implements the base xonsh parser."""
+import itertools
import os
import re
import textwrap
@@ -3496,27 +3497,43 @@ class BaseParser:
"""subproc_arg : subproc_arg_part"""
p[0] = p[1]
+ def _arg_part_combine(self, *arg_parts):
+ """Combines arg_parts. If all arg_parts are strings, concatenate the strings.
+ Otherwise, return a list of arg_parts."""
+ if all(ast.is_const_str(ap) for ap in arg_parts):
+ return ast.const_str(
+ "".join(ap.value for ap in arg_parts),
+ lineno=arg_parts[0].lineno,
+ col_offset=arg_parts[0].col_offset,
+ )
+ else:
+ return list(
+ itertools.chain.from_iterable(
+ ap if isinstance(ap, list) else [ap] for ap in arg_parts
+ )
+ )
+
def p_subproc_arg_many(self, p):
"""subproc_arg : subproc_arg subproc_arg_part"""
# This glues the string together after parsing
+ p[0] = self._arg_part_combine(p[1], p[2])
+
+ def p_subproc_arg_part_brackets(self, p):
+ """subproc_arg_part : lbracket_tok subproc_arg rbracket_tok"""
p1 = p[1]
p2 = p[2]
- if ast.is_const_str(p1) and ast.is_const_str(p2):
- p0 = ast.const_str(
- p1.value + p2.value, lineno=p1.lineno, col_offset=p1.col_offset
- )
- elif isinstance(p1, list):
- if isinstance(p2, list):
- p1.extend(p2)
- else:
- p1.append(p2)
- p0 = p1
- elif isinstance(p2, list):
- p2.insert(0, p1)
- p0 = p2
- else:
- p0 = [p1, p2]
- p[0] = p0
+ p3 = p[3]
+ p1 = ast.const_str(s=p1.value, lineno=p1.lineno, col_offset=p1.lexpos)
+ p3 = ast.const_str(s=p3.value, lineno=p3.lineno, col_offset=p3.lexpos)
+ p[0] = self._arg_part_combine(p1, p2, p3)
+
+ def p_subproc_arg_part_brackets_empty(self, p):
+ """subproc_arg_part : lbracket_tok rbracket_tok"""
+ p1 = p[1]
+ p2 = p[2]
+ p1 = ast.const_str(s=p1.value, lineno=p1.lineno, col_offset=p1.lexpos)
+ p2 = ast.const_str(s=p2.value, lineno=p2.lineno, col_offset=p2.lexpos)
+ p[0] = self._arg_part_combine(p1, p2)
def _attach_subproc_arg_part_rules(self):
toks = set(self.tokens)
diff --git a/xonsh/procs/specs.py b/xonsh/procs/specs.py
index 7c538a1b..660cfc85 100644
--- a/xonsh/procs/specs.py
+++ b/xonsh/procs/specs.py
@@ -250,6 +250,17 @@ def _redirect_streams(r, loc=None):
return stdin, stdout, stderr
+def _flatten_cmd_redirects(cmd):
+ """Transforms a command like ['ls', ('>', '/dev/null')] into ['ls', '>', '/dev/null']."""
+ new_cmd = []
+ for c in cmd:
+ if isinstance(c, tuple):
+ new_cmd.extend(c)
+ else:
+ new_cmd.append(c)
+ return new_cmd
+
+
def default_signal_pauser(n, f):
"""Pauses a signal, as needed."""
signal.pause()
@@ -352,7 +363,7 @@ class SubprocSpec:
else:
self.env = None
# pure attrs
- self.args = list(cmd)
+ self.args = _flatten_cmd_redirects(cmd)
self.alias = None
self.alias_name = None
self.alias_stack = XSH.env.get("__ALIAS_STACK", "").split(":")
@@ -433,9 +444,7 @@ class SubprocSpec:
raise xt.XonshError(msg)
def get_command_str(self):
- return " ".join(
- " ".join(arg) if isinstance(arg, tuple) else arg for arg in self.args
- )
+ return " ".join(arg for arg in self.args)
#
# Execution methods
@@ -883,6 +892,9 @@ def run_subproc(cmds, captured=False, envs=None):
print(f"TRACE SUBPROC: {cmds}, captured={captured}", file=sys.stderr)
specs = cmds_to_specs(cmds, captured=captured, envs=envs)
+ cmds = [
+ _flatten_cmd_redirects(cmd) if isinstance(cmd, list) else cmd for cmd in cmds
+ ]
if _should_set_title():
# context manager updates the command information that gets
# accessed by CurrentJobField when setting the terminal's title
| xonsh/xonsh | 08ac0d97590567728d1b0fb817c70eeb617766ca | diff --git a/tests/test_parser.py b/tests/test_parser.py
index ae57dfa2..ee131ed8 100644
--- a/tests/test_parser.py
+++ b/tests/test_parser.py
@@ -2649,6 +2649,25 @@ def test_echo_slash_question(check_xonsh_ast):
check_xonsh_ast({}, "![echo /?]", False)
[email protected](
+ "case",
+ [
+ "[]",
+ "[[]]",
+ "[a]",
+ "[a][b]",
+ "a[b]",
+ "[a]b",
+ "a[b]c",
+ "a[b[c]]",
+ "[a]b[[]c[d,e]f[]g,h]",
+ "[a@([1,2])]@([3,4])",
+ ],
+)
+def test_echo_brackets(case, check_xonsh_ast):
+ check_xonsh_ast({}, f"![echo {case}]")
+
+
def test_bad_quotes(check_xonsh_ast):
with pytest.raises(SyntaxError):
check_xonsh_ast({}, '![echo """hello]', False)
| Syntax errors in subprocess commands containing []
I am trying to run a command which should be getting passed to a subprocess (in this case rake). The command itself includes square brackets (`[]`) which results in a traceback.
The command: `rake so_thing[some,parameters]`
The error:
<details>
```
Traceback (most recent call last):
File "/home/tmacey/.local/lib/python3.6/site-packages/xonsh/ptk/shell.py", line 137, in _push
locs=None)
File "/home/tmacey/.local/lib/python3.6/site-packages/xonsh/execer.py", line 110, in compile
transform=transform)
File "/home/tmacey/.local/lib/python3.6/site-packages/xonsh/execer.py", line 79, in parse
tree, input = self._parse_ctx_free(input, mode=mode, filename=filename)
File "/home/tmacey/.local/lib/python3.6/site-packages/xonsh/execer.py", line 179, in _parse_ctx_free
raise original_error from None
File "/home/tmacey/.local/lib/python3.6/site-packages/xonsh/execer.py", line 166, in _parse_ctx_free
debug_level=(self.debug_level > 2))
File "/home/tmacey/.local/lib/python3.6/site-packages/xonsh/parsers/base.py", line 348, in parse
tree = self.parser.parse(input=s, lexer=self.lexer, debug=debug_level)
File "/usr/lib/python3.6/site-packages/ply/yacc.py", line 331, in parse
return self.parseopt_notrack(input, lexer, debug, tracking, tokenfunc)
File "/usr/lib/python3.6/site-packages/ply/yacc.py", line 1199, in parseopt_notrack
tok = call_errorfunc(self.errorfunc, errtoken, self)
File "/usr/lib/python3.6/site-packages/ply/yacc.py", line 193, in call_errorfunc
r = errorfunc(token)
File "/home/tmacey/.local/lib/python3.6/site-packages/xonsh/parsers/base.py", line 2726, in p_error
column=p.lexpos))
File "/home/tmacey/.local/lib/python3.6/site-packages/xonsh/parsers/base.py", line 479, in _parse_error
raise err
File "<string>", line None
SyntaxError: /home/tmacey/.local/lib/python3.6/site-packages/xontrib/jedi.xsh:1:21: ('code: [',)
rake generate_stack[01,dev2-useast1]
^
```
</details>
## For community
⬇️ **Please click the 👍 reaction instead of leaving a `+1` or 👍 comment**
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_parser.py::test_echo_brackets[[]]",
"tests/test_parser.py::test_echo_brackets[[[]]]",
"tests/test_parser.py::test_echo_brackets[[a]]",
"tests/test_parser.py::test_echo_brackets[[a][b]]",
"tests/test_parser.py::test_echo_brackets[a[b]]",
"tests/test_parser.py::test_echo_brackets[[a]b]",
"tests/test_parser.py::test_echo_brackets[a[b]c]",
"tests/test_parser.py::test_echo_brackets[a[b[c]]]",
"tests/test_parser.py::test_echo_brackets[[a]b[[]c[d,e]f[]g,h]]",
"tests/test_parser.py::test_echo_brackets[[a@([1,2])]@([3,4])]"
] | [
"tests/test_parser.py::test_int_literal",
"tests/test_parser.py::test_int_literal_underscore",
"tests/test_parser.py::test_float_literal",
"tests/test_parser.py::test_float_literal_underscore",
"tests/test_parser.py::test_imag_literal",
"tests/test_parser.py::test_float_imag_literal",
"tests/test_parser.py::test_complex",
"tests/test_parser.py::test_str_literal",
"tests/test_parser.py::test_bytes_literal",
"tests/test_parser.py::test_raw_literal",
"tests/test_parser.py::test_f_literal",
"tests/test_parser.py::test_string_literal_concat[-]",
"tests/test_parser.py::test_string_literal_concat[-f]",
"tests/test_parser.py::test_string_literal_concat[-r]",
"tests/test_parser.py::test_string_literal_concat[-fr]",
"tests/test_parser.py::test_string_literal_concat[f-]",
"tests/test_parser.py::test_string_literal_concat[f-f]",
"tests/test_parser.py::test_string_literal_concat[f-r]",
"tests/test_parser.py::test_string_literal_concat[f-fr]",
"tests/test_parser.py::test_string_literal_concat[r-]",
"tests/test_parser.py::test_string_literal_concat[r-f]",
"tests/test_parser.py::test_string_literal_concat[r-r]",
"tests/test_parser.py::test_string_literal_concat[r-fr]",
"tests/test_parser.py::test_string_literal_concat[fr-]",
"tests/test_parser.py::test_string_literal_concat[fr-f]",
"tests/test_parser.py::test_string_literal_concat[fr-r]",
"tests/test_parser.py::test_string_literal_concat[fr-fr]",
"tests/test_parser.py::test_f_env_var",
"tests/test_parser.py::test_fstring_adaptor[f\"$HOME\"-$HOME]",
"tests/test_parser.py::test_fstring_adaptor[f\"{0}",
"tests/test_parser.py::test_fstring_adaptor[f\"{$HOME}\"-/foo/bar]",
"tests/test_parser.py::test_fstring_adaptor[f\"{",
"tests/test_parser.py::test_fstring_adaptor[f\"{'$HOME'}\"-$HOME]",
"tests/test_parser.py::test_fstring_adaptor[f\"$HOME",
"tests/test_parser.py::test_fstring_adaptor[f\"{${'HOME'}}\"-/foo/bar]",
"tests/test_parser.py::test_fstring_adaptor[f'{${$FOO+$BAR}}'-/foo/bar]",
"tests/test_parser.py::test_fstring_adaptor[f\"${$FOO}{$BAR}={f'{$HOME}'}\"-$HOME=/foo/bar]",
"tests/test_parser.py::test_fstring_adaptor[f\"\"\"foo\\n{f\"_{$HOME}_\"}\\nbar\"\"\"-foo\\n_/foo/bar_\\nbar]",
"tests/test_parser.py::test_fstring_adaptor[f\"\"\"foo\\n{f\"_{${'HOME'}}_\"}\\nbar\"\"\"-foo\\n_/foo/bar_\\nbar]",
"tests/test_parser.py::test_fstring_adaptor[f\"\"\"foo\\n{f\"_{${",
"tests/test_parser.py::test_fstring_adaptor[f'{$HOME=}'-$HOME='/foo/bar']",
"tests/test_parser.py::test_raw_bytes_literal",
"tests/test_parser.py::test_unary_plus",
"tests/test_parser.py::test_unary_minus",
"tests/test_parser.py::test_unary_invert",
"tests/test_parser.py::test_binop_plus",
"tests/test_parser.py::test_binop_minus",
"tests/test_parser.py::test_binop_times",
"tests/test_parser.py::test_binop_matmult",
"tests/test_parser.py::test_binop_div",
"tests/test_parser.py::test_binop_mod",
"tests/test_parser.py::test_binop_floordiv",
"tests/test_parser.py::test_binop_pow",
"tests/test_parser.py::test_plus_pow",
"tests/test_parser.py::test_plus_plus",
"tests/test_parser.py::test_plus_minus",
"tests/test_parser.py::test_minus_plus",
"tests/test_parser.py::test_minus_minus",
"tests/test_parser.py::test_minus_plus_minus",
"tests/test_parser.py::test_times_plus",
"tests/test_parser.py::test_plus_times",
"tests/test_parser.py::test_times_times",
"tests/test_parser.py::test_times_div",
"tests/test_parser.py::test_times_div_mod",
"tests/test_parser.py::test_times_div_mod_floor",
"tests/test_parser.py::test_str_str",
"tests/test_parser.py::test_str_str_str",
"tests/test_parser.py::test_str_plus_str",
"tests/test_parser.py::test_str_times_int",
"tests/test_parser.py::test_int_times_str",
"tests/test_parser.py::test_group_plus_times",
"tests/test_parser.py::test_plus_group_times",
"tests/test_parser.py::test_group",
"tests/test_parser.py::test_lt",
"tests/test_parser.py::test_gt",
"tests/test_parser.py::test_eq",
"tests/test_parser.py::test_le",
"tests/test_parser.py::test_ge",
"tests/test_parser.py::test_ne",
"tests/test_parser.py::test_in",
"tests/test_parser.py::test_is",
"tests/test_parser.py::test_not_in",
"tests/test_parser.py::test_is_not",
"tests/test_parser.py::test_lt_lt",
"tests/test_parser.py::test_lt_lt_lt",
"tests/test_parser.py::test_not",
"tests/test_parser.py::test_or",
"tests/test_parser.py::test_or_or",
"tests/test_parser.py::test_and",
"tests/test_parser.py::test_and_and",
"tests/test_parser.py::test_and_or",
"tests/test_parser.py::test_or_and",
"tests/test_parser.py::test_group_and_and",
"tests/test_parser.py::test_group_and_or",
"tests/test_parser.py::test_if_else_expr",
"tests/test_parser.py::test_if_else_expr_expr",
"tests/test_parser.py::test_subscription_syntaxes",
"tests/test_parser.py::test_subscription_special_syntaxes",
"tests/test_parser.py::test_str_idx",
"tests/test_parser.py::test_str_slice",
"tests/test_parser.py::test_str_step",
"tests/test_parser.py::test_str_slice_all",
"tests/test_parser.py::test_str_slice_upper",
"tests/test_parser.py::test_str_slice_lower",
"tests/test_parser.py::test_str_slice_other",
"tests/test_parser.py::test_str_slice_lower_other",
"tests/test_parser.py::test_str_slice_upper_other",
"tests/test_parser.py::test_str_2slice",
"tests/test_parser.py::test_str_2step",
"tests/test_parser.py::test_str_2slice_all",
"tests/test_parser.py::test_str_2slice_upper",
"tests/test_parser.py::test_str_2slice_lower",
"tests/test_parser.py::test_str_2slice_lowerupper",
"tests/test_parser.py::test_str_2slice_other",
"tests/test_parser.py::test_str_2slice_lower_other",
"tests/test_parser.py::test_str_2slice_upper_other",
"tests/test_parser.py::test_str_3slice",
"tests/test_parser.py::test_str_3step",
"tests/test_parser.py::test_str_3slice_all",
"tests/test_parser.py::test_str_3slice_upper",
"tests/test_parser.py::test_str_3slice_lower",
"tests/test_parser.py::test_str_3slice_lowerlowerupper",
"tests/test_parser.py::test_str_3slice_lowerupperlower",
"tests/test_parser.py::test_str_3slice_lowerupperupper",
"tests/test_parser.py::test_str_3slice_upperlowerlower",
"tests/test_parser.py::test_str_3slice_upperlowerupper",
"tests/test_parser.py::test_str_3slice_upperupperlower",
"tests/test_parser.py::test_str_3slice_other",
"tests/test_parser.py::test_str_3slice_lower_other",
"tests/test_parser.py::test_str_3slice_upper_other",
"tests/test_parser.py::test_str_slice_true",
"tests/test_parser.py::test_str_true_slice",
"tests/test_parser.py::test_list_empty",
"tests/test_parser.py::test_list_one",
"tests/test_parser.py::test_list_one_comma",
"tests/test_parser.py::test_list_two",
"tests/test_parser.py::test_list_three",
"tests/test_parser.py::test_list_three_comma",
"tests/test_parser.py::test_list_one_nested",
"tests/test_parser.py::test_list_list_four_nested",
"tests/test_parser.py::test_list_tuple_three_nested",
"tests/test_parser.py::test_list_set_tuple_three_nested",
"tests/test_parser.py::test_list_tuple_one_nested",
"tests/test_parser.py::test_tuple_tuple_one_nested",
"tests/test_parser.py::test_dict_list_one_nested",
"tests/test_parser.py::test_dict_list_one_nested_comma",
"tests/test_parser.py::test_dict_tuple_one_nested",
"tests/test_parser.py::test_dict_tuple_one_nested_comma",
"tests/test_parser.py::test_dict_list_two_nested",
"tests/test_parser.py::test_set_tuple_one_nested",
"tests/test_parser.py::test_set_tuple_two_nested",
"tests/test_parser.py::test_tuple_empty",
"tests/test_parser.py::test_tuple_one_bare",
"tests/test_parser.py::test_tuple_two_bare",
"tests/test_parser.py::test_tuple_three_bare",
"tests/test_parser.py::test_tuple_three_bare_comma",
"tests/test_parser.py::test_tuple_one_comma",
"tests/test_parser.py::test_tuple_two",
"tests/test_parser.py::test_tuple_three",
"tests/test_parser.py::test_tuple_three_comma",
"tests/test_parser.py::test_bare_tuple_of_tuples",
"tests/test_parser.py::test_set_one",
"tests/test_parser.py::test_set_one_comma",
"tests/test_parser.py::test_set_two",
"tests/test_parser.py::test_set_two_comma",
"tests/test_parser.py::test_set_three",
"tests/test_parser.py::test_dict_empty",
"tests/test_parser.py::test_dict_one",
"tests/test_parser.py::test_dict_one_comma",
"tests/test_parser.py::test_dict_two",
"tests/test_parser.py::test_dict_two_comma",
"tests/test_parser.py::test_dict_three",
"tests/test_parser.py::test_dict_from_dict_one",
"tests/test_parser.py::test_dict_from_dict_one_comma",
"tests/test_parser.py::test_dict_from_dict_two_xy",
"tests/test_parser.py::test_dict_from_dict_two_x_first",
"tests/test_parser.py::test_dict_from_dict_two_x_second",
"tests/test_parser.py::test_dict_from_dict_two_x_none",
"tests/test_parser.py::test_dict_from_dict_three_xyz[True-True-True]",
"tests/test_parser.py::test_dict_from_dict_three_xyz[True-True-False]",
"tests/test_parser.py::test_dict_from_dict_three_xyz[True-False-True]",
"tests/test_parser.py::test_dict_from_dict_three_xyz[True-False-False]",
"tests/test_parser.py::test_dict_from_dict_three_xyz[False-True-True]",
"tests/test_parser.py::test_dict_from_dict_three_xyz[False-True-False]",
"tests/test_parser.py::test_dict_from_dict_three_xyz[False-False-True]",
"tests/test_parser.py::test_dict_from_dict_three_xyz[False-False-False]",
"tests/test_parser.py::test_unpack_range_tuple",
"tests/test_parser.py::test_unpack_range_tuple_4",
"tests/test_parser.py::test_unpack_range_tuple_parens",
"tests/test_parser.py::test_unpack_range_tuple_parens_4",
"tests/test_parser.py::test_unpack_range_list",
"tests/test_parser.py::test_unpack_range_list_4",
"tests/test_parser.py::test_unpack_range_set",
"tests/test_parser.py::test_unpack_range_set_4",
"tests/test_parser.py::test_true",
"tests/test_parser.py::test_false",
"tests/test_parser.py::test_none",
"tests/test_parser.py::test_elipssis",
"tests/test_parser.py::test_not_implemented_name",
"tests/test_parser.py::test_genexpr",
"tests/test_parser.py::test_genexpr_if",
"tests/test_parser.py::test_genexpr_if_and",
"tests/test_parser.py::test_dbl_genexpr",
"tests/test_parser.py::test_genexpr_if_genexpr",
"tests/test_parser.py::test_genexpr_if_genexpr_if",
"tests/test_parser.py::test_listcomp",
"tests/test_parser.py::test_listcomp_if",
"tests/test_parser.py::test_listcomp_if_and",
"tests/test_parser.py::test_listcomp_multi_if",
"tests/test_parser.py::test_dbl_listcomp",
"tests/test_parser.py::test_listcomp_if_listcomp",
"tests/test_parser.py::test_listcomp_if_listcomp_if",
"tests/test_parser.py::test_setcomp",
"tests/test_parser.py::test_setcomp_if",
"tests/test_parser.py::test_setcomp_if_and",
"tests/test_parser.py::test_dbl_setcomp",
"tests/test_parser.py::test_setcomp_if_setcomp",
"tests/test_parser.py::test_setcomp_if_setcomp_if",
"tests/test_parser.py::test_dictcomp",
"tests/test_parser.py::test_dictcomp_unpack_parens",
"tests/test_parser.py::test_dictcomp_unpack_no_parens",
"tests/test_parser.py::test_dictcomp_if",
"tests/test_parser.py::test_dictcomp_if_and",
"tests/test_parser.py::test_dbl_dictcomp",
"tests/test_parser.py::test_dictcomp_if_dictcomp",
"tests/test_parser.py::test_dictcomp_if_dictcomp_if",
"tests/test_parser.py::test_lambda",
"tests/test_parser.py::test_lambda_x",
"tests/test_parser.py::test_lambda_kwx",
"tests/test_parser.py::test_lambda_x_y",
"tests/test_parser.py::test_lambda_x_y_z",
"tests/test_parser.py::test_lambda_x_kwy",
"tests/test_parser.py::test_lambda_kwx_kwy",
"tests/test_parser.py::test_lambda_kwx_kwy_kwz",
"tests/test_parser.py::test_lambda_x_comma",
"tests/test_parser.py::test_lambda_x_y_comma",
"tests/test_parser.py::test_lambda_x_y_z_comma",
"tests/test_parser.py::test_lambda_x_kwy_comma",
"tests/test_parser.py::test_lambda_kwx_kwy_comma",
"tests/test_parser.py::test_lambda_kwx_kwy_kwz_comma",
"tests/test_parser.py::test_lambda_args",
"tests/test_parser.py::test_lambda_args_x",
"tests/test_parser.py::test_lambda_args_x_y",
"tests/test_parser.py::test_lambda_args_x_kwy",
"tests/test_parser.py::test_lambda_args_kwx_y",
"tests/test_parser.py::test_lambda_args_kwx_kwy",
"tests/test_parser.py::test_lambda_x_args",
"tests/test_parser.py::test_lambda_x_args_y",
"tests/test_parser.py::test_lambda_x_args_y_z",
"tests/test_parser.py::test_lambda_kwargs",
"tests/test_parser.py::test_lambda_x_kwargs",
"tests/test_parser.py::test_lambda_x_y_kwargs",
"tests/test_parser.py::test_lambda_x_kwy_kwargs",
"tests/test_parser.py::test_lambda_args_kwargs",
"tests/test_parser.py::test_lambda_x_args_kwargs",
"tests/test_parser.py::test_lambda_x_y_args_kwargs",
"tests/test_parser.py::test_lambda_kwx_args_kwargs",
"tests/test_parser.py::test_lambda_x_kwy_args_kwargs",
"tests/test_parser.py::test_lambda_x_args_y_kwargs",
"tests/test_parser.py::test_lambda_x_args_kwy_kwargs",
"tests/test_parser.py::test_lambda_args_y_kwargs",
"tests/test_parser.py::test_lambda_star_x",
"tests/test_parser.py::test_lambda_star_x_y",
"tests/test_parser.py::test_lambda_star_x_kwargs",
"tests/test_parser.py::test_lambda_star_kwx_kwargs",
"tests/test_parser.py::test_lambda_x_star_y",
"tests/test_parser.py::test_lambda_x_y_star_z",
"tests/test_parser.py::test_lambda_x_kwy_star_y",
"tests/test_parser.py::test_lambda_x_kwy_star_kwy",
"tests/test_parser.py::test_lambda_x_star_y_kwargs",
"tests/test_parser.py::test_lambda_x_divide_y_star_z_kwargs",
"tests/test_parser.py::test_call_range",
"tests/test_parser.py::test_call_range_comma",
"tests/test_parser.py::test_call_range_x_y",
"tests/test_parser.py::test_call_range_x_y_comma",
"tests/test_parser.py::test_call_range_x_y_z",
"tests/test_parser.py::test_call_dict_kwx",
"tests/test_parser.py::test_call_dict_kwx_comma",
"tests/test_parser.py::test_call_dict_kwx_kwy",
"tests/test_parser.py::test_call_tuple_gen",
"tests/test_parser.py::test_call_tuple_genifs",
"tests/test_parser.py::test_call_range_star",
"tests/test_parser.py::test_call_range_x_star",
"tests/test_parser.py::test_call_int",
"tests/test_parser.py::test_call_int_base_dict",
"tests/test_parser.py::test_call_dict_kwargs",
"tests/test_parser.py::test_call_list_many_star_args",
"tests/test_parser.py::test_call_list_many_starstar_args",
"tests/test_parser.py::test_call_list_many_star_and_starstar_args",
"tests/test_parser.py::test_call_alot",
"tests/test_parser.py::test_call_alot_next",
"tests/test_parser.py::test_call_alot_next_next",
"tests/test_parser.py::test_getattr",
"tests/test_parser.py::test_getattr_getattr",
"tests/test_parser.py::test_dict_tuple_key",
"tests/test_parser.py::test_dict_tuple_key_get",
"tests/test_parser.py::test_dict_tuple_key_get_3",
"tests/test_parser.py::test_pipe_op",
"tests/test_parser.py::test_pipe_op_two",
"tests/test_parser.py::test_pipe_op_three",
"tests/test_parser.py::test_xor_op",
"tests/test_parser.py::test_xor_op_two",
"tests/test_parser.py::test_xor_op_three",
"tests/test_parser.py::test_xor_pipe",
"tests/test_parser.py::test_amp_op",
"tests/test_parser.py::test_amp_op_two",
"tests/test_parser.py::test_amp_op_three",
"tests/test_parser.py::test_lshift_op",
"tests/test_parser.py::test_lshift_op_two",
"tests/test_parser.py::test_lshift_op_three",
"tests/test_parser.py::test_rshift_op",
"tests/test_parser.py::test_rshift_op_two",
"tests/test_parser.py::test_rshift_op_three",
"tests/test_parser.py::test_named_expr",
"tests/test_parser.py::test_named_expr_list",
"tests/test_parser.py::test_equals",
"tests/test_parser.py::test_equals_semi",
"tests/test_parser.py::test_x_y_equals_semi",
"tests/test_parser.py::test_equals_two",
"tests/test_parser.py::test_equals_two_semi",
"tests/test_parser.py::test_equals_three",
"tests/test_parser.py::test_equals_three_semi",
"tests/test_parser.py::test_plus_eq",
"tests/test_parser.py::test_sub_eq",
"tests/test_parser.py::test_times_eq",
"tests/test_parser.py::test_matmult_eq",
"tests/test_parser.py::test_div_eq",
"tests/test_parser.py::test_floordiv_eq",
"tests/test_parser.py::test_pow_eq",
"tests/test_parser.py::test_mod_eq",
"tests/test_parser.py::test_xor_eq",
"tests/test_parser.py::test_ampersand_eq",
"tests/test_parser.py::test_bitor_eq",
"tests/test_parser.py::test_lshift_eq",
"tests/test_parser.py::test_rshift_eq",
"tests/test_parser.py::test_bare_unpack",
"tests/test_parser.py::test_lhand_group_unpack",
"tests/test_parser.py::test_rhand_group_unpack",
"tests/test_parser.py::test_grouped_unpack",
"tests/test_parser.py::test_double_grouped_unpack",
"tests/test_parser.py::test_double_ungrouped_unpack",
"tests/test_parser.py::test_stary_eq",
"tests/test_parser.py::test_stary_x",
"tests/test_parser.py::test_tuple_x_stary",
"tests/test_parser.py::test_list_x_stary",
"tests/test_parser.py::test_bare_x_stary",
"tests/test_parser.py::test_bare_x_stary_z",
"tests/test_parser.py::test_equals_list",
"tests/test_parser.py::test_equals_dict",
"tests/test_parser.py::test_equals_attr",
"tests/test_parser.py::test_equals_annotation",
"tests/test_parser.py::test_equals_annotation_empty",
"tests/test_parser.py::test_dict_keys",
"tests/test_parser.py::test_assert_msg",
"tests/test_parser.py::test_assert",
"tests/test_parser.py::test_pass",
"tests/test_parser.py::test_del",
"tests/test_parser.py::test_del_comma",
"tests/test_parser.py::test_del_two",
"tests/test_parser.py::test_del_two_comma",
"tests/test_parser.py::test_del_with_parens",
"tests/test_parser.py::test_raise",
"tests/test_parser.py::test_raise_x",
"tests/test_parser.py::test_raise_x_from",
"tests/test_parser.py::test_import_x",
"tests/test_parser.py::test_import_xy",
"tests/test_parser.py::test_import_xyz",
"tests/test_parser.py::test_from_x_import_y",
"tests/test_parser.py::test_from_dot_import_y",
"tests/test_parser.py::test_from_dotx_import_y",
"tests/test_parser.py::test_from_dotdotx_import_y",
"tests/test_parser.py::test_from_dotdotdotx_import_y",
"tests/test_parser.py::test_from_dotdotdotdotx_import_y",
"tests/test_parser.py::test_from_import_x_y",
"tests/test_parser.py::test_from_import_x_y_z",
"tests/test_parser.py::test_from_dot_import_x_y",
"tests/test_parser.py::test_from_dot_import_x_y_z",
"tests/test_parser.py::test_from_dot_import_group_x_y",
"tests/test_parser.py::test_import_x_as_y",
"tests/test_parser.py::test_import_xy_as_z",
"tests/test_parser.py::test_import_x_y_as_z",
"tests/test_parser.py::test_import_x_as_y_z",
"tests/test_parser.py::test_import_x_as_y_z_as_a",
"tests/test_parser.py::test_from_dot_import_x_as_y",
"tests/test_parser.py::test_from_x_import_star",
"tests/test_parser.py::test_from_x_import_group_x_y_z",
"tests/test_parser.py::test_from_x_import_group_x_y_z_comma",
"tests/test_parser.py::test_from_x_import_y_as_z",
"tests/test_parser.py::test_from_x_import_y_as_z_a_as_b",
"tests/test_parser.py::test_from_dotx_import_y_as_z_a_as_b_c_as_d",
"tests/test_parser.py::test_continue",
"tests/test_parser.py::test_break",
"tests/test_parser.py::test_global",
"tests/test_parser.py::test_global_xy",
"tests/test_parser.py::test_nonlocal_x",
"tests/test_parser.py::test_nonlocal_xy",
"tests/test_parser.py::test_yield",
"tests/test_parser.py::test_yield_x",
"tests/test_parser.py::test_yield_x_comma",
"tests/test_parser.py::test_yield_x_y",
"tests/test_parser.py::test_yield_x_starexpr",
"tests/test_parser.py::test_yield_from_x",
"tests/test_parser.py::test_return",
"tests/test_parser.py::test_return_x",
"tests/test_parser.py::test_return_x_comma",
"tests/test_parser.py::test_return_x_y",
"tests/test_parser.py::test_return_x_starexpr",
"tests/test_parser.py::test_if_true",
"tests/test_parser.py::test_if_true_twolines",
"tests/test_parser.py::test_if_true_twolines_deindent",
"tests/test_parser.py::test_if_true_else",
"tests/test_parser.py::test_if_true_x",
"tests/test_parser.py::test_if_switch",
"tests/test_parser.py::test_if_switch_elif1_else",
"tests/test_parser.py::test_if_switch_elif2_else",
"tests/test_parser.py::test_if_nested",
"tests/test_parser.py::test_while",
"tests/test_parser.py::test_while_else",
"tests/test_parser.py::test_for",
"tests/test_parser.py::test_for_zip",
"tests/test_parser.py::test_for_idx",
"tests/test_parser.py::test_for_zip_idx",
"tests/test_parser.py::test_for_attr",
"tests/test_parser.py::test_for_zip_attr",
"tests/test_parser.py::test_for_else",
"tests/test_parser.py::test_async_for",
"tests/test_parser.py::test_with",
"tests/test_parser.py::test_with_as",
"tests/test_parser.py::test_with_xy",
"tests/test_parser.py::test_with_x_as_y_z",
"tests/test_parser.py::test_with_x_as_y_a_as_b",
"tests/test_parser.py::test_with_in_func",
"tests/test_parser.py::test_async_with",
"tests/test_parser.py::test_try",
"tests/test_parser.py::test_try_except_t",
"tests/test_parser.py::test_try_except_t_as_e",
"tests/test_parser.py::test_try_except_t_u",
"tests/test_parser.py::test_try_except_t_u_as_e",
"tests/test_parser.py::test_try_except_t_except_u",
"tests/test_parser.py::test_try_except_else",
"tests/test_parser.py::test_try_except_finally",
"tests/test_parser.py::test_try_except_else_finally",
"tests/test_parser.py::test_try_finally",
"tests/test_parser.py::test_func",
"tests/test_parser.py::test_func_ret",
"tests/test_parser.py::test_func_ret_42",
"tests/test_parser.py::test_func_ret_42_65",
"tests/test_parser.py::test_func_rarrow",
"tests/test_parser.py::test_func_x",
"tests/test_parser.py::test_func_kwx",
"tests/test_parser.py::test_func_x_y",
"tests/test_parser.py::test_func_x_y_z",
"tests/test_parser.py::test_func_x_kwy",
"tests/test_parser.py::test_func_kwx_kwy",
"tests/test_parser.py::test_func_kwx_kwy_kwz",
"tests/test_parser.py::test_func_x_comma",
"tests/test_parser.py::test_func_x_y_comma",
"tests/test_parser.py::test_func_x_y_z_comma",
"tests/test_parser.py::test_func_x_kwy_comma",
"tests/test_parser.py::test_func_kwx_kwy_comma",
"tests/test_parser.py::test_func_kwx_kwy_kwz_comma",
"tests/test_parser.py::test_func_args",
"tests/test_parser.py::test_func_args_x",
"tests/test_parser.py::test_func_args_x_y",
"tests/test_parser.py::test_func_args_x_kwy",
"tests/test_parser.py::test_func_args_kwx_y",
"tests/test_parser.py::test_func_args_kwx_kwy",
"tests/test_parser.py::test_func_x_args",
"tests/test_parser.py::test_func_x_args_y",
"tests/test_parser.py::test_func_x_args_y_z",
"tests/test_parser.py::test_func_kwargs",
"tests/test_parser.py::test_func_x_kwargs",
"tests/test_parser.py::test_func_x_y_kwargs",
"tests/test_parser.py::test_func_x_kwy_kwargs",
"tests/test_parser.py::test_func_args_kwargs",
"tests/test_parser.py::test_func_x_args_kwargs",
"tests/test_parser.py::test_func_x_y_args_kwargs",
"tests/test_parser.py::test_func_kwx_args_kwargs",
"tests/test_parser.py::test_func_x_kwy_args_kwargs",
"tests/test_parser.py::test_func_x_args_y_kwargs",
"tests/test_parser.py::test_func_x_args_kwy_kwargs",
"tests/test_parser.py::test_func_args_y_kwargs",
"tests/test_parser.py::test_func_star_x",
"tests/test_parser.py::test_func_star_x_y",
"tests/test_parser.py::test_func_star_x_kwargs",
"tests/test_parser.py::test_func_star_kwx_kwargs",
"tests/test_parser.py::test_func_x_star_y",
"tests/test_parser.py::test_func_x_y_star_z",
"tests/test_parser.py::test_func_x_kwy_star_y",
"tests/test_parser.py::test_func_x_kwy_star_kwy",
"tests/test_parser.py::test_func_x_star_y_kwargs",
"tests/test_parser.py::test_func_x_divide",
"tests/test_parser.py::test_func_x_divide_y_star_z_kwargs",
"tests/test_parser.py::test_func_tx",
"tests/test_parser.py::test_func_txy",
"tests/test_parser.py::test_class",
"tests/test_parser.py::test_class_obj",
"tests/test_parser.py::test_class_int_flt",
"tests/test_parser.py::test_class_obj_kw",
"tests/test_parser.py::test_decorator",
"tests/test_parser.py::test_decorator_2",
"tests/test_parser.py::test_decorator_call",
"tests/test_parser.py::test_decorator_call_args",
"tests/test_parser.py::test_decorator_dot_call_args",
"tests/test_parser.py::test_decorator_dot_dot_call_args",
"tests/test_parser.py::test_broken_prompt_func",
"tests/test_parser.py::test_class_with_methods",
"tests/test_parser.py::test_nested_functions",
"tests/test_parser.py::test_function_blank_line",
"tests/test_parser.py::test_async_func",
"tests/test_parser.py::test_async_decorator",
"tests/test_parser.py::test_async_await",
"tests/test_parser.py::test_named_expr_args",
"tests/test_parser.py::test_named_expr_if",
"tests/test_parser.py::test_named_expr_elif",
"tests/test_parser.py::test_named_expr_while",
"tests/test_parser.py::test_path_literal",
"tests/test_parser.py::test_path_fstring_literal",
"tests/test_parser.py::test_path_literal_concat[p-p]",
"tests/test_parser.py::test_path_literal_concat[p-pf]",
"tests/test_parser.py::test_path_literal_concat[p-pr]",
"tests/test_parser.py::test_path_literal_concat[pf-p]",
"tests/test_parser.py::test_path_literal_concat[pf-pf]",
"tests/test_parser.py::test_path_literal_concat[pf-pr]",
"tests/test_parser.py::test_path_literal_concat[pr-p]",
"tests/test_parser.py::test_path_literal_concat[pr-pf]",
"tests/test_parser.py::test_path_literal_concat[pr-pr]",
"tests/test_parser.py::test_dollar_name",
"tests/test_parser.py::test_dollar_py",
"tests/test_parser.py::test_dollar_py_test",
"tests/test_parser.py::test_dollar_py_recursive_name",
"tests/test_parser.py::test_dollar_py_test_recursive_name",
"tests/test_parser.py::test_dollar_py_test_recursive_test",
"tests/test_parser.py::test_dollar_name_set",
"tests/test_parser.py::test_dollar_py_set",
"tests/test_parser.py::test_dollar_sub",
"tests/test_parser.py::test_dollar_sub_space[$(ls",
"tests/test_parser.py::test_dollar_sub_space[$(",
"tests/test_parser.py::test_ls_dot",
"tests/test_parser.py::test_lambda_in_atparens",
"tests/test_parser.py::test_generator_in_atparens",
"tests/test_parser.py::test_bare_tuple_in_atparens",
"tests/test_parser.py::test_nested_madness",
"tests/test_parser.py::test_atparens_intoken",
"tests/test_parser.py::test_ls_dot_nesting",
"tests/test_parser.py::test_ls_dot_nesting_var",
"tests/test_parser.py::test_ls_dot_str",
"tests/test_parser.py::test_ls_nest_ls",
"tests/test_parser.py::test_ls_nest_ls_dashl",
"tests/test_parser.py::test_ls_envvar_strval",
"tests/test_parser.py::test_ls_envvar_listval",
"tests/test_parser.py::test_bang_sub",
"tests/test_parser.py::test_bang_sub_space[!(ls",
"tests/test_parser.py::test_bang_sub_space[!(",
"tests/test_parser.py::test_bang_ls_dot",
"tests/test_parser.py::test_bang_ls_dot_nesting",
"tests/test_parser.py::test_bang_ls_dot_nesting_var",
"tests/test_parser.py::test_bang_ls_dot_str",
"tests/test_parser.py::test_bang_ls_nest_ls",
"tests/test_parser.py::test_bang_ls_nest_ls_dashl",
"tests/test_parser.py::test_bang_ls_envvar_strval",
"tests/test_parser.py::test_bang_ls_envvar_listval",
"tests/test_parser.py::test_bang_envvar_args",
"tests/test_parser.py::test_question",
"tests/test_parser.py::test_dobquestion",
"tests/test_parser.py::test_question_chain",
"tests/test_parser.py::test_ls_regex",
"tests/test_parser.py::test_backtick[--]",
"tests/test_parser.py::test_backtick[--p]",
"tests/test_parser.py::test_backtick[-f-]",
"tests/test_parser.py::test_backtick[-f-p]",
"tests/test_parser.py::test_backtick[r--]",
"tests/test_parser.py::test_backtick[r--p]",
"tests/test_parser.py::test_backtick[r-f-]",
"tests/test_parser.py::test_backtick[r-f-p]",
"tests/test_parser.py::test_backtick[g--]",
"tests/test_parser.py::test_backtick[g--p]",
"tests/test_parser.py::test_backtick[g-f-]",
"tests/test_parser.py::test_backtick[g-f-p]",
"tests/test_parser.py::test_ls_regex_octothorpe",
"tests/test_parser.py::test_ls_explicitregex",
"tests/test_parser.py::test_ls_explicitregex_octothorpe",
"tests/test_parser.py::test_ls_glob",
"tests/test_parser.py::test_ls_glob_octothorpe",
"tests/test_parser.py::test_ls_customsearch",
"tests/test_parser.py::test_custombacktick",
"tests/test_parser.py::test_ls_customsearch_octothorpe",
"tests/test_parser.py::test_injection",
"tests/test_parser.py::test_rhs_nested_injection",
"tests/test_parser.py::test_merged_injection",
"tests/test_parser.py::test_backtick_octothorpe",
"tests/test_parser.py::test_uncaptured_sub",
"tests/test_parser.py::test_hiddenobj_sub",
"tests/test_parser.py::test_slash_envarv_echo",
"tests/test_parser.py::test_echo_double_eq",
"tests/test_parser.py::test_bang_two_cmds_one_pipe",
"tests/test_parser.py::test_bang_three_cmds_two_pipes",
"tests/test_parser.py::test_bang_one_cmd_write",
"tests/test_parser.py::test_bang_one_cmd_append",
"tests/test_parser.py::test_bang_two_cmds_write",
"tests/test_parser.py::test_bang_two_cmds_append",
"tests/test_parser.py::test_bang_cmd_background",
"tests/test_parser.py::test_bang_cmd_background_nospace",
"tests/test_parser.py::test_bang_git_quotes_no_space",
"tests/test_parser.py::test_bang_git_quotes_space",
"tests/test_parser.py::test_bang_git_two_quotes_space",
"tests/test_parser.py::test_bang_git_two_quotes_space_space",
"tests/test_parser.py::test_bang_ls_quotes_3_space",
"tests/test_parser.py::test_two_cmds_one_pipe",
"tests/test_parser.py::test_three_cmds_two_pipes",
"tests/test_parser.py::test_two_cmds_one_and_brackets",
"tests/test_parser.py::test_three_cmds_two_ands",
"tests/test_parser.py::test_two_cmds_one_doubleamps",
"tests/test_parser.py::test_three_cmds_two_doubleamps",
"tests/test_parser.py::test_two_cmds_one_or",
"tests/test_parser.py::test_three_cmds_two_ors",
"tests/test_parser.py::test_two_cmds_one_doublepipe",
"tests/test_parser.py::test_three_cmds_two_doublepipe",
"tests/test_parser.py::test_one_cmd_write",
"tests/test_parser.py::test_one_cmd_append",
"tests/test_parser.py::test_two_cmds_write",
"tests/test_parser.py::test_two_cmds_append",
"tests/test_parser.py::test_cmd_background",
"tests/test_parser.py::test_cmd_background_nospace",
"tests/test_parser.py::test_git_quotes_no_space",
"tests/test_parser.py::test_git_quotes_space",
"tests/test_parser.py::test_git_two_quotes_space",
"tests/test_parser.py::test_git_two_quotes_space_space",
"tests/test_parser.py::test_ls_quotes_3_space",
"tests/test_parser.py::test_leading_envvar_assignment",
"tests/test_parser.py::test_echo_comma",
"tests/test_parser.py::test_echo_internal_comma",
"tests/test_parser.py::test_comment_only",
"tests/test_parser.py::test_echo_slash_question",
"tests/test_parser.py::test_bad_quotes",
"tests/test_parser.py::test_redirect",
"tests/test_parser.py::test_use_subshell[![(cat)]]",
"tests/test_parser.py::test_use_subshell[![(cat;)]]",
"tests/test_parser.py::test_use_subshell[![(cd",
"tests/test_parser.py::test_use_subshell[![(echo",
"tests/test_parser.py::test_use_subshell[![(if",
"tests/test_parser.py::test_redirect_abspath[$[cat",
"tests/test_parser.py::test_redirect_abspath[$[(cat)",
"tests/test_parser.py::test_redirect_abspath[$[<",
"tests/test_parser.py::test_redirect_abspath[![<",
"tests/test_parser.py::test_redirect_output[]",
"tests/test_parser.py::test_redirect_output[o]",
"tests/test_parser.py::test_redirect_output[out]",
"tests/test_parser.py::test_redirect_output[1]",
"tests/test_parser.py::test_redirect_error[e]",
"tests/test_parser.py::test_redirect_error[err]",
"tests/test_parser.py::test_redirect_error[2]",
"tests/test_parser.py::test_redirect_all[a]",
"tests/test_parser.py::test_redirect_all[all]",
"tests/test_parser.py::test_redirect_all[&]",
"tests/test_parser.py::test_redirect_error_to_output[-e>o]",
"tests/test_parser.py::test_redirect_error_to_output[-e>out]",
"tests/test_parser.py::test_redirect_error_to_output[-err>o]",
"tests/test_parser.py::test_redirect_error_to_output[-2>1]",
"tests/test_parser.py::test_redirect_error_to_output[-e>1]",
"tests/test_parser.py::test_redirect_error_to_output[-err>1]",
"tests/test_parser.py::test_redirect_error_to_output[-2>out]",
"tests/test_parser.py::test_redirect_error_to_output[-2>o]",
"tests/test_parser.py::test_redirect_error_to_output[-err>&1]",
"tests/test_parser.py::test_redirect_error_to_output[-e>&1]",
"tests/test_parser.py::test_redirect_error_to_output[-2>&1]",
"tests/test_parser.py::test_redirect_error_to_output[o-e>o]",
"tests/test_parser.py::test_redirect_error_to_output[o-e>out]",
"tests/test_parser.py::test_redirect_error_to_output[o-err>o]",
"tests/test_parser.py::test_redirect_error_to_output[o-2>1]",
"tests/test_parser.py::test_redirect_error_to_output[o-e>1]",
"tests/test_parser.py::test_redirect_error_to_output[o-err>1]",
"tests/test_parser.py::test_redirect_error_to_output[o-2>out]",
"tests/test_parser.py::test_redirect_error_to_output[o-2>o]",
"tests/test_parser.py::test_redirect_error_to_output[o-err>&1]",
"tests/test_parser.py::test_redirect_error_to_output[o-e>&1]",
"tests/test_parser.py::test_redirect_error_to_output[o-2>&1]",
"tests/test_parser.py::test_redirect_error_to_output[out-e>o]",
"tests/test_parser.py::test_redirect_error_to_output[out-e>out]",
"tests/test_parser.py::test_redirect_error_to_output[out-err>o]",
"tests/test_parser.py::test_redirect_error_to_output[out-2>1]",
"tests/test_parser.py::test_redirect_error_to_output[out-e>1]",
"tests/test_parser.py::test_redirect_error_to_output[out-err>1]",
"tests/test_parser.py::test_redirect_error_to_output[out-2>out]",
"tests/test_parser.py::test_redirect_error_to_output[out-2>o]",
"tests/test_parser.py::test_redirect_error_to_output[out-err>&1]",
"tests/test_parser.py::test_redirect_error_to_output[out-e>&1]",
"tests/test_parser.py::test_redirect_error_to_output[out-2>&1]",
"tests/test_parser.py::test_redirect_error_to_output[1-e>o]",
"tests/test_parser.py::test_redirect_error_to_output[1-e>out]",
"tests/test_parser.py::test_redirect_error_to_output[1-err>o]",
"tests/test_parser.py::test_redirect_error_to_output[1-2>1]",
"tests/test_parser.py::test_redirect_error_to_output[1-e>1]",
"tests/test_parser.py::test_redirect_error_to_output[1-err>1]",
"tests/test_parser.py::test_redirect_error_to_output[1-2>out]",
"tests/test_parser.py::test_redirect_error_to_output[1-2>o]",
"tests/test_parser.py::test_redirect_error_to_output[1-err>&1]",
"tests/test_parser.py::test_redirect_error_to_output[1-e>&1]",
"tests/test_parser.py::test_redirect_error_to_output[1-2>&1]",
"tests/test_parser.py::test_redirect_output_to_error[e-o>e]",
"tests/test_parser.py::test_redirect_output_to_error[e-o>err]",
"tests/test_parser.py::test_redirect_output_to_error[e-out>e]",
"tests/test_parser.py::test_redirect_output_to_error[e-1>2]",
"tests/test_parser.py::test_redirect_output_to_error[e-o>2]",
"tests/test_parser.py::test_redirect_output_to_error[e-out>2]",
"tests/test_parser.py::test_redirect_output_to_error[e-1>err]",
"tests/test_parser.py::test_redirect_output_to_error[e-1>e]",
"tests/test_parser.py::test_redirect_output_to_error[e-out>&2]",
"tests/test_parser.py::test_redirect_output_to_error[e-o>&2]",
"tests/test_parser.py::test_redirect_output_to_error[e-1>&2]",
"tests/test_parser.py::test_redirect_output_to_error[err-o>e]",
"tests/test_parser.py::test_redirect_output_to_error[err-o>err]",
"tests/test_parser.py::test_redirect_output_to_error[err-out>e]",
"tests/test_parser.py::test_redirect_output_to_error[err-1>2]",
"tests/test_parser.py::test_redirect_output_to_error[err-o>2]",
"tests/test_parser.py::test_redirect_output_to_error[err-out>2]",
"tests/test_parser.py::test_redirect_output_to_error[err-1>err]",
"tests/test_parser.py::test_redirect_output_to_error[err-1>e]",
"tests/test_parser.py::test_redirect_output_to_error[err-out>&2]",
"tests/test_parser.py::test_redirect_output_to_error[err-o>&2]",
"tests/test_parser.py::test_redirect_output_to_error[err-1>&2]",
"tests/test_parser.py::test_redirect_output_to_error[2-o>e]",
"tests/test_parser.py::test_redirect_output_to_error[2-o>err]",
"tests/test_parser.py::test_redirect_output_to_error[2-out>e]",
"tests/test_parser.py::test_redirect_output_to_error[2-1>2]",
"tests/test_parser.py::test_redirect_output_to_error[2-o>2]",
"tests/test_parser.py::test_redirect_output_to_error[2-out>2]",
"tests/test_parser.py::test_redirect_output_to_error[2-1>err]",
"tests/test_parser.py::test_redirect_output_to_error[2-1>e]",
"tests/test_parser.py::test_redirect_output_to_error[2-out>&2]",
"tests/test_parser.py::test_redirect_output_to_error[2-o>&2]",
"tests/test_parser.py::test_redirect_output_to_error[2-1>&2]",
"tests/test_parser.py::test_macro_call_empty",
"tests/test_parser.py::test_macro_call_one_arg[x]",
"tests/test_parser.py::test_macro_call_one_arg[True]",
"tests/test_parser.py::test_macro_call_one_arg[None]",
"tests/test_parser.py::test_macro_call_one_arg[import",
"tests/test_parser.py::test_macro_call_one_arg[x=10]",
"tests/test_parser.py::test_macro_call_one_arg[\"oh",
"tests/test_parser.py::test_macro_call_one_arg[...]",
"tests/test_parser.py::test_macro_call_one_arg[",
"tests/test_parser.py::test_macro_call_one_arg[if",
"tests/test_parser.py::test_macro_call_one_arg[{x:",
"tests/test_parser.py::test_macro_call_one_arg[{1,",
"tests/test_parser.py::test_macro_call_one_arg[(x,y)]",
"tests/test_parser.py::test_macro_call_one_arg[(x,",
"tests/test_parser.py::test_macro_call_one_arg[((x,",
"tests/test_parser.py::test_macro_call_one_arg[g()]",
"tests/test_parser.py::test_macro_call_one_arg[range(10)]",
"tests/test_parser.py::test_macro_call_one_arg[range(1,",
"tests/test_parser.py::test_macro_call_one_arg[()]",
"tests/test_parser.py::test_macro_call_one_arg[{}]",
"tests/test_parser.py::test_macro_call_one_arg[[]]",
"tests/test_parser.py::test_macro_call_one_arg[[1,",
"tests/test_parser.py::test_macro_call_one_arg[@(x)]",
"tests/test_parser.py::test_macro_call_one_arg[!(ls",
"tests/test_parser.py::test_macro_call_one_arg[![ls",
"tests/test_parser.py::test_macro_call_one_arg[$(ls",
"tests/test_parser.py::test_macro_call_one_arg[${x",
"tests/test_parser.py::test_macro_call_one_arg[$[ls",
"tests/test_parser.py::test_macro_call_one_arg[@$(which",
"tests/test_parser.py::test_macro_call_two_args[x-True]",
"tests/test_parser.py::test_macro_call_two_args[x-import",
"tests/test_parser.py::test_macro_call_two_args[x-\"oh",
"tests/test_parser.py::test_macro_call_two_args[x-",
"tests/test_parser.py::test_macro_call_two_args[x-{x:",
"tests/test_parser.py::test_macro_call_two_args[x-{1,",
"tests/test_parser.py::test_macro_call_two_args[x-(x,",
"tests/test_parser.py::test_macro_call_two_args[x-g()]",
"tests/test_parser.py::test_macro_call_two_args[x-range(1,",
"tests/test_parser.py::test_macro_call_two_args[x-{}]",
"tests/test_parser.py::test_macro_call_two_args[x-[1,",
"tests/test_parser.py::test_macro_call_two_args[x-!(ls",
"tests/test_parser.py::test_macro_call_two_args[x-$(ls",
"tests/test_parser.py::test_macro_call_two_args[x-$[ls",
"tests/test_parser.py::test_macro_call_two_args[None-True]",
"tests/test_parser.py::test_macro_call_two_args[None-import",
"tests/test_parser.py::test_macro_call_two_args[None-\"oh",
"tests/test_parser.py::test_macro_call_two_args[None-",
"tests/test_parser.py::test_macro_call_two_args[None-{x:",
"tests/test_parser.py::test_macro_call_two_args[None-{1,",
"tests/test_parser.py::test_macro_call_two_args[None-(x,",
"tests/test_parser.py::test_macro_call_two_args[None-g()]",
"tests/test_parser.py::test_macro_call_two_args[None-range(1,",
"tests/test_parser.py::test_macro_call_two_args[None-{}]",
"tests/test_parser.py::test_macro_call_two_args[None-[1,",
"tests/test_parser.py::test_macro_call_two_args[None-!(ls",
"tests/test_parser.py::test_macro_call_two_args[None-$(ls",
"tests/test_parser.py::test_macro_call_two_args[None-$[ls",
"tests/test_parser.py::test_macro_call_two_args[x=10-True]",
"tests/test_parser.py::test_macro_call_two_args[x=10-import",
"tests/test_parser.py::test_macro_call_two_args[x=10-\"oh",
"tests/test_parser.py::test_macro_call_two_args[x=10-",
"tests/test_parser.py::test_macro_call_two_args[x=10-{x:",
"tests/test_parser.py::test_macro_call_two_args[x=10-{1,",
"tests/test_parser.py::test_macro_call_two_args[x=10-(x,",
"tests/test_parser.py::test_macro_call_two_args[x=10-g()]",
"tests/test_parser.py::test_macro_call_two_args[x=10-range(1,",
"tests/test_parser.py::test_macro_call_two_args[x=10-{}]",
"tests/test_parser.py::test_macro_call_two_args[x=10-[1,",
"tests/test_parser.py::test_macro_call_two_args[x=10-!(ls",
"tests/test_parser.py::test_macro_call_two_args[x=10-$(ls",
"tests/test_parser.py::test_macro_call_two_args[x=10-$[ls",
"tests/test_parser.py::test_macro_call_two_args[...-True]",
"tests/test_parser.py::test_macro_call_two_args[...-import",
"tests/test_parser.py::test_macro_call_two_args[...-\"oh",
"tests/test_parser.py::test_macro_call_two_args[...-",
"tests/test_parser.py::test_macro_call_two_args[...-{x:",
"tests/test_parser.py::test_macro_call_two_args[...-{1,",
"tests/test_parser.py::test_macro_call_two_args[...-(x,",
"tests/test_parser.py::test_macro_call_two_args[...-g()]",
"tests/test_parser.py::test_macro_call_two_args[...-range(1,",
"tests/test_parser.py::test_macro_call_two_args[...-{}]",
"tests/test_parser.py::test_macro_call_two_args[...-[1,",
"tests/test_parser.py::test_macro_call_two_args[...-!(ls",
"tests/test_parser.py::test_macro_call_two_args[...-$(ls",
"tests/test_parser.py::test_macro_call_two_args[...-$[ls",
"tests/test_parser.py::test_macro_call_two_args[if",
"tests/test_parser.py::test_macro_call_two_args[{x:",
"tests/test_parser.py::test_macro_call_two_args[(x,y)-True]",
"tests/test_parser.py::test_macro_call_two_args[(x,y)-import",
"tests/test_parser.py::test_macro_call_two_args[(x,y)-\"oh",
"tests/test_parser.py::test_macro_call_two_args[(x,y)-",
"tests/test_parser.py::test_macro_call_two_args[(x,y)-{x:",
"tests/test_parser.py::test_macro_call_two_args[(x,y)-{1,",
"tests/test_parser.py::test_macro_call_two_args[(x,y)-(x,",
"tests/test_parser.py::test_macro_call_two_args[(x,y)-g()]",
"tests/test_parser.py::test_macro_call_two_args[(x,y)-range(1,",
"tests/test_parser.py::test_macro_call_two_args[(x,y)-{}]",
"tests/test_parser.py::test_macro_call_two_args[(x,y)-[1,",
"tests/test_parser.py::test_macro_call_two_args[(x,y)-!(ls",
"tests/test_parser.py::test_macro_call_two_args[(x,y)-$(ls",
"tests/test_parser.py::test_macro_call_two_args[(x,y)-$[ls",
"tests/test_parser.py::test_macro_call_two_args[((x,",
"tests/test_parser.py::test_macro_call_two_args[range(10)-True]",
"tests/test_parser.py::test_macro_call_two_args[range(10)-import",
"tests/test_parser.py::test_macro_call_two_args[range(10)-\"oh",
"tests/test_parser.py::test_macro_call_two_args[range(10)-",
"tests/test_parser.py::test_macro_call_two_args[range(10)-{x:",
"tests/test_parser.py::test_macro_call_two_args[range(10)-{1,",
"tests/test_parser.py::test_macro_call_two_args[range(10)-(x,",
"tests/test_parser.py::test_macro_call_two_args[range(10)-g()]",
"tests/test_parser.py::test_macro_call_two_args[range(10)-range(1,",
"tests/test_parser.py::test_macro_call_two_args[range(10)-{}]",
"tests/test_parser.py::test_macro_call_two_args[range(10)-[1,",
"tests/test_parser.py::test_macro_call_two_args[range(10)-!(ls",
"tests/test_parser.py::test_macro_call_two_args[range(10)-$(ls",
"tests/test_parser.py::test_macro_call_two_args[range(10)-$[ls",
"tests/test_parser.py::test_macro_call_two_args[()-True]",
"tests/test_parser.py::test_macro_call_two_args[()-import",
"tests/test_parser.py::test_macro_call_two_args[()-\"oh",
"tests/test_parser.py::test_macro_call_two_args[()-",
"tests/test_parser.py::test_macro_call_two_args[()-{x:",
"tests/test_parser.py::test_macro_call_two_args[()-{1,",
"tests/test_parser.py::test_macro_call_two_args[()-(x,",
"tests/test_parser.py::test_macro_call_two_args[()-g()]",
"tests/test_parser.py::test_macro_call_two_args[()-range(1,",
"tests/test_parser.py::test_macro_call_two_args[()-{}]",
"tests/test_parser.py::test_macro_call_two_args[()-[1,",
"tests/test_parser.py::test_macro_call_two_args[()-!(ls",
"tests/test_parser.py::test_macro_call_two_args[()-$(ls",
"tests/test_parser.py::test_macro_call_two_args[()-$[ls",
"tests/test_parser.py::test_macro_call_two_args[[]-True]",
"tests/test_parser.py::test_macro_call_two_args[[]-import",
"tests/test_parser.py::test_macro_call_two_args[[]-\"oh",
"tests/test_parser.py::test_macro_call_two_args[[]-",
"tests/test_parser.py::test_macro_call_two_args[[]-{x:",
"tests/test_parser.py::test_macro_call_two_args[[]-{1,",
"tests/test_parser.py::test_macro_call_two_args[[]-(x,",
"tests/test_parser.py::test_macro_call_two_args[[]-g()]",
"tests/test_parser.py::test_macro_call_two_args[[]-range(1,",
"tests/test_parser.py::test_macro_call_two_args[[]-{}]",
"tests/test_parser.py::test_macro_call_two_args[[]-[1,",
"tests/test_parser.py::test_macro_call_two_args[[]-!(ls",
"tests/test_parser.py::test_macro_call_two_args[[]-$(ls",
"tests/test_parser.py::test_macro_call_two_args[[]-$[ls",
"tests/test_parser.py::test_macro_call_two_args[@(x)-True]",
"tests/test_parser.py::test_macro_call_two_args[@(x)-import",
"tests/test_parser.py::test_macro_call_two_args[@(x)-\"oh",
"tests/test_parser.py::test_macro_call_two_args[@(x)-",
"tests/test_parser.py::test_macro_call_two_args[@(x)-{x:",
"tests/test_parser.py::test_macro_call_two_args[@(x)-{1,",
"tests/test_parser.py::test_macro_call_two_args[@(x)-(x,",
"tests/test_parser.py::test_macro_call_two_args[@(x)-g()]",
"tests/test_parser.py::test_macro_call_two_args[@(x)-range(1,",
"tests/test_parser.py::test_macro_call_two_args[@(x)-{}]",
"tests/test_parser.py::test_macro_call_two_args[@(x)-[1,",
"tests/test_parser.py::test_macro_call_two_args[@(x)-!(ls",
"tests/test_parser.py::test_macro_call_two_args[@(x)-$(ls",
"tests/test_parser.py::test_macro_call_two_args[@(x)-$[ls",
"tests/test_parser.py::test_macro_call_two_args[![ls",
"tests/test_parser.py::test_macro_call_two_args[${x",
"tests/test_parser.py::test_macro_call_two_args[@$(which",
"tests/test_parser.py::test_macro_call_three_args[x-True-None]",
"tests/test_parser.py::test_macro_call_three_args[x-True-\"oh",
"tests/test_parser.py::test_macro_call_three_args[x-True-if",
"tests/test_parser.py::test_macro_call_three_args[x-True-{1,",
"tests/test_parser.py::test_macro_call_three_args[x-True-((x,",
"tests/test_parser.py::test_macro_call_three_args[x-True-range(1,",
"tests/test_parser.py::test_macro_call_three_args[x-True-[]]",
"tests/test_parser.py::test_macro_call_three_args[x-True-!(ls",
"tests/test_parser.py::test_macro_call_three_args[x-True-${x",
"tests/test_parser.py::test_macro_call_three_args[x-x=10-None]",
"tests/test_parser.py::test_macro_call_three_args[x-x=10-\"oh",
"tests/test_parser.py::test_macro_call_three_args[x-x=10-if",
"tests/test_parser.py::test_macro_call_three_args[x-x=10-{1,",
"tests/test_parser.py::test_macro_call_three_args[x-x=10-((x,",
"tests/test_parser.py::test_macro_call_three_args[x-x=10-range(1,",
"tests/test_parser.py::test_macro_call_three_args[x-x=10-[]]",
"tests/test_parser.py::test_macro_call_three_args[x-x=10-!(ls",
"tests/test_parser.py::test_macro_call_three_args[x-x=10-${x",
"tests/test_parser.py::test_macro_call_three_args[x-",
"tests/test_parser.py::test_macro_call_three_args[x-{x:",
"tests/test_parser.py::test_macro_call_three_args[x-(x,",
"tests/test_parser.py::test_macro_call_three_args[x-range(10)-None]",
"tests/test_parser.py::test_macro_call_three_args[x-range(10)-\"oh",
"tests/test_parser.py::test_macro_call_three_args[x-range(10)-if",
"tests/test_parser.py::test_macro_call_three_args[x-range(10)-{1,",
"tests/test_parser.py::test_macro_call_three_args[x-range(10)-((x,",
"tests/test_parser.py::test_macro_call_three_args[x-range(10)-range(1,",
"tests/test_parser.py::test_macro_call_three_args[x-range(10)-[]]",
"tests/test_parser.py::test_macro_call_three_args[x-range(10)-!(ls",
"tests/test_parser.py::test_macro_call_three_args[x-range(10)-${x",
"tests/test_parser.py::test_macro_call_three_args[x-{}-None]",
"tests/test_parser.py::test_macro_call_three_args[x-{}-\"oh",
"tests/test_parser.py::test_macro_call_three_args[x-{}-if",
"tests/test_parser.py::test_macro_call_three_args[x-{}-{1,",
"tests/test_parser.py::test_macro_call_three_args[x-{}-((x,",
"tests/test_parser.py::test_macro_call_three_args[x-{}-range(1,",
"tests/test_parser.py::test_macro_call_three_args[x-{}-[]]",
"tests/test_parser.py::test_macro_call_three_args[x-{}-!(ls",
"tests/test_parser.py::test_macro_call_three_args[x-{}-${x",
"tests/test_parser.py::test_macro_call_three_args[x-@(x)-None]",
"tests/test_parser.py::test_macro_call_three_args[x-@(x)-\"oh",
"tests/test_parser.py::test_macro_call_three_args[x-@(x)-if",
"tests/test_parser.py::test_macro_call_three_args[x-@(x)-{1,",
"tests/test_parser.py::test_macro_call_three_args[x-@(x)-((x,",
"tests/test_parser.py::test_macro_call_three_args[x-@(x)-range(1,",
"tests/test_parser.py::test_macro_call_three_args[x-@(x)-[]]",
"tests/test_parser.py::test_macro_call_three_args[x-@(x)-!(ls",
"tests/test_parser.py::test_macro_call_three_args[x-@(x)-${x",
"tests/test_parser.py::test_macro_call_three_args[x-$(ls",
"tests/test_parser.py::test_macro_call_three_args[x-@$(which",
"tests/test_parser.py::test_macro_call_three_args[import",
"tests/test_parser.py::test_macro_call_three_args[...-True-None]",
"tests/test_parser.py::test_macro_call_three_args[...-True-\"oh",
"tests/test_parser.py::test_macro_call_three_args[...-True-if",
"tests/test_parser.py::test_macro_call_three_args[...-True-{1,",
"tests/test_parser.py::test_macro_call_three_args[...-True-((x,",
"tests/test_parser.py::test_macro_call_three_args[...-True-range(1,",
"tests/test_parser.py::test_macro_call_three_args[...-True-[]]",
"tests/test_parser.py::test_macro_call_three_args[...-True-!(ls",
"tests/test_parser.py::test_macro_call_three_args[...-True-${x",
"tests/test_parser.py::test_macro_call_three_args[...-x=10-None]",
"tests/test_parser.py::test_macro_call_three_args[...-x=10-\"oh",
"tests/test_parser.py::test_macro_call_three_args[...-x=10-if",
"tests/test_parser.py::test_macro_call_three_args[...-x=10-{1,",
"tests/test_parser.py::test_macro_call_three_args[...-x=10-((x,",
"tests/test_parser.py::test_macro_call_three_args[...-x=10-range(1,",
"tests/test_parser.py::test_macro_call_three_args[...-x=10-[]]",
"tests/test_parser.py::test_macro_call_three_args[...-x=10-!(ls",
"tests/test_parser.py::test_macro_call_three_args[...-x=10-${x",
"tests/test_parser.py::test_macro_call_three_args[...-",
"tests/test_parser.py::test_macro_call_three_args[...-{x:",
"tests/test_parser.py::test_macro_call_three_args[...-(x,",
"tests/test_parser.py::test_macro_call_three_args[...-range(10)-None]",
"tests/test_parser.py::test_macro_call_three_args[...-range(10)-\"oh",
"tests/test_parser.py::test_macro_call_three_args[...-range(10)-if",
"tests/test_parser.py::test_macro_call_three_args[...-range(10)-{1,",
"tests/test_parser.py::test_macro_call_three_args[...-range(10)-((x,",
"tests/test_parser.py::test_macro_call_three_args[...-range(10)-range(1,",
"tests/test_parser.py::test_macro_call_three_args[...-range(10)-[]]",
"tests/test_parser.py::test_macro_call_three_args[...-range(10)-!(ls",
"tests/test_parser.py::test_macro_call_three_args[...-range(10)-${x",
"tests/test_parser.py::test_macro_call_three_args[...-{}-None]",
"tests/test_parser.py::test_macro_call_three_args[...-{}-\"oh",
"tests/test_parser.py::test_macro_call_three_args[...-{}-if",
"tests/test_parser.py::test_macro_call_three_args[...-{}-{1,",
"tests/test_parser.py::test_macro_call_three_args[...-{}-((x,",
"tests/test_parser.py::test_macro_call_three_args[...-{}-range(1,",
"tests/test_parser.py::test_macro_call_three_args[...-{}-[]]",
"tests/test_parser.py::test_macro_call_three_args[...-{}-!(ls",
"tests/test_parser.py::test_macro_call_three_args[...-{}-${x",
"tests/test_parser.py::test_macro_call_three_args[...-@(x)-None]",
"tests/test_parser.py::test_macro_call_three_args[...-@(x)-\"oh",
"tests/test_parser.py::test_macro_call_three_args[...-@(x)-if",
"tests/test_parser.py::test_macro_call_three_args[...-@(x)-{1,",
"tests/test_parser.py::test_macro_call_three_args[...-@(x)-((x,",
"tests/test_parser.py::test_macro_call_three_args[...-@(x)-range(1,",
"tests/test_parser.py::test_macro_call_three_args[...-@(x)-[]]",
"tests/test_parser.py::test_macro_call_three_args[...-@(x)-!(ls",
"tests/test_parser.py::test_macro_call_three_args[...-@(x)-${x",
"tests/test_parser.py::test_macro_call_three_args[...-$(ls",
"tests/test_parser.py::test_macro_call_three_args[...-@$(which",
"tests/test_parser.py::test_macro_call_three_args[{x:",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-True-None]",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-True-\"oh",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-True-if",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-True-{1,",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-True-((x,",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-True-range(1,",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-True-[]]",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-True-!(ls",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-True-${x",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-x=10-None]",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-x=10-\"oh",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-x=10-if",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-x=10-{1,",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-x=10-((x,",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-x=10-range(1,",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-x=10-[]]",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-x=10-!(ls",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-x=10-${x",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-{x:",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-(x,",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-range(10)-None]",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-range(10)-\"oh",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-range(10)-if",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-range(10)-{1,",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-range(10)-((x,",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-range(10)-range(1,",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-range(10)-[]]",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-range(10)-!(ls",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-range(10)-${x",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-{}-None]",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-{}-\"oh",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-{}-if",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-{}-{1,",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-{}-((x,",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-{}-range(1,",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-{}-[]]",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-{}-!(ls",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-{}-${x",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-@(x)-None]",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-@(x)-\"oh",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-@(x)-if",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-@(x)-{1,",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-@(x)-((x,",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-@(x)-range(1,",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-@(x)-[]]",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-@(x)-!(ls",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-@(x)-${x",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-$(ls",
"tests/test_parser.py::test_macro_call_three_args[(x,y)-@$(which",
"tests/test_parser.py::test_macro_call_three_args[g()-True-None]",
"tests/test_parser.py::test_macro_call_three_args[g()-True-\"oh",
"tests/test_parser.py::test_macro_call_three_args[g()-True-if",
"tests/test_parser.py::test_macro_call_three_args[g()-True-{1,",
"tests/test_parser.py::test_macro_call_three_args[g()-True-((x,",
"tests/test_parser.py::test_macro_call_three_args[g()-True-range(1,",
"tests/test_parser.py::test_macro_call_three_args[g()-True-[]]",
"tests/test_parser.py::test_macro_call_three_args[g()-True-!(ls",
"tests/test_parser.py::test_macro_call_three_args[g()-True-${x",
"tests/test_parser.py::test_macro_call_three_args[g()-x=10-None]",
"tests/test_parser.py::test_macro_call_three_args[g()-x=10-\"oh",
"tests/test_parser.py::test_macro_call_three_args[g()-x=10-if",
"tests/test_parser.py::test_macro_call_three_args[g()-x=10-{1,",
"tests/test_parser.py::test_macro_call_three_args[g()-x=10-((x,",
"tests/test_parser.py::test_macro_call_three_args[g()-x=10-range(1,",
"tests/test_parser.py::test_macro_call_three_args[g()-x=10-[]]",
"tests/test_parser.py::test_macro_call_three_args[g()-x=10-!(ls",
"tests/test_parser.py::test_macro_call_three_args[g()-x=10-${x",
"tests/test_parser.py::test_macro_call_three_args[g()-",
"tests/test_parser.py::test_macro_call_three_args[g()-{x:",
"tests/test_parser.py::test_macro_call_three_args[g()-(x,",
"tests/test_parser.py::test_macro_call_three_args[g()-range(10)-None]",
"tests/test_parser.py::test_macro_call_three_args[g()-range(10)-\"oh",
"tests/test_parser.py::test_macro_call_three_args[g()-range(10)-if",
"tests/test_parser.py::test_macro_call_three_args[g()-range(10)-{1,",
"tests/test_parser.py::test_macro_call_three_args[g()-range(10)-((x,",
"tests/test_parser.py::test_macro_call_three_args[g()-range(10)-range(1,",
"tests/test_parser.py::test_macro_call_three_args[g()-range(10)-[]]",
"tests/test_parser.py::test_macro_call_three_args[g()-range(10)-!(ls",
"tests/test_parser.py::test_macro_call_three_args[g()-range(10)-${x",
"tests/test_parser.py::test_macro_call_three_args[g()-{}-None]",
"tests/test_parser.py::test_macro_call_three_args[g()-{}-\"oh",
"tests/test_parser.py::test_macro_call_three_args[g()-{}-if",
"tests/test_parser.py::test_macro_call_three_args[g()-{}-{1,",
"tests/test_parser.py::test_macro_call_three_args[g()-{}-((x,",
"tests/test_parser.py::test_macro_call_three_args[g()-{}-range(1,",
"tests/test_parser.py::test_macro_call_three_args[g()-{}-[]]",
"tests/test_parser.py::test_macro_call_three_args[g()-{}-!(ls",
"tests/test_parser.py::test_macro_call_three_args[g()-{}-${x",
"tests/test_parser.py::test_macro_call_three_args[g()-@(x)-None]",
"tests/test_parser.py::test_macro_call_three_args[g()-@(x)-\"oh",
"tests/test_parser.py::test_macro_call_three_args[g()-@(x)-if",
"tests/test_parser.py::test_macro_call_three_args[g()-@(x)-{1,",
"tests/test_parser.py::test_macro_call_three_args[g()-@(x)-((x,",
"tests/test_parser.py::test_macro_call_three_args[g()-@(x)-range(1,",
"tests/test_parser.py::test_macro_call_three_args[g()-@(x)-[]]",
"tests/test_parser.py::test_macro_call_three_args[g()-@(x)-!(ls",
"tests/test_parser.py::test_macro_call_three_args[g()-@(x)-${x",
"tests/test_parser.py::test_macro_call_three_args[g()-$(ls",
"tests/test_parser.py::test_macro_call_three_args[g()-@$(which",
"tests/test_parser.py::test_macro_call_three_args[()-True-None]",
"tests/test_parser.py::test_macro_call_three_args[()-True-\"oh",
"tests/test_parser.py::test_macro_call_three_args[()-True-if",
"tests/test_parser.py::test_macro_call_three_args[()-True-{1,",
"tests/test_parser.py::test_macro_call_three_args[()-True-((x,",
"tests/test_parser.py::test_macro_call_three_args[()-True-range(1,",
"tests/test_parser.py::test_macro_call_three_args[()-True-[]]",
"tests/test_parser.py::test_macro_call_three_args[()-True-!(ls",
"tests/test_parser.py::test_macro_call_three_args[()-True-${x",
"tests/test_parser.py::test_macro_call_three_args[()-x=10-None]",
"tests/test_parser.py::test_macro_call_three_args[()-x=10-\"oh",
"tests/test_parser.py::test_macro_call_three_args[()-x=10-if",
"tests/test_parser.py::test_macro_call_three_args[()-x=10-{1,",
"tests/test_parser.py::test_macro_call_three_args[()-x=10-((x,",
"tests/test_parser.py::test_macro_call_three_args[()-x=10-range(1,",
"tests/test_parser.py::test_macro_call_three_args[()-x=10-[]]",
"tests/test_parser.py::test_macro_call_three_args[()-x=10-!(ls",
"tests/test_parser.py::test_macro_call_three_args[()-x=10-${x",
"tests/test_parser.py::test_macro_call_three_args[()-",
"tests/test_parser.py::test_macro_call_three_args[()-{x:",
"tests/test_parser.py::test_macro_call_three_args[()-(x,",
"tests/test_parser.py::test_macro_call_three_args[()-range(10)-None]",
"tests/test_parser.py::test_macro_call_three_args[()-range(10)-\"oh",
"tests/test_parser.py::test_macro_call_three_args[()-range(10)-if",
"tests/test_parser.py::test_macro_call_three_args[()-range(10)-{1,",
"tests/test_parser.py::test_macro_call_three_args[()-range(10)-((x,",
"tests/test_parser.py::test_macro_call_three_args[()-range(10)-range(1,",
"tests/test_parser.py::test_macro_call_three_args[()-range(10)-[]]",
"tests/test_parser.py::test_macro_call_three_args[()-range(10)-!(ls",
"tests/test_parser.py::test_macro_call_three_args[()-range(10)-${x",
"tests/test_parser.py::test_macro_call_three_args[()-{}-None]",
"tests/test_parser.py::test_macro_call_three_args[()-{}-\"oh",
"tests/test_parser.py::test_macro_call_three_args[()-{}-if",
"tests/test_parser.py::test_macro_call_three_args[()-{}-{1,",
"tests/test_parser.py::test_macro_call_three_args[()-{}-((x,",
"tests/test_parser.py::test_macro_call_three_args[()-{}-range(1,",
"tests/test_parser.py::test_macro_call_three_args[()-{}-[]]",
"tests/test_parser.py::test_macro_call_three_args[()-{}-!(ls",
"tests/test_parser.py::test_macro_call_three_args[()-{}-${x",
"tests/test_parser.py::test_macro_call_three_args[()-@(x)-None]",
"tests/test_parser.py::test_macro_call_three_args[()-@(x)-\"oh",
"tests/test_parser.py::test_macro_call_three_args[()-@(x)-if",
"tests/test_parser.py::test_macro_call_three_args[()-@(x)-{1,",
"tests/test_parser.py::test_macro_call_three_args[()-@(x)-((x,",
"tests/test_parser.py::test_macro_call_three_args[()-@(x)-range(1,",
"tests/test_parser.py::test_macro_call_three_args[()-@(x)-[]]",
"tests/test_parser.py::test_macro_call_three_args[()-@(x)-!(ls",
"tests/test_parser.py::test_macro_call_three_args[()-@(x)-${x",
"tests/test_parser.py::test_macro_call_three_args[()-$(ls",
"tests/test_parser.py::test_macro_call_three_args[()-@$(which",
"tests/test_parser.py::test_macro_call_three_args[[1,",
"tests/test_parser.py::test_macro_call_three_args[![ls",
"tests/test_parser.py::test_macro_call_three_args[$[ls",
"tests/test_parser.py::test_macro_call_one_trailing[x]",
"tests/test_parser.py::test_macro_call_one_trailing[True]",
"tests/test_parser.py::test_macro_call_one_trailing[None]",
"tests/test_parser.py::test_macro_call_one_trailing[import",
"tests/test_parser.py::test_macro_call_one_trailing[x=10]",
"tests/test_parser.py::test_macro_call_one_trailing[\"oh",
"tests/test_parser.py::test_macro_call_one_trailing[...]",
"tests/test_parser.py::test_macro_call_one_trailing[",
"tests/test_parser.py::test_macro_call_one_trailing[if",
"tests/test_parser.py::test_macro_call_one_trailing[{x:",
"tests/test_parser.py::test_macro_call_one_trailing[{1,",
"tests/test_parser.py::test_macro_call_one_trailing[(x,y)]",
"tests/test_parser.py::test_macro_call_one_trailing[(x,",
"tests/test_parser.py::test_macro_call_one_trailing[((x,",
"tests/test_parser.py::test_macro_call_one_trailing[g()]",
"tests/test_parser.py::test_macro_call_one_trailing[range(10)]",
"tests/test_parser.py::test_macro_call_one_trailing[range(1,",
"tests/test_parser.py::test_macro_call_one_trailing[()]",
"tests/test_parser.py::test_macro_call_one_trailing[{}]",
"tests/test_parser.py::test_macro_call_one_trailing[[]]",
"tests/test_parser.py::test_macro_call_one_trailing[[1,",
"tests/test_parser.py::test_macro_call_one_trailing[@(x)]",
"tests/test_parser.py::test_macro_call_one_trailing[!(ls",
"tests/test_parser.py::test_macro_call_one_trailing[![ls",
"tests/test_parser.py::test_macro_call_one_trailing[$(ls",
"tests/test_parser.py::test_macro_call_one_trailing[${x",
"tests/test_parser.py::test_macro_call_one_trailing[$[ls",
"tests/test_parser.py::test_macro_call_one_trailing[@$(which",
"tests/test_parser.py::test_macro_call_one_trailing_space[x]",
"tests/test_parser.py::test_macro_call_one_trailing_space[True]",
"tests/test_parser.py::test_macro_call_one_trailing_space[None]",
"tests/test_parser.py::test_macro_call_one_trailing_space[import",
"tests/test_parser.py::test_macro_call_one_trailing_space[x=10]",
"tests/test_parser.py::test_macro_call_one_trailing_space[\"oh",
"tests/test_parser.py::test_macro_call_one_trailing_space[...]",
"tests/test_parser.py::test_macro_call_one_trailing_space[",
"tests/test_parser.py::test_macro_call_one_trailing_space[if",
"tests/test_parser.py::test_macro_call_one_trailing_space[{x:",
"tests/test_parser.py::test_macro_call_one_trailing_space[{1,",
"tests/test_parser.py::test_macro_call_one_trailing_space[(x,y)]",
"tests/test_parser.py::test_macro_call_one_trailing_space[(x,",
"tests/test_parser.py::test_macro_call_one_trailing_space[((x,",
"tests/test_parser.py::test_macro_call_one_trailing_space[g()]",
"tests/test_parser.py::test_macro_call_one_trailing_space[range(10)]",
"tests/test_parser.py::test_macro_call_one_trailing_space[range(1,",
"tests/test_parser.py::test_macro_call_one_trailing_space[()]",
"tests/test_parser.py::test_macro_call_one_trailing_space[{}]",
"tests/test_parser.py::test_macro_call_one_trailing_space[[]]",
"tests/test_parser.py::test_macro_call_one_trailing_space[[1,",
"tests/test_parser.py::test_macro_call_one_trailing_space[@(x)]",
"tests/test_parser.py::test_macro_call_one_trailing_space[!(ls",
"tests/test_parser.py::test_macro_call_one_trailing_space[![ls",
"tests/test_parser.py::test_macro_call_one_trailing_space[$(ls",
"tests/test_parser.py::test_macro_call_one_trailing_space[${x",
"tests/test_parser.py::test_macro_call_one_trailing_space[$[ls",
"tests/test_parser.py::test_macro_call_one_trailing_space[@$(which",
"tests/test_parser.py::test_empty_subprocbang[echo!-!(-)]",
"tests/test_parser.py::test_empty_subprocbang[echo!-$(-)]",
"tests/test_parser.py::test_empty_subprocbang[echo!-![-]]",
"tests/test_parser.py::test_empty_subprocbang[echo!-$[-]]",
"tests/test_parser.py::test_empty_subprocbang[echo",
"tests/test_parser.py::test_single_subprocbang[echo!x-!(-)]",
"tests/test_parser.py::test_single_subprocbang[echo!x-$(-)]",
"tests/test_parser.py::test_single_subprocbang[echo!x-![-]]",
"tests/test_parser.py::test_single_subprocbang[echo!x-$[-]]",
"tests/test_parser.py::test_single_subprocbang[echo",
"tests/test_parser.py::test_arg_single_subprocbang[echo",
"tests/test_parser.py::test_arg_single_subprocbang_nested[echo",
"tests/test_parser.py::test_many_subprocbang[echo!x",
"tests/test_parser.py::test_many_subprocbang[echo",
"tests/test_parser.py::test_many_subprocbang[timeit!",
"tests/test_parser.py::test_many_subprocbang[timeit!!!!-!(-)]",
"tests/test_parser.py::test_many_subprocbang[timeit!!!!-$(-)]",
"tests/test_parser.py::test_many_subprocbang[timeit!!!!-![-]]",
"tests/test_parser.py::test_many_subprocbang[timeit!!!!-$[-]]",
"tests/test_parser.py::test_many_subprocbang[timeit!!(ls)-!(-)]",
"tests/test_parser.py::test_many_subprocbang[timeit!!(ls)-$(-)]",
"tests/test_parser.py::test_many_subprocbang[timeit!!(ls)-![-]]",
"tests/test_parser.py::test_many_subprocbang[timeit!!(ls)-$[-]]",
"tests/test_parser.py::test_many_subprocbang[timeit!\"!)\"-!(-)]",
"tests/test_parser.py::test_many_subprocbang[timeit!\"!)\"-$(-)]",
"tests/test_parser.py::test_many_subprocbang[timeit!\"!)\"-![-]]",
"tests/test_parser.py::test_many_subprocbang[timeit!\"!)\"-$[-]]",
"tests/test_parser.py::test_withbang_single_suite[pass\\n]",
"tests/test_parser.py::test_withbang_single_suite[x",
"tests/test_parser.py::test_withbang_single_suite[export",
"tests/test_parser.py::test_withbang_single_suite[with",
"tests/test_parser.py::test_withbang_as_single_suite[pass\\n]",
"tests/test_parser.py::test_withbang_as_single_suite[x",
"tests/test_parser.py::test_withbang_as_single_suite[export",
"tests/test_parser.py::test_withbang_as_single_suite[with",
"tests/test_parser.py::test_withbang_single_suite_trailing[pass\\n]",
"tests/test_parser.py::test_withbang_single_suite_trailing[x",
"tests/test_parser.py::test_withbang_single_suite_trailing[export",
"tests/test_parser.py::test_withbang_single_suite_trailing[with",
"tests/test_parser.py::test_withbang_single_simple[pass]",
"tests/test_parser.py::test_withbang_single_simple[x",
"tests/test_parser.py::test_withbang_single_simple[export",
"tests/test_parser.py::test_withbang_single_simple[[1,\\n",
"tests/test_parser.py::test_withbang_single_simple_opt[pass]",
"tests/test_parser.py::test_withbang_single_simple_opt[x",
"tests/test_parser.py::test_withbang_single_simple_opt[export",
"tests/test_parser.py::test_withbang_single_simple_opt[[1,\\n",
"tests/test_parser.py::test_withbang_as_many_suite[pass\\n]",
"tests/test_parser.py::test_withbang_as_many_suite[x",
"tests/test_parser.py::test_withbang_as_many_suite[export",
"tests/test_parser.py::test_withbang_as_many_suite[with",
"tests/test_parser.py::test_subproc_raw_str_literal",
"tests/test_parser.py::test_syntax_error_del_literal",
"tests/test_parser.py::test_syntax_error_del_constant",
"tests/test_parser.py::test_syntax_error_del_emptytuple",
"tests/test_parser.py::test_syntax_error_del_call",
"tests/test_parser.py::test_syntax_error_del_lambda",
"tests/test_parser.py::test_syntax_error_del_ifexp",
"tests/test_parser.py::test_syntax_error_del_comps[[i",
"tests/test_parser.py::test_syntax_error_del_comps[{i",
"tests/test_parser.py::test_syntax_error_del_comps[(i",
"tests/test_parser.py::test_syntax_error_del_comps[{k:v",
"tests/test_parser.py::test_syntax_error_del_ops[x",
"tests/test_parser.py::test_syntax_error_del_ops[-x]",
"tests/test_parser.py::test_syntax_error_del_cmp[x",
"tests/test_parser.py::test_syntax_error_lonely_del",
"tests/test_parser.py::test_syntax_error_assign_literal",
"tests/test_parser.py::test_syntax_error_assign_constant",
"tests/test_parser.py::test_syntax_error_assign_emptytuple",
"tests/test_parser.py::test_syntax_error_assign_call",
"tests/test_parser.py::test_syntax_error_assign_lambda",
"tests/test_parser.py::test_syntax_error_assign_ifexp",
"tests/test_parser.py::test_syntax_error_assign_comps[[i",
"tests/test_parser.py::test_syntax_error_assign_comps[{i",
"tests/test_parser.py::test_syntax_error_assign_comps[(i",
"tests/test_parser.py::test_syntax_error_assign_comps[{k:v",
"tests/test_parser.py::test_syntax_error_assign_ops[x",
"tests/test_parser.py::test_syntax_error_assign_ops[-x]",
"tests/test_parser.py::test_syntax_error_assign_cmp[x",
"tests/test_parser.py::test_syntax_error_augassign_literal",
"tests/test_parser.py::test_syntax_error_augassign_constant",
"tests/test_parser.py::test_syntax_error_augassign_emptytuple",
"tests/test_parser.py::test_syntax_error_augassign_call",
"tests/test_parser.py::test_syntax_error_augassign_lambda",
"tests/test_parser.py::test_syntax_error_augassign_ifexp",
"tests/test_parser.py::test_syntax_error_augassign_comps[[i",
"tests/test_parser.py::test_syntax_error_augassign_comps[{i",
"tests/test_parser.py::test_syntax_error_augassign_comps[(i",
"tests/test_parser.py::test_syntax_error_augassign_comps[{k:v",
"tests/test_parser.py::test_syntax_error_augassign_ops[x",
"tests/test_parser.py::test_syntax_error_augassign_ops[-x]",
"tests/test_parser.py::test_syntax_error_augassign_cmp[x",
"tests/test_parser.py::test_syntax_error_bar_kwonlyargs",
"tests/test_parser.py::test_syntax_error_bar_posonlyargs",
"tests/test_parser.py::test_syntax_error_bar_posonlyargs_no_comma",
"tests/test_parser.py::test_syntax_error_nondefault_follows_default",
"tests/test_parser.py::test_syntax_error_posonly_nondefault_follows_default",
"tests/test_parser.py::test_syntax_error_lambda_nondefault_follows_default",
"tests/test_parser.py::test_syntax_error_lambda_posonly_nondefault_follows_default",
"tests/test_parser.py::test_syntax_error_literal_concat_different[-p]",
"tests/test_parser.py::test_syntax_error_literal_concat_different[-b]",
"tests/test_parser.py::test_syntax_error_literal_concat_different[p-]",
"tests/test_parser.py::test_syntax_error_literal_concat_different[p-b]",
"tests/test_parser.py::test_syntax_error_literal_concat_different[b-]",
"tests/test_parser.py::test_syntax_error_literal_concat_different[b-p]",
"tests/test_parser.py::test_get_repo_url",
"tests/test_parser.py::test_match_and_case_are_not_keywords"
] | {
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2024-04-08T19:37:32Z" | bsd-2-clause |
|
xuanxu__starmatrix-45 | diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index ddd32f0..e643d2d 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -4,6 +4,12 @@
Changelog
=========
+
+1.6.0 (unreleased)
+==================
+- Added Phi function from Strolger et al (2020)
+
+
1.5.3 (2021-07-14)
==================
- Better normalization rates and fits for Greggio DTDs
diff --git a/README.rst b/README.rst
index 89b1cea..14143c5 100644
--- a/README.rst
+++ b/README.rst
@@ -141,6 +141,11 @@ The ``dtd_sn`` param in the config file can be set to use any of the available D
:greggio-WDD1: DTD from model Wide DD 1 Gyr from Greggio, L. (2005)
:greggio-SDCH: DTD from model SD Chandra from Greggio, L. (2005)
:greggio-SDSCH: DTD from model SD sub-Chandra from Greggio, L. (2005)
+:strolger-fit1: Phi function from Strolger et al (2020) with (ξ, ω, 𝛼) = (10, 600, 220)
+:strolger-fit2: Phi function from Strolger et al (2020) with (ξ, ω, 𝛼) = (110, 1000, 2)
+:strolger-fit3: Phi function from Strolger et al (2020) with (ξ, ω, 𝛼) = (350, 1200, 20)
+:strolger-fit4: Phi function from Strolger et al (2020) with (ξ, ω, 𝛼) = (6000, 6000, -2)
+:strolger-optimized: Phi function from Strolger et al (2020) with (ξ, ω, 𝛼) = (-1518, 51, 50)
Supernovae yields
-----------------
@@ -215,3 +220,4 @@ Starmatrix is built upon a long list of previous works from different authors/pa
* *Gronow, S. et al.*, 2021, A&A
* *Mori, K. et al.*, 2018, ApJ, 863:176
* *Chen, X., Hu, L. & Wang, L.*, 2021, ApJ
+* *Strolger et al*, 2020, ApJ, Vol 890, 2. doi: 10.3847/1538-4357/ab6a97
diff --git a/docs/configuration.rst b/docs/configuration.rst
index f8d9052..a92aced 100644
--- a/docs/configuration.rst
+++ b/docs/configuration.rst
@@ -87,6 +87,11 @@ The ``dtd_sn`` param in the config file can be set to use any of the available D
:greggio-WDD1: DTD from model Wide DD 1 Gyr from Greggio, L. (2005)
:greggio-SDCH: DTD from model SD Chandra from Greggio, L. (2005)
:greggio-SDSCH: DTD from model SD sub-Chandra from Greggio, L. (2005)
+:strolger-fit1: Phi function from Strolger et al (2020) with (ξ, ω, 𝛼) = (10, 600, 220)
+:strolger-fit2: Phi function from Strolger et al (2020) with (ξ, ω, 𝛼) = (110, 1000, 2)
+:strolger-fit3: Phi function from Strolger et al (2020) with (ξ, ω, 𝛼) = (350, 1200, 20)
+:strolger-fit4: Phi function from Strolger et al (2020) with (ξ, ω, 𝛼) = (6000, 6000, -2)
+:strolger-optimized: Phi function from Strolger et al (2020) with (ξ, ω, 𝛼) = (-1518, 51, 50)
Supernovae yields
-----------------
diff --git a/docs/credits.rst b/docs/credits.rst
index f9dd88c..7f885a3 100644
--- a/docs/credits.rst
+++ b/docs/credits.rst
@@ -36,6 +36,7 @@ Starmatrix is built upon a long list of previous works from different authors/pa
* *Leung & Nomoto*, 2018, ApJ, Vol 861, Issue 2, Id 143
* *Leung & Nomoto*, 2020, ApJ, Vol 888, Issue 2, Id 80
* *Chen, X., Hu, L. & Wang, L.*, 2021, ApJ
+* *Strolger et al*, 2020, ApJ, Vol 890, 2. doi: 10.3847/1538-4357/ab6a97
License
-------
diff --git a/src/starmatrix/dtds.py b/src/starmatrix/dtds.py
index 5bfdda5..03943c7 100644
--- a/src/starmatrix/dtds.py
+++ b/src/starmatrix/dtds.py
@@ -7,10 +7,14 @@ Contains some predefined DTDs from different papers/authors:
* Maoz & Graur (2017)
* Castrillo et al (2020)
* Greggio, L. (2005)
+* Strolger et al. (2020)
"""
import math
+import scipy.integrate
+import starmatrix.constants as constants
+from functools import lru_cache
def select_dtd(option):
@@ -25,7 +29,12 @@ def select_dtd(option):
"greggio-WDD1": dtd_wide_dd_1,
"greggio-SDCH": dtd_sd_chandra,
"greggio-SDSCH": dtd_sd_subchandra,
- "chen": dtd_chen
+ "chen": dtd_chen,
+ "strolger-fit1": dtds_strolger["fit_1"],
+ "strolger-fit2": dtds_strolger["fit_2"],
+ "strolger-fit3": dtds_strolger["fit_3"],
+ "strolger-fit4": dtds_strolger["fit_4"],
+ "strolger-optimized": dtds_strolger["optimized"],
}
return dtds[option]
@@ -284,3 +293,57 @@ def dtd_chen(t):
rate = 2.069e-4 # [SN / Yr / M*]
return rate * dtd
+
+
+class Strolger:
+ def __init__(self, psi, omega, alpha):
+ self.psi = psi
+ self.omega = omega
+ self.alpha = alpha
+
+ def description(self):
+ return ("Delay Time Distributions (DTDs) from Strolger et al, "
+ "The Astrophysical Journal, 2020, 890, 2. "
+ "DOI: 10.3847/1538-4357/ab6a97")
+
+ def phi(self, t_gyrs):
+ t_myrs = t_gyrs * 1e3
+
+ u = t_myrs - self.psi
+ term_1 = (1/(self.omega * math.pi)) * math.exp((-(u**2))/(2*(self.omega**2)))
+
+ t_low = -math.inf
+ t_up = self.alpha*(u/self.omega)
+
+ if 12 < t_up:
+ term_2 = 2 * scipy.integrate.quad(self.term_2_f, t_low, 0)[0]
+ else:
+ term_2 = scipy.integrate.quad(self.term_2_f, t_low, t_up)[0]
+
+ return term_1 * term_2
+
+ def term_2_f(self, t_prime):
+ return math.exp(-math.pow(t_prime, 2)/2)
+
+ @lru_cache(maxsize=128)
+ def normalization_rate(self):
+ return self.efficiency() / self.phi_integrated()
+
+ def efficiency(self):
+ # SN/M* as Hubble-time-integrated production efficiency SN/Mo
+ return 1.03e-3
+
+ def phi_integrated(self):
+ return scipy.integrate.quad(self.phi, 0, constants.TOTAL_TIME)[0]
+
+ def at_time(self, t):
+ return self.normalization_rate() * self.phi(t)
+
+
+dtds_strolger = {
+ "fit_1": Strolger(10, 600, 220).at_time,
+ "fit_2": Strolger(110, 1000, 2).at_time,
+ "fit_3": Strolger(350, 1200, 20).at_time,
+ "fit_4": Strolger(6000, 6000, -2).at_time,
+ "optimized": Strolger(-1518, 51, 50).at_time,
+}
diff --git a/src/starmatrix/sample_input/params.yml b/src/starmatrix/sample_input/params.yml
index 35fa2c4..eb92429 100644
--- a/src/starmatrix/sample_input/params.yml
+++ b/src/starmatrix/sample_input/params.yml
@@ -54,6 +54,11 @@
# greggio-WDD1 = DTD from model Wide DD 1 Gyr from Greggio, L. (2005)
# greggio-SDCH = DTD from model SD Chandra from Greggio, L. (2005)
# greggio-SDSCH = DTD from model SD sub-Chandra from Greggio, L. (2005)
+# strolger-fit1 = Phi from Strolger et al (2020) with (ξ, ω, 𝛼) = (10, 600, 220)
+# strolger-fit2 = Phi from Strolger et al (2020) with (ξ, ω, 𝛼) = (110, 1000, 2)
+# strolger-fit3 = Phi from Strolger et al (2020) with (ξ, ω, 𝛼) = (350, 1200, 20)
+# strolger-fit4 = Phi from Strolger et al (2020) with (ξ, ω, 𝛼) = (6000, 6000, -2)
+# strolger-optimized = Phi from Strolger et al (2020) with (ξ, ω, 𝛼) = (-1518, 51, 50)
# ]
# sn_yields = [
diff --git a/src/starmatrix/settings.py b/src/starmatrix/settings.py
index cd22f91..8cceb63 100644
--- a/src/starmatrix/settings.py
+++ b/src/starmatrix/settings.py
@@ -34,7 +34,8 @@ default = {
valid_values = {
"imf": ["salpeter", "starburst", "chabrier", "ferrini", "kroupa", "miller_scalo", "maschberger"],
"dtd_sn": ["rlp", "maoz", "castrillo", "greggio", "chen", "greggio-CDD04", "greggio-CDD1",
- "greggio-WDD04", "greggio-WDD1", "greggio-SDCH", "greggio-SDSCH"],
+ "greggio-WDD04", "greggio-WDD1", "greggio-SDCH", "greggio-SDSCH",
+ "strolger-fit1", "strolger-fit2", "strolger-fit3", "strolger-fit4", "strolger-optimized"],
"sn_yields": ["iwa1998",
"sei2013",
"ln2020",
| xuanxu/starmatrix | b8f09d6799e9f08e0e9df4ce378c5578feb00999 | diff --git a/src/starmatrix/tests/dtds/test_strolger.py b/src/starmatrix/tests/dtds/test_strolger.py
new file mode 100644
index 0000000..b5c68ab
--- /dev/null
+++ b/src/starmatrix/tests/dtds/test_strolger.py
@@ -0,0 +1,26 @@
+import pytest
+from starmatrix.dtds import Strolger
+
+
+def test_parameters_initialization():
+ strolger = Strolger(1000, 2000, 3000)
+ assert strolger.psi == 1000
+ assert strolger.omega == 2000
+ assert strolger.alpha == 3000
+
+
+def test_has_description():
+ assert Strolger(10, 10, 10).description() is not None
+
+
+def test_is_normalized():
+ dtd = Strolger(6000, 6000, -2)
+ sample_t = 6
+ dtd_point = dtd.at_time(sample_t)
+ assert dtd_point > 0
+ assert dtd_point == dtd.phi(sample_t) * dtd.normalization_rate()
+
+
+def test_normalization_rate_uses_hubble_efficiency():
+ dtd = Strolger(6000, 6000, -2)
+ assert dtd.normalization_rate() == 1.03e-3 / dtd.phi_integrated()
diff --git a/src/starmatrix/tests/test_dtds.py b/src/starmatrix/tests/test_dtds.py
index 25cf0fc..5e60cca 100644
--- a/src/starmatrix/tests/test_dtds.py
+++ b/src/starmatrix/tests/test_dtds.py
@@ -14,6 +14,7 @@ from starmatrix.dtds import dtd_wide_dd_1
from starmatrix.dtds import dtd_sd_chandra
from starmatrix.dtds import dtd_sd_subchandra
from starmatrix.dtds import dtd_chen
+from starmatrix.dtds import dtds_strolger
@pytest.fixture
@@ -31,10 +32,13 @@ def test_dtds_presence(available_dtds):
def test_select_dtd(available_dtds):
dtds = [dtd_ruiz_lapuente, dtd_maoz_graur, dtd_castrillo, dtd_greggio, dtd_chen,
- dtd_close_dd_04, dtd_close_dd_1, dtd_wide_dd_04, dtd_wide_dd_1, dtd_sd_chandra, dtd_sd_subchandra]
+ dtd_close_dd_04, dtd_close_dd_1, dtd_wide_dd_04, dtd_wide_dd_1, dtd_sd_chandra, dtd_sd_subchandra,
+ dtds_strolger["fit_1"], dtds_strolger["fit_2"], dtds_strolger["fit_3"], dtds_strolger["fit_4"], dtds_strolger["optimized"]]
+
+ assert len(available_dtds) == len(dtds)
for i in range(len(available_dtds)):
- times = [0, 0.001, 0.04, 0.1, 0.4, 2, 9.] + list(np.random.rand(5)) + list(np.random.rand(5) * 9)
+ times = [0, 0.001, 0.04, 0.1, 0.4, 1, 2, 9.] + list(np.random.rand(5)) + list(np.random.rand(5) * 9)
for time in times:
assert select_dtd(available_dtds[i])(time) == dtds[i](time)
| Add Strolger's phi
In `Strolger et al, ApJ, 2020, 890, 2` there is a Phi function used to fit Delay Time Distributions by parameter optimization.
![Strolger](https://user-images.githubusercontent.com/6528/125192595-f15f2800-e248-11eb-9c24-59140d0e7d93.png)
Task: Add Phi with different parameter options to Starmatrix: the 4 fits for binary population synthesis analyses for SD scenarios, and the optimized solution.
![fits](https://user-images.githubusercontent.com/6528/125192551-c379e380-e248-11eb-8f08-474b9f74b741.png)
![params](https://user-images.githubusercontent.com/6528/125192586-e5736600-e248-11eb-8f7b-a4a89e7c8e68.png)
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/starmatrix/tests/dtds/test_strolger.py::test_parameters_initialization",
"src/starmatrix/tests/dtds/test_strolger.py::test_has_description",
"src/starmatrix/tests/dtds/test_strolger.py::test_is_normalized",
"src/starmatrix/tests/dtds/test_strolger.py::test_normalization_rate_uses_hubble_efficiency",
"src/starmatrix/tests/test_dtds.py::test_dtds_presence",
"src/starmatrix/tests/test_dtds.py::test_select_dtd",
"src/starmatrix/tests/test_dtds.py::test_no_negative_time_values",
"src/starmatrix/tests/test_dtds.py::test_dtd_correction_factor"
] | [] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_media",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-07-17T20:26:30Z" | mit |
|
y0-causal-inference__y0-12 | diff --git a/src/y0/dsl.py b/src/y0/dsl.py
index 148e047..6247e6a 100644
--- a/src/y0/dsl.py
+++ b/src/y0/dsl.py
@@ -15,8 +15,7 @@ __all__ = [
'Variable',
'Intervention',
'CounterfactualVariable',
- 'ConditionalProbability',
- 'JointProbability',
+ 'Distribution',
'P',
'Probability',
'Sum',
@@ -44,6 +43,9 @@ class _Mathable(ABC):
def to_latex(self) -> str:
"""Output this DSL object in the LaTeX string format."""
+ def _repr_latex_(self) -> str: # hack for auto-display of latex in jupyter notebook
+ return f'${self.to_latex()}$'
+
def __str__(self) -> str:
return self.to_text()
@@ -84,23 +86,36 @@ class Variable(_Mathable):
def __matmul__(self, variables: XList[Variable]) -> CounterfactualVariable:
return self.intervene(variables)
- def given(self, parents: XList[Variable]) -> ConditionalProbability:
+ def given(self, parents: Union[XList[Variable], Distribution]) -> Distribution:
"""Create a distribution in which this variable is conditioned on the given variable(s).
+ The new distribution is a Markov Kernel.
+
:param parents: A variable or list of variables to include as conditions in the new conditional distribution
:returns: A new conditional probability distribution
+ :raises TypeError: If a distribution is given as the parents that contains conditionals
.. note:: This function can be accessed with the or | operator.
"""
- return ConditionalProbability(
- child=self,
- parents=_upgrade_variables(parents),
- )
-
- def __or__(self, parents: XList[Variable]) -> ConditionalProbability:
+ if not isinstance(parents, Distribution):
+ return Distribution(
+ children=[self],
+ parents=_upgrade_variables(parents),
+ )
+ elif parents.is_conditioned():
+ raise TypeError('can not be given a distribution that has conditionals')
+ else:
+ # The parents variable is actually a Distribution instance with no parents,
+ # so its children become the parents for the new Markov Kernel distribution
+ return Distribution(
+ children=[self],
+ parents=parents.children, # don't think about this too hard
+ )
+
+ def __or__(self, parents: XList[Variable]) -> Distribution:
return self.given(parents)
- def joint(self, children: XList[Variable]) -> JointProbability:
+ def joint(self, children: XList[Variable]) -> Distribution:
"""Create a joint distribution between this variable and the given variable(s).
:param children: The variable(s) for use with this variable in a joint distribution
@@ -108,9 +123,11 @@ class Variable(_Mathable):
.. note:: This function can be accessed with the and & operator.
"""
- return JointProbability([self, *_upgrade_variables(children)])
+ return Distribution(
+ children=[self, *_upgrade_variables(children)],
+ )
- def __and__(self, children: XList[Variable]) -> JointProbability:
+ def __and__(self, children: XList[Variable]) -> Distribution:
return self.joint(children)
def invert(self) -> Intervention:
@@ -211,82 +228,97 @@ class CounterfactualVariable(Variable):
@dataclass
-class JointProbability(_Mathable):
- """A joint probability distribution over several variables."""
+class Distribution(_Mathable):
+ """A general distribution over several child variables, conditioned by several parents."""
children: List[Variable]
+ parents: List[Variable] = field(default_factory=list)
+
+ def __post_init__(self):
+ if isinstance(self.children, Variable):
+ self.children = [self.children]
+ if not self.children:
+ raise ValueError('distribution must have at least one child')
+ if isinstance(self.parents, Variable):
+ self.parents = [self.parents]
def to_text(self) -> str:
- """Output this joint probability distribution in the internal string format."""
- return ','.join(child.to_text() for child in self.children)
+ """Output this distribution in the internal string format."""
+ children = ','.join(child.to_text() for child in self.children)
+ if self.parents:
+ parents = ','.join(parent.to_text() for parent in self.parents)
+ return f'{children}|{parents}'
+ else:
+ return children
def to_latex(self) -> str:
- """Output this joint probability distribution in the LaTeX string format."""
- return ','.join(child.to_latex() for child in self.children)
+ """Output this distribution in the LaTeX string format."""
+ children = ','.join(child.to_latex() for child in self.children)
+ parents = ','.join(parent.to_latex() for parent in self.parents)
+ return f'{children}|{parents}'
+
+ def is_conditioned(self) -> bool:
+ """Return if this distribution is conditioned."""
+ return 0 < len(self.parents)
- def joint(self, children: XList[Variable]) -> JointProbability:
- """Create a joint distribution between the variables in this distribution the given variable(s).
+ def is_markov_kernel(self) -> bool:
+ """Return if this distribution a markov kernel -> one child variable and one or more conditionals."""
+ return len(self.children) == 1
- :param children: The variable(s) with which this joint distribution is extended
- :returns: A new joint distribution over all previous and given variables.
+ def joint(self, children: XList[Variable]) -> Distribution:
+ """Create a new distribution including the given child variables.
+
+ :param children: The variable(s) with which this distribution's children are extended
+ :returns: A new distribution.
.. note:: This function can be accessed with the and & operator.
"""
- return JointProbability([
- *self.children,
- *_upgrade_variables(children),
- ])
+ return Distribution(
+ children=[*self.children, *_upgrade_variables(children)],
+ parents=self.parents,
+ )
- def __and__(self, children: XList[Variable]) -> JointProbability:
+ def __and__(self, children: XList[Variable]) -> Distribution:
return self.joint(children)
+ def given(self, parents: Union[XList[Variable], Distribution]) -> Distribution:
+ """Create a new mixed distribution additionally conditioned on the given parent variables.
-@dataclass
-class ConditionalProbability(_Mathable):
- """A conditional distribution over a single child variable and one or more parent conditional variables."""
-
- child: Variable
- parents: List[Variable]
-
- def to_text(self) -> str:
- """Output this conditional probability distribution in the internal string format."""
- parents = ','.join(parent.to_text() for parent in self.parents)
- return f'{self.child.to_text()}|{parents}'
-
- def to_latex(self) -> str:
- """Output this conditional probability distribution in the LaTeX string format."""
- parents = ','.join(parent.to_latex() for parent in self.parents)
- return f'{self.child.to_latex()}|{parents}'
-
- def given(self, parents: XList[Variable]) -> ConditionalProbability:
- """Create a new conditional distribution with this distribution's children, parents, and the given parent(s).
-
- :param parents: A variable or list of variables to include as conditions in the new conditional distribution,
- in addition to the variables already in this conditional distribution
- :returns: A new conditional probability distribution
+ :param parents: The variable(s) with which this distribution's parents are extended
+ :returns: A new distribution
+ :raises TypeError: If a distribution is given as the parents that contains conditionals
.. note:: This function can be accessed with the or | operator.
"""
- return ConditionalProbability(
- child=self.child,
- parents=[*self.parents, *_upgrade_variables(parents)],
- )
-
- def __or__(self, parents: XList[Variable]) -> ConditionalProbability:
+ if not isinstance(parents, Distribution):
+ return Distribution(
+ children=self.children,
+ parents=[*self.parents, *_upgrade_variables(parents)],
+ )
+ elif parents.is_conditioned():
+ raise TypeError('can not be given a distribution that has conditionals')
+ else:
+ # The parents variable is actually a Distribution instance with no parents,
+ # so its children get appended as parents for the new mixed distribution
+ return Distribution(
+ children=self.children,
+ parents=[*self.parents, *parents.children], # don't think about this too hard
+ )
+
+ def __or__(self, parents: XList[Variable]) -> Distribution:
return self.given(parents)
class Expression(_Mathable, ABC):
"""The abstract class representing all expressions."""
- def _repr_latex_(self) -> str: # hack for auto-display of latex in jupyter notebook
- return f'${self.to_latex()}$'
-
+ @abstractmethod
def __mul__(self, other):
- raise NotImplementedError
+ pass
+ @abstractmethod
def __truediv__(self, other):
- raise NotImplementedError
+ pass
class Probability(Expression):
@@ -294,32 +326,36 @@ class Probability(Expression):
def __init__(
self,
- probability: Union[Variable, List[Variable], ConditionalProbability, JointProbability],
+ distribution: Union[Variable, List[Variable], Distribution],
*args: Variable,
) -> None:
"""Create a probability expression over the given variable(s) or distribution.
- :param probability: If given a :class:`ConditionalProbability` or :class:`JointProbability`,
- creates a probability expression directly over the distribution. If given variable or
- list of variables, conveniently creates a :class:`JointProbability` over the variable(s)
- first.
- :param args: If the first argument (``probability``) was given as a single variable, the
- ``args`` variadic argument can be used to specify a list of additiona variables.
+ :param distribution: If given a :class:`Distribution`, creates a probability expression
+ directly over the distribution. If given variable or list of variables, conveniently
+ creates a :class:`Distribtion` with the variable(s) as children.
+ :param args: If the first argument (``distribution``) was given as a single variable, the
+ ``args`` variadic argument can be used to specify a list of additional variables.
:raises ValueError: If varidic args are used incorrectly (i.e., in combination with a
- list of variables, :class:`ConditionalProbability`, or :class:`JointProbability`.
+ list of variables or :class:`Distribution`.
.. note:: This class is so commonly used, that it is aliased as :class:`P`.
- Creation with a :class:`ConditionalProbability`:
+ Creation with a conditional distribution:
>>> from y0.dsl import P, A, B
>>> P(A | B)
- Creation with a :class:`JointProbability`:
+ Creation with a joint distribution:
>>> from y0.dsl import P, A, B
>>> P(A & B)
+ Creation with a mixed joint/conditional distribution:
+
+ >>> from y0.dsl import P, A, B, C
+ >>> P(A & B | C)
+
Creation with a single :class:`Variable`:
>>> from y0.dsl import P, A
@@ -335,30 +371,30 @@ class Probability(Expression):
>>> from y0.dsl import P, A, B
>>> P(A, B)
"""
- if isinstance(probability, Variable):
+ if isinstance(distribution, Variable):
if not args:
- probability = [probability]
+ distribution = [distribution]
elif not all(isinstance(p, Variable) for p in args):
raise ValueError
else:
- probability = [probability, *args]
- if isinstance(probability, list):
- probability = JointProbability(probability)
- self.probability = probability
+ distribution = [distribution, *args]
+ if isinstance(distribution, list):
+ distribution = Distribution(children=distribution)
+ self.distribution = distribution
def to_text(self) -> str:
"""Output this probability in the internal string format."""
- return f'P({self.probability.to_text()})'
+ return f'P({self.distribution.to_text()})'
def to_latex(self) -> str:
"""Output this probability in the LaTeX string format."""
- return f'P({self.probability.to_latex()})'
+ return f'P({self.distribution.to_latex()})'
def __repr__(self):
- return f'P({repr(self.probability)})'
+ return f'P({repr(self.distribution)})'
def __eq__(self, other):
- return isinstance(other, Probability) and self.probability == other.probability
+ return isinstance(other, Probability) and self.distribution == other.distribution
def __mul__(self, other: Expression) -> Expression:
if isinstance(other, Product):
diff --git a/src/y0/parser_utils.py b/src/y0/parser_utils.py
index f460b57..3d03bf4 100644
--- a/src/y0/parser_utils.py
+++ b/src/y0/parser_utils.py
@@ -4,9 +4,7 @@
from pyparsing import Group, Optional, ParseResults, Suppress, Word, alphas, delimitedList
-from .dsl import (
- ConditionalProbability, CounterfactualVariable, Intervention, JointProbability, Probability, Variable,
-)
+from .dsl import (CounterfactualVariable, Distribution, Intervention, Probability, Variable)
__all__ = [
'probability_pe',
@@ -47,13 +45,9 @@ def _make_variable(_s, _l, tokens: ParseResults) -> Variable:
def _make_probability(_s, _l, tokens: ParseResults) -> Probability:
children, parents = tokens['children'].asList(), tokens['parents'].asList()
- if not parents:
- return Probability(JointProbability(children=children))
if not children:
raise ValueError
- if len(children) > 1:
- raise ValueError
- return Probability(ConditionalProbability(child=children[0], parents=parents))
+ return Probability(Distribution(children=children, parents=parents))
# The suffix "pe" refers to :class:`pyparsing.ParserElement`, which is the
| y0-causal-inference/y0 | c0b9789f73521e22c2dab116219fda4be4a6da05 | diff --git a/tests/test_dsl.py b/tests/test_dsl.py
index d7413c8..c3143c2 100644
--- a/tests/test_dsl.py
+++ b/tests/test_dsl.py
@@ -6,8 +6,8 @@ import itertools as itt
import unittest
from y0.dsl import (
- A, B, C, ConditionalProbability, CounterfactualVariable, D, Fraction, Intervention, JointProbability, P, Q, S, Sum,
- T, Variable, W, X, Y, Z,
+ A, B, C, CounterfactualVariable, D, Distribution, Fraction, Intervention, P, Q, S, Sum, T,
+ Variable, W, X, Y, Z,
)
V = Variable('V')
@@ -19,13 +19,18 @@ class TestDSL(unittest.TestCase):
def assert_text(self, s: str, expression):
"""Assert the expression when it is converted to a string."""
self.assertIsInstance(s, str)
- self.assertEqual(s, expression.to_text())
+ self.assertEqual(s, expression.to_text(), msg=f'Expression: {repr(expression)}')
def test_variable(self):
"""Test the variable DSL object."""
self.assert_text('A', Variable('A'))
self.assert_text('A', A) # shorthand for testing purposes
+ def test_stop_the_madness(self):
+ """Test that a variable can not be named "P"."""
+ with self.assertRaises(ValueError):
+ _ = Variable('P')
+
def test_intervention(self):
"""Test the invervention DSL object."""
self.assert_text('W*', Intervention('W', True))
@@ -70,10 +75,10 @@ class TestDSL(unittest.TestCase):
with self.subTest(a=a, b=b), self.assertRaises(ValueError):
Y @ Intervention('X', star=a) @ Intervention('X', star=b)
- def test_conditional(self):
- """Test the ConditionalProbability DSL object."""
+ def test_conditional_distribution(self):
+ """Test the :class:`Distribution` DSL object."""
# Normal instantiation
- self.assert_text('A|B', ConditionalProbability(A, [B]))
+ self.assert_text('A|B', Distribution(A, [B]))
# Instantiation with list-based operand to or | operator
self.assert_text('A|B', Variable('A') | [B])
@@ -97,29 +102,60 @@ class TestDSL(unittest.TestCase):
self.assert_text('Y_{W,X*}|B,C', Y @ W @ ~X | B | C)
self.assert_text('Y_{W,X*}|B_{Q*},C', Y @ W @ ~X | B @ Intervention('Q', True) | C)
- def test_conditional_probability(self):
- """Test generation of conditional probabilities."""
- self.assert_text('P(A|B)', P(ConditionalProbability(A, [B])))
- self.assert_text('P(A|B)', P(A | [B]))
- self.assert_text('P(A|B,C)', P(ConditionalProbability(A, [B]) | C))
- self.assert_text('P(A|B,C)', P(A | [B, C]))
- self.assert_text('P(A|B,C)', P(A | B | C))
-
- def test_joint(self):
+ def test_joint_distribution(self):
"""Test the JointProbability DSL object."""
- self.assert_text('A,B', JointProbability([A, B]))
+ self.assert_text('A,B', Distribution([A, B]))
self.assert_text('A,B', A & B)
- self.assert_text('A,B,C', JointProbability([A, B, C]))
+ self.assert_text('A,B,C', Distribution([A, B, C]))
self.assert_text('A,B,C', A & B & C)
- def test_joint_probability(self):
- """Test generation of joint probabilities."""
- # Shortcut for list building
+ def test_probability(self):
+ """Test generation of probabilities."""
+ # Make sure there are children
+ with self.assertRaises(ValueError):
+ Distribution([])
+
+ # Test markov kernels (AKA has only one child variable)
+ self.assert_text('P(A|B)', P(Distribution(A, [B])))
+ self.assert_text('P(A|B)', P(A | [B]))
+ self.assert_text('P(A|B,C)', P(Distribution(A, [B]) | C))
+ self.assert_text('P(A|B,C)', P(A | [B, C]))
+ self.assert_text('P(A|B,C)', P(A | B | C))
+ self.assert_text('P(A|B,C)', P(A | B & C))
+
+ # Test simple joint distributions
self.assert_text('P(A,B)', P([A, B]))
self.assert_text('P(A,B)', P(A, B))
self.assert_text('P(A,B)', P(A & B))
self.assert_text('P(A,B,C)', P(A & B & C))
+ # Test mixed with single conditional
+ self.assert_text('P(A,B|C)', P(Distribution([A, B], [C])))
+ self.assert_text('P(A,B|C)', P(Distribution([A, B], C)))
+ self.assert_text('P(A,B|C)', P(Distribution([A, B]) | C))
+ self.assert_text('P(A,B|C)', P(A & B | C))
+
+ # Test mixed with multiple conditionals
+ self.assert_text('P(A,B|C,D)', P(Distribution([A, B], [C, D])))
+ self.assert_text('P(A,B|C,D)', P(Distribution([A, B]) | C | D))
+ self.assert_text('P(A,B|C,D)', P(Distribution([A, B], [C]) | D))
+ self.assert_text('P(A,B|C,D)', P(A & B | C | D))
+ self.assert_text('P(A,B|C,D)', P(A & B | [C, D]))
+ self.assert_text('P(A,B|C,D)', P(A & B | Distribution([C, D])))
+ self.assert_text('P(A,B|C,D)', P(A & B | C & D))
+
+ def test_conditioning_errors(self):
+ """Test erroring on conditionals."""
+ for expression in [
+ Distribution(B, C),
+ Distribution([B, C], D),
+ Distribution([B, C], [D, W]),
+ ]:
+ with self.assertRaises(TypeError):
+ _ = A | expression
+ with self.assertRaises(TypeError):
+ _ = X & Y | expression
+
def test_sum(self):
"""Test the Sum DSL object."""
# Sum with no variables
| Unify joint and conditional probabilities | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_dsl.py::TestDSL::test_conditional_distribution",
"tests/test_dsl.py::TestDSL::test_conditioning_errors",
"tests/test_dsl.py::TestDSL::test_counterfactual_errors",
"tests/test_dsl.py::TestDSL::test_counterfactual_variable",
"tests/test_dsl.py::TestDSL::test_intervention",
"tests/test_dsl.py::TestDSL::test_jeremy",
"tests/test_dsl.py::TestDSL::test_joint_distribution",
"tests/test_dsl.py::TestDSL::test_probability",
"tests/test_dsl.py::TestDSL::test_stop_the_madness",
"tests/test_dsl.py::TestDSL::test_sum",
"tests/test_dsl.py::TestDSL::test_variable"
] | [] | {
"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
} | "2021-01-13T12:01:03Z" | mit |
|
y0-causal-inference__y0-51 | diff --git a/src/y0/mutate/canonicalize_expr.py b/src/y0/mutate/canonicalize_expr.py
index 61924c0..b5122f7 100644
--- a/src/y0/mutate/canonicalize_expr.py
+++ b/src/y0/mutate/canonicalize_expr.py
@@ -64,9 +64,6 @@ class Canonicalizer:
if isinstance(expression, Probability): # atomic
return self._canonicalize_probability(expression)
elif isinstance(expression, Sum):
- if isinstance(expression.expression, Probability): # also atomic
- return expression
-
return Sum(
expression=self.canonicalize(expression.expression),
ranges=expression.ranges,
| y0-causal-inference/y0 | 36b3a29d99065c0adca2aecdf28de77c8fdf53fa | diff --git a/tests/test_mutate/test_canonicalize.py b/tests/test_mutate/test_canonicalize.py
index 06ed32a..c76d878 100644
--- a/tests/test_mutate/test_canonicalize.py
+++ b/tests/test_mutate/test_canonicalize.py
@@ -108,13 +108,17 @@ class TestCanonicalize(unittest.TestCase):
self.assert_canonicalize(P(A & B | C), P(c1 & c2 | C), [A, B, C])
# Two conditions, C and D
for p1, p2 in itt.permutations([C, D]):
- self.assert_canonicalize(P(A & B | C | D), P(c1 & c2 | (p1, p2)), [A, B, C, D])
+ expected = P(A & B | C | D)
+ expression = P(c1 & c2 | (p1, p2))
+ ordering = [A, B, C, D]
+ self.assert_canonicalize(expected, expression, ordering)
+ self.assert_canonicalize(Sum(expected), Sum(expression), ordering)
for c1, c2, c3 in itt.permutations([A, B, C]):
self.assert_canonicalize(P(A, B, C), P(c1, c2, c3), [A, B, C])
for p1, p2, p3 in itt.permutations([X, Y, Z]):
- self.assert_canonicalize(
- P(A & B & C | (X, Y, Z)),
- P(c1 & c2 & c3 | (p1 & p2 & p3)),
- [A, B, C, X, Y, Z],
- )
+ expected = P(A & B & C | (X, Y, Z))
+ expression = P(c1 & c2 & c3 | (p1 & p2 & p3))
+ ordering = [A, B, C, X, Y, Z]
+ self.assert_canonicalize(expected, expression, ordering)
+ self.assert_canonicalize(Sum(expected), Sum(expression), ordering)
| Canonicalize does not work on Sum
```python
from y0.dsl import P, Sum, X, Y, Z, Product
from y0.mutate import canonicalize
expected = Sum[Z](P(Y,Z))
actual = Sum(P(Z, Y),[Z])
expected_vars = expected.get_variables()
ordering = list(expected_vars)
expected_canonical = canonicalize(expected, ordering)
actual_canonical = canonicalize(actual, ordering)
print(f"Expected: {expected_canonical}\nActual: {actual_canonical}")
```
```
Expected: [ sum_{Z} P(Y,Z) ]
Actual: [ sum_{Z} P(Z,Y) ]
```
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_mutate/test_canonicalize.py::TestCanonicalize::test_non_markov"
] | [
"tests/test_mutate/test_canonicalize.py::TestCanonicalize::test_atomic",
"tests/test_mutate/test_canonicalize.py::TestCanonicalize::test_derived_atomic",
"tests/test_mutate/test_canonicalize.py::TestCanonicalize::test_mixed"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2021-06-02T00:36:15Z" | mit |
|
yaml2sbml-dev__yaml2sbml-32 | diff --git a/yaml2sbml/__init__.py b/yaml2sbml/__init__.py
index 7795a69..e923ece 100644
--- a/yaml2sbml/__init__.py
+++ b/yaml2sbml/__init__.py
@@ -1,3 +1,3 @@
from yaml2sbml.yaml2sbml import yaml2sbml
-from yaml2sbml.yaml2PEtab import yaml2petab
+from yaml2sbml.yaml2PEtab import yaml2petab, validate_petab_tables
from yaml2sbml.yaml_validation import validate_yaml
diff --git a/yaml2sbml/yaml2PEtab.py b/yaml2sbml/yaml2PEtab.py
index c44b32b..2d53f3f 100644
--- a/yaml2sbml/yaml2PEtab.py
+++ b/yaml2sbml/yaml2PEtab.py
@@ -8,7 +8,7 @@ import petab
import yaml
-from .yaml2sbml import parse_yaml, load_yaml_file
+from .yaml2sbml import _parse_yaml, _load_yaml_file
from .yaml_validation import validate_yaml
@@ -50,14 +50,14 @@ def yaml2petab(yaml_file: str,
else:
sbml_dir = os.path.join(output_dir, model_name + '.xml')
- sbml_as_string = parse_yaml(yaml_file)
+ sbml_as_string = _parse_yaml(yaml_file)
with open(sbml_dir, 'w') as f_out:
f_out.write(sbml_as_string)
# create petab tsv files:
- yaml_dict = load_yaml_file(yaml_file)
- create_petab_tables_from_yaml(yaml_dict, output_dir)
+ yaml_dict = _load_yaml_file(yaml_file)
+ _create_petab_tables_from_yaml(yaml_dict, output_dir)
# create yaml file, that organizes the petab problem:
if (petab_yaml_name is None) and (measurement_table_name is not None):
@@ -72,10 +72,12 @@ def yaml2petab(yaml_file: str,
sbml_dir,
petab_yaml_name,
measurement_table_name)
+ # validate PEtab tables:
+ validate_petab_tables(sbml_dir, output_dir)
-def create_petab_tables_from_yaml(yaml_dict: dict,
- output_dir: str):
+def _create_petab_tables_from_yaml(yaml_dict: dict,
+ output_dir: str):
"""
Parses the yaml dict to a PEtab observable/parameter table.
diff --git a/yaml2sbml/yaml2sbml.py b/yaml2sbml/yaml2sbml.py
index a381285..70af213 100644
--- a/yaml2sbml/yaml2sbml.py
+++ b/yaml2sbml/yaml2sbml.py
@@ -23,14 +23,14 @@ def yaml2sbml(yaml_file: str, sbml_file: str):
"""
validate_yaml(yaml_file)
- sbml_as_string = parse_yaml(yaml_file)
+ sbml_as_string = _parse_yaml(yaml_file)
# write sbml file
with open(sbml_file, 'w') as f_out:
f_out.write(sbml_as_string)
-def parse_yaml(yaml_file: str) -> str:
+def _parse_yaml(yaml_file: str) -> str:
"""
Takes in a yaml file with the specification of ODEs, parses it, and
returns the corresponding SBML string.
@@ -52,7 +52,7 @@ def parse_yaml(yaml_file: str) -> str:
model = document.createModel()
model = _create_compartment(model)
- yaml_dic = load_yaml_file(yaml_file)
+ yaml_dic = _load_yaml_file(yaml_file)
_convert_yaml_blocks_to_sbml(model, yaml_dic)
# check consistency and give warnings for errors in SBML:
@@ -89,7 +89,7 @@ def _create_compartment(model: sbml.Model):
return model
-def load_yaml_file(yaml_file: str) -> dict:
+def _load_yaml_file(yaml_file: str) -> dict:
"""
Loads yaml file and returns the resulting dictionary.
@@ -123,13 +123,13 @@ def _convert_yaml_blocks_to_sbml(model: sbml.Model, yaml_dic: dict):
Raises:
"""
- function_dict = {'time': read_time_block,
- 'parameters': read_parameters_block,
- 'assignments': read_assignments_block,
- 'functions': read_functions_block,
- 'observables': read_observables_block,
- 'odes': read_odes_block,
- 'conditions': read_conditions_block}
+ function_dict = {'time': _read_time_block,
+ 'parameters': _read_parameters_block,
+ 'assignments': _read_assignments_block,
+ 'functions': _read_functions_block,
+ 'observables': _read_observables_block,
+ 'odes': _read_odes_block,
+ 'conditions': _read_conditions_block}
for block in yaml_dic:
function_dict[block](model, yaml_dic[block])
@@ -137,7 +137,7 @@ def _convert_yaml_blocks_to_sbml(model: sbml.Model, yaml_dic: dict):
return model
-def read_time_block(model: sbml.Model, time_dic: dict):
+def _read_time_block(model: sbml.Model, time_dic: dict):
"""
Reads and processes the time block.
@@ -154,10 +154,10 @@ def read_time_block(model: sbml.Model, time_dic: dict):
if time_dic['variable'] == 'time':
return
else:
- create_time(model, time_dic['variable'])
+ _create_time(model, time_dic['variable'])
-def create_time(model: sbml.Model, time_var: str):
+def _create_time(model: sbml.Model, time_var: str):
"""
Creates the time variable, add assignment to 'time'
@@ -180,7 +180,7 @@ def create_time(model: sbml.Model, time_var: str):
time_assignment.setMath(sbml.parseL3Formula('time'))
-def read_parameters_block(model: sbml.Model, parameter_list: list):
+def _read_parameters_block(model: sbml.Model, parameter_list: list):
"""
Reads and processes the parameters block in the ODE yaml file.
In particular, it reads the parameters and adds them to the given SBML model.
@@ -198,12 +198,12 @@ def read_parameters_block(model: sbml.Model, parameter_list: list):
"""
for parameter_def in parameter_list:
if 'nominalValue' in parameter_def.keys():
- create_parameter(model, parameter_def['parameterId'], parameter_def['nominalValue'])
+ _create_parameter(model, parameter_def['parameterId'], parameter_def['nominalValue'])
else:
- create_parameter(model, parameter_def['parameterId'])
+ _create_parameter(model, parameter_def['parameterId'])
-def create_parameter(model: sbml.Model, parameter_id: str, value: str = None):
+def _create_parameter(model: sbml.Model, parameter_id: str, value: str = None):
"""
Creates a parameter and adds it to the given SBML model.
Units are set as dimensionless by default.
@@ -229,7 +229,7 @@ def create_parameter(model: sbml.Model, parameter_id: str, value: str = None):
k.setUnits('dimensionless')
-def read_assignments_block(model: sbml.Model, assignment_list: list):
+def _read_assignments_block(model: sbml.Model, assignment_list: list):
"""
Reads and processes the assignments block in the ODE yaml file.
In particular, it reads the assignments and adds them to the given SBML file.
@@ -248,10 +248,10 @@ def read_assignments_block(model: sbml.Model, assignment_list: list):
"""
for assignment_def in assignment_list:
- create_assignment(model, assignment_def['assignmentId'], assignment_def['formula'])
+ _create_assignment(model, assignment_def['assignmentId'], assignment_def['formula'])
-def create_assignment(model: sbml.Model, assignment_id: str, formula: str):
+def _create_assignment(model: sbml.Model, assignment_id: str, formula: str):
"""
Creates an assignment rule, that assigns id to formula.
@@ -275,7 +275,7 @@ def create_assignment(model: sbml.Model, assignment_id: str, formula: str):
assignment_rule.setMath(sbml.parseL3Formula(formula))
-def read_functions_block(model: sbml.Model, functions_list: list):
+def _read_functions_block(model: sbml.Model, functions_list: list):
"""
Reads and processes the functions block in the ODE yaml file.
In particular, it reads the functions and adds them to the given SBML file
@@ -293,11 +293,11 @@ def read_functions_block(model: sbml.Model, functions_list: list):
"""
for function_def in functions_list:
- create_function(model, function_def['functionId'], function_def['arguments'],
- function_def['formula'])
+ _create_function(model, function_def['functionId'], function_def['arguments'],
+ function_def['formula'])
-def create_function(model: sbml.Model, function_id: str, arguments: str, formula: str):
+def _create_function(model: sbml.Model, function_id: str, arguments: str, formula: str):
"""
Creates a functionDefinition and adds it to the given SBML model.
@@ -318,7 +318,7 @@ def create_function(model: sbml.Model, function_id: str, arguments: str, formula
f.setMath(math)
-def read_odes_block(model: sbml.Model, odes_list: list):
+def _read_odes_block(model: sbml.Model, odes_list: list):
"""
Reads and processes the odes block in the ODE yaml file.
In particular, it reads the odes and adds a species for
@@ -339,11 +339,11 @@ def read_odes_block(model: sbml.Model, odes_list: list):
"""
for ode_def in odes_list:
- create_species(model, ode_def['stateId'], ode_def['initialValue'])
- create_rate_rule(model, ode_def['stateId'], ode_def['rightHandSide'])
+ _create_species(model, ode_def['stateId'], ode_def['initialValue'])
+ _create_rate_rule(model, ode_def['stateId'], ode_def['rightHandSide'])
-def create_species(model: sbml.Model, species_id: str, initial_amount: str):
+def _create_species(model: sbml.Model, species_id: str, initial_amount: str):
"""
Creates a species and adds it to the given SBML model.
Units are set as dimensionless by default.
@@ -380,7 +380,7 @@ def create_species(model: sbml.Model, species_id: str, initial_amount: str):
return s
-def create_rate_rule(model: sbml.Model, species: str, formula: str):
+def _create_rate_rule(model: sbml.Model, species: str, formula: str):
"""
Creates a SBML rateRule for a species and adds it to the given model.
This is where the ODEs from the text file are encoded.
@@ -402,7 +402,7 @@ def create_rate_rule(model: sbml.Model, species: str, formula: str):
r.setMath(math_ast)
-def read_observables_block(model: sbml.Model, observable_list: list):
+def _read_observables_block(model: sbml.Model, observable_list: list):
"""
Reads an processes the observables block in the ODE yaml file.
Since the observables are not represented in the SBML, it only gives
@@ -421,7 +421,7 @@ def read_observables_block(model: sbml.Model, observable_list: list):
'only have an effect the output, when called via yaml2PEtab')
-def read_conditions_block(model: sbml.Model, observable_list: list):
+def _read_conditions_block(model: sbml.Model, observable_list: list):
"""
Reads an processes the conditions block in the ODE yaml file.
Since the conditions are not represented in the SBML, it only gives
| yaml2sbml-dev/yaml2sbml | af592aad955dd733d33525fcbe6416a088e6df5d | diff --git a/tests/test_yaml2sbml.py b/tests/test_yaml2sbml.py
index 60c8bf0..24b0bb9 100644
--- a/tests/test_yaml2sbml.py
+++ b/tests/test_yaml2sbml.py
@@ -1,7 +1,7 @@
import os
import unittest
-from yaml2sbml.yaml2sbml import parse_yaml
+from yaml2sbml.yaml2sbml import _parse_yaml
class TestYaml2SBML(unittest.TestCase):
@@ -20,7 +20,7 @@ class TestYaml2SBML(unittest.TestCase):
ode_file = os.path.join(self.test_folder, 'ode_input2.yaml')
expected_result_file = os.path.join(self.test_folder, 'true_sbml_output.xml')
- sbml_contents = parse_yaml(ode_file)
+ sbml_contents = _parse_yaml(ode_file)
with open(expected_result_file, 'r') as f_in:
expected_sbml_contents = f_in.read()
@@ -36,7 +36,7 @@ class TestYaml2SBML(unittest.TestCase):
ode_file = os.path.join(self.test_folder, 'ode_input2.yaml')
expected_result_file = os.path.join(self.test_folder, 'true_sbml_output.xml')
- sbml_contents = parse_yaml(ode_file)
+ sbml_contents = _parse_yaml(ode_file)
with open(expected_result_file, 'r') as f_in:
expected_sbml_contents = f_in.read()
| Clear separation between public and private API
It would be nice, to have a clearer division between the public and private API of the tool. The public API should be imported via `import yaml2sbml`, the private one should only contain functions, that start with an underscore. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_yaml2sbml.py::TestYaml2SBML::test_yaml_import",
"tests/test_yaml2sbml.py::TestYaml2SBML::test_yaml_import_observables"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2020-10-27T17:41:06Z" | mit |
|
yaml2sbml-dev__yaml2sbml-40 | diff --git a/yaml2sbml/YamlModel.py b/yaml2sbml/YamlModel.py
index c0ff853..7d26ce3 100644
--- a/yaml2sbml/YamlModel.py
+++ b/yaml2sbml/YamlModel.py
@@ -17,7 +17,7 @@ class YamlModel:
"""
Set up yaml model.
"""
- self._yaml_model = {'time': None,
+ self._yaml_model = {'time': {},
'odes': [],
'parameters': [],
'assignments': [],
@@ -174,7 +174,7 @@ class YamlModel:
for (key, val) in self._yaml_model.items():
if val:
- reduced_model_dict[key] = copy.deepcopy(val)
+ reduced_model_dict[key] = copy.deepcopy(val)
return reduced_model_dict
@@ -184,10 +184,13 @@ class YamlModel:
def set_time(self,
time_variable: str):
- self._yaml_model['time'] = [time_variable]
+ self._yaml_model['time'] = {'variable': time_variable}
def get_time(self):
- return self._yaml_model['time'][0]
+ if self.is_set_time():
+ return self._yaml_model['time']['variable']
+ else:
+ return None
# functions adding a value
def add_parameter(self,
diff --git a/yaml2sbml/yaml_schema.yaml b/yaml2sbml/yaml_schema.yaml
index c4f5f11..b3640a8 100644
--- a/yaml2sbml/yaml_schema.yaml
+++ b/yaml2sbml/yaml_schema.yaml
@@ -6,11 +6,13 @@ description: yaml2sbml file format
properties:
time:
+ type: object
items:
variable:
type: string
description: defines a time variable, in case the right hand side of the ODE is time-dependent.
-
+ required:
+ - variable
parameters:
type: array
| yaml2sbml-dev/yaml2sbml | bfb9a46db7980e2476011a4471858ec7bc19f757 | diff --git a/tests/test_YamlModel.py b/tests/test_YamlModel.py
index a02407f..43842b5 100644
--- a/tests/test_YamlModel.py
+++ b/tests/test_YamlModel.py
@@ -254,6 +254,21 @@ class TestYamlModel(unittest.TestCase):
model.delete_condition(condition_id)
self.assertListEqual(model.get_condition_ids(), [])
+ def test_valid_model(self):
+ """
+ Tests, whether the resulting models are valid.
+ """
+ model = YamlModel()
+
+ model.set_time('t')
+ model.add_ode(state_id='x',
+ right_hand_side='k_1 * x + t',
+ initial_value=0)
+ model.add_parameter(parameter_id='k_1',
+ nominal_value=1)
+
+ model.validate_model()
+
if __name__ == '__main__':
suite = unittest.TestSuite()
diff --git a/tests/test_yaml2sbml/ode_input_invalid_time_1.yaml b/tests/test_yaml2sbml/ode_input_invalid_time_1.yaml
new file mode 100644
index 0000000..08acc01
--- /dev/null
+++ b/tests/test_yaml2sbml/ode_input_invalid_time_1.yaml
@@ -0,0 +1,9 @@
+time:
+ - t
+odes:
+- initialValue: 0
+ rightHandSide: k_1 * x + t
+ stateId: x
+parameters:
+- nominalValue: 1
+ parameterId: k_1
diff --git a/tests/test_yaml2sbml/ode_input_invalid_time_2.yaml b/tests/test_yaml2sbml/ode_input_invalid_time_2.yaml
new file mode 100644
index 0000000..dedcf75
--- /dev/null
+++ b/tests/test_yaml2sbml/ode_input_invalid_time_2.yaml
@@ -0,0 +1,9 @@
+time:
+ - variable: t
+odes:
+- initialValue: 0
+ rightHandSide: k_1 * x + t
+ stateId: x
+parameters:
+- nominalValue: 1
+ parameterId: k_1
diff --git a/tests/test_yaml_validation.py b/tests/test_yaml_validation.py
index 19cce2f..0bebd4d 100644
--- a/tests/test_yaml_validation.py
+++ b/tests/test_yaml_validation.py
@@ -36,6 +36,18 @@ class TestYamlValidation(unittest.TestCase):
with self.assertRaises(ValidationError):
validate_yaml(file_in)
+ def test_catch_invalid_time_block_missing_variable_key(self):
+ # time block without kew word "variable"
+ file_in = os.path.join(self.test_folder, 'ode_input_invalid_time_1.yaml')
+ with self.assertRaises(ValidationError):
+ validate_yaml(file_in)
+
+ def test_catch_invalid_time_block_as_array(self):
+ # time block as array instead of single object
+ file_in = os.path.join(self.test_folder, 'ode_input_invalid_time_2.yaml')
+ with self.assertRaises(ValidationError):
+ validate_yaml(file_in)
+
if __name__ == '__main__':
suite = unittest.TestSuite()
| Error in time variable specification with YamlModel
```python
from tempfile import NamedTemporaryFile
from yaml2sbml import YamlModel
model = YamlModel()
model.set_time('t')
with NamedTemporaryFile(suffix='.xml') as f:
model.write_to_sbml(f.name, over_write=True)
```
produces
```
Traceback (most recent call last):
model.write_to_sbml(f.name, over_write=True)
File "yaml2sbml/YamlModel.py", line 116, in write_to_sbml
sbml_as_string = _parse_yaml_dict(reduced_model_dict)
File "yaml2sbml/yaml2sbml.py", line 73, in _parse_yaml_dict
_convert_yaml_blocks_to_sbml(model, yaml_dict)
File "yaml2sbml/yaml2sbml.py", line 152, in _convert_yaml_blocks_to_sbml
function_dict[block](model, yaml_dic[block])
File "yaml2sbml/yaml2sbml/yaml2sbml.py", line 171, in _read_time_block
if time_dic['variable'] == 'time':
TypeError: list indices must be integers or slices, not str
```
This can be fixed by changing the [specification of the time variable](https://github.com/yaml2sbml-dev/yaml2sbml/blob/master/yaml2sbml/YamlModel.py#L187) from
```python
self._yaml_model['time'] = [time_variable]
```
to
```python
self._yaml_model['time'] = {'variable': time_variable}
```
In the context of the YAML model file, this would be equivalent to changing
```yaml
time:
- t
```
to
```yaml
time:
variable: t
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_yaml_validation.py::TestYamlValidation::test_catch_invalid_time_block_as_array",
"tests/test_yaml_validation.py::TestYamlValidation::test_catch_invalid_time_block_missing_variable_key"
] | [
"tests/test_YamlModel.py::TestYamlModel::test_assignment",
"tests/test_YamlModel.py::TestYamlModel::test_condition",
"tests/test_YamlModel.py::TestYamlModel::test_function",
"tests/test_YamlModel.py::TestYamlModel::test_load_and_write",
"tests/test_YamlModel.py::TestYamlModel::test_observable",
"tests/test_YamlModel.py::TestYamlModel::test_ode",
"tests/test_YamlModel.py::TestYamlModel::test_parameter",
"tests/test_YamlModel.py::TestYamlModel::test_time",
"tests/test_YamlModel.py::TestYamlModel::test_valid_model",
"tests/test_yaml_validation.py::TestYamlValidation::test_validate_yaml_empty_section",
"tests/test_yaml_validation.py::TestYamlValidation::test_validate_yaml_typos",
"tests/test_yaml_validation.py::TestYamlValidation::test_validate_yaml_typos_required",
"tests/test_yaml_validation.py::TestYamlValidation::test_validate_yaml_valid_1",
"tests/test_yaml_validation.py::TestYamlValidation::test_validate_yaml_valid_2"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2020-11-29T13:17:09Z" | mit |
|
yasufumy__pipelib-43 | diff --git a/pipelib/core.py b/pipelib/core.py
index 36f7b37..ec31d3e 100644
--- a/pipelib/core.py
+++ b/pipelib/core.py
@@ -80,17 +80,17 @@ class Dataset:
yield from chain(dataset, *others)
return PipelinedDataset(self, f)
- def map_parallel(self, map_func, n=None, chunksize=1):
+ def map_parallel(self, map_func, n=None, chunksize=1, unordered=False):
return PipelinedDataset(
- self, parallel.MapParallel(map_func, n, chunksize))
+ self, parallel.MapParallel(map_func, n, chunksize, unordered))
- def flat_map_parallel(self, map_func, n=None, chunksize=1):
+ def flat_map_parallel(self, map_func, n=None, chunksize=1, unordered=False):
return PipelinedDataset(
- self, parallel.FlatMapParallel(map_func, n, chunksize))
+ self, parallel.FlatMapParallel(map_func, n, chunksize, unordered))
- def filter_parallel(self, predicate, n=None, chunksize=1):
+ def filter_parallel(self, predicate, n=None, chunksize=1, unordered=False):
return PipelinedDataset(
- self, parallel.FilterParallel(predicate, n, chunksize))
+ self, parallel.FilterParallel(predicate, n, chunksize, unordered))
def all(self):
return list(self)
diff --git a/pipelib/parallel.py b/pipelib/parallel.py
index 98dfdd8..c7433ee 100644
--- a/pipelib/parallel.py
+++ b/pipelib/parallel.py
@@ -4,21 +4,27 @@ import multiprocess
class MapParallel:
- def __init__(self, func, n=None, chunksize=1):
+ def __init__(self, func, n=None, chunksize=1, unordered=False):
self._func = func
self._n = n
self._chunksize = chunksize
+ if not unordered:
+ self._map_method = 'imap'
+ else:
+ self._map_method = 'imap_unordered'
def __call__(self, dataset):
with multiprocess.Pool(self._n) as p:
- yield from p.imap_unordered(self._func, dataset, self._chunksize)
+ yield from getattr(p, self._map_method)(
+ self._func, dataset, self._chunksize)
class FlatMapParallel(MapParallel):
def __call__(self, dataset):
with multiprocess.Pool(self._n) as p:
yield from chain.from_iterable(
- p.imap_unordered(self._func, dataset, self._chunksize))
+ getattr(p, self._map_method)(
+ self._func, dataset, self._chunksize))
class FilterParallel(MapParallel):
@@ -37,4 +43,5 @@ class FilterParallel(MapParallel):
with multiprocess.Pool(self._n) as p:
yield from (x for x, keep in
- p.imap_unordered(task, dataset, self._chunksize) if keep)
+ getattr(p, self._map_method)(
+ task, dataset, self._chunksize) if keep)
diff --git a/setup.py b/setup.py
index eba6daf..0854f8a 100644
--- a/setup.py
+++ b/setup.py
@@ -7,7 +7,7 @@ except ImportError:
setup(
name='pipelib',
- version='0.2.2',
+ version='0.2.3',
description='pipeline architecture data library',
long_description=open('./README.md', encoding='utf-8').read(),
long_description_content_type='text/markdown',
| yasufumy/pipelib | 817dc34a6be1568b6e40b51922b71f36aa5b2c31 | diff --git a/tests/test_parallel.py b/tests/test_parallel.py
index c65ddc8..5502153 100644
--- a/tests/test_parallel.py
+++ b/tests/test_parallel.py
@@ -9,24 +9,45 @@ class ParallelTestCase(TestCase):
self.data = range(100)
def test_map_parallel(self):
- result = list(parallel.MapParallel(lambda x: x ** 2)(self.data))
- result.sort()
expected = [x ** 2 for x in self.data]
+ # ordered
+ result = parallel.MapParallel(lambda x: x ** 2)(self.data)
+ for x, y in zip(result, expected):
+ self.assertEqual(x, y)
+ # unordered
+ result = list(parallel.MapParallel(
+ lambda x: x ** 2, unordered=True)(self.data))
+ result.sort()
self.assertListEqual(result, expected)
def test_filter_parallel(self):
def predicate(x):
return x % 2 == 0
- result = list(parallel.FilterParallel(predicate)(self.data))
- result.sort()
task = parallel.FilterParallel._FilterTask(predicate)
- expected = [task(x) for x in self.data]
- expected = [x[0] for x in expected if x[1]]
+ expected = [task(x)[0] for x in self.data if task(x)[1]]
+
+ # ordered
+ result = parallel.FilterParallel(predicate)(self.data)
+ for x, y in zip(result, expected):
+ self.assertEqual(x, y)
+
+ # unordered
+ result = list(parallel.FilterParallel(
+ predicate, unordered=True)(self.data))
+ result.sort()
self.assertListEqual(result, expected)
def test_flat_map_parallel(self):
- result = list(parallel.FlatMapParallel(lambda x: [x])(self.data))
- result.sort()
expected = [x for x in self.data]
+
+ # ordered
+ result = parallel.FlatMapParallel(lambda x: [x])(self.data)
+ for x, y in zip(result, expected):
+ self.assertEqual(x, y)
+
+ # unordered
+ result = list(parallel.FlatMapParallel(
+ lambda x: [x], unordered=True)(self.data))
+ result.sort()
self.assertListEqual(result, expected)
| Option for order/unorder
- [x] `Dataset.map_parallel`
- [x] `Dataset.flat_map_parallel`
- [x] `Dataset.filter_parallel` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_parallel.py::ParallelTestCase::test_filter_parallel",
"tests/test_parallel.py::ParallelTestCase::test_flat_map_parallel",
"tests/test_parallel.py::ParallelTestCase::test_map_parallel"
] | [] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2019-02-12T04:25:23Z" | mit |
|
yt-project__unyt-242 | diff --git a/docs/conf.py b/docs/conf.py
index e6e89f8..dddfa2f 100755
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -73,7 +73,7 @@ release = unyt.__version__
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
-language = 'en'
+language = "en"
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
diff --git a/unyt/array.py b/unyt/array.py
index fae1e95..8e40f84 100644
--- a/unyt/array.py
+++ b/unyt/array.py
@@ -2155,12 +2155,14 @@ class unyt_quantity(unyt_array):
def __round__(self):
return type(self)(round(float(self)), self.units)
- def reshape(self, shape, order="C"):
+ def reshape(self, *shape, order="C"):
# this is necessary to support some numpy operations
# natively, like numpy.meshgrid, which internally performs
# reshaping, e.g., arr.reshape(1, -1), which doesn't affect the size,
# but does change the object's internal representation to a >0D array
# see https://github.com/yt-project/unyt/issues/224
+ if len(shape) == 1:
+ shape = shape[0]
if shape == () or shape is None:
return super().reshape(shape, order=order)
else:
| yt-project/unyt | 17e016e988fcc59326fcb53c566d56746ebce428 | diff --git a/unyt/tests/test_unyt_array.py b/unyt/tests/test_unyt_array.py
index 8cf00af..6132d0f 100644
--- a/unyt/tests/test_unyt_array.py
+++ b/unyt/tests/test_unyt_array.py
@@ -2673,3 +2673,11 @@ def test_reshape_quantity_noop(shape):
b = a.reshape(shape)
assert b.shape == a.shape == ()
assert type(b) is unyt_quantity
+
+
+def test_reshape_quantity_via_shape_tuple():
+ # this is necessary to support np.tile
+ a = unyt_quantity(1, "m")
+ b = a.reshape(-1, 1)
+ assert b.shape == (1, 1)
+ assert type(b) is unyt_array
| REG: reshape regression
### Description
Testing yt against unyt's dev branch, I found 4 tests failing
https://github.com/yt-project/yt/runs/7277732032?check_suite_focus=true
I think there's only one actual regression with `unyt_array.reshape`, so I have a hunch it's coming from #225
I'll inspect this further and see what I can do to fix the problem here before the next release
for information @jzuhone | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"unyt/tests/test_unyt_array.py::test_reshape_quantity_via_shape_tuple"
] | [
"unyt/tests/test_unyt_array.py::test_comparisons",
"unyt/tests/test_unyt_array.py::test_unyt_array_unyt_quantity_ops",
"unyt/tests/test_unyt_array.py::test_selecting",
"unyt/tests/test_unyt_array.py::test_iteration",
"unyt/tests/test_unyt_array.py::test_unpickling_old_array",
"unyt/tests/test_unyt_array.py::test_registry_association",
"unyt/tests/test_unyt_array.py::test_to_value",
"unyt/tests/test_unyt_array.py::test_astropy",
"unyt/tests/test_unyt_array.py::test_pint",
"unyt/tests/test_unyt_array.py::test_subclass",
"unyt/tests/test_unyt_array.py::test_h5_io",
"unyt/tests/test_unyt_array.py::test_equivalencies",
"unyt/tests/test_unyt_array.py::test_ytarray_coercion",
"unyt/tests/test_unyt_array.py::test_dimensionless_conversion",
"unyt/tests/test_unyt_array.py::test_loadtxt_and_savetxt",
"unyt/tests/test_unyt_array.py::test_trig_ufunc_degrees",
"unyt/tests/test_unyt_array.py::test_initialization_different_registries",
"unyt/tests/test_unyt_array.py::test_ones_and_zeros_like",
"unyt/tests/test_unyt_array.py::test_coerce_iterable",
"unyt/tests/test_unyt_array.py::test_bypass_validation",
"unyt/tests/test_unyt_array.py::test_creation",
"unyt/tests/test_unyt_array.py::test_conversion_from_int_types[8]",
"unyt/tests/test_unyt_array.py::test_conversion_from_int_types[16]",
"unyt/tests/test_unyt_array.py::test_conversion_from_int_types[32]",
"unyt/tests/test_unyt_array.py::test_conversion_from_int_types[64]",
"unyt/tests/test_unyt_array.py::test_overflow_warnings",
"unyt/tests/test_unyt_array.py::test_name_attribute",
"unyt/tests/test_unyt_array.py::test_mil",
"unyt/tests/test_unyt_array.py::test_kip",
"unyt/tests/test_unyt_array.py::test_ksi",
"unyt/tests/test_unyt_array.py::test_complexvalued",
"unyt/tests/test_unyt_array.py::test_string_formatting",
"unyt/tests/test_unyt_array.py::test_invalid_expression_quantity_from_string[++1cm]",
"unyt/tests/test_unyt_array.py::test_invalid_expression_quantity_from_string[--1cm]",
"unyt/tests/test_unyt_array.py::test_invalid_expression_quantity_from_string[cm10]",
"unyt/tests/test_unyt_array.py::test_invalid_expression_quantity_from_string[cm",
"unyt/tests/test_unyt_array.py::test_invalid_expression_quantity_from_string[.cm]",
"unyt/tests/test_unyt_array.py::test_invalid_unit_quantity_from_string[10",
"unyt/tests/test_unyt_array.py::test_invalid_unit_quantity_from_string[50.",
"unyt/tests/test_unyt_array.py::test_invalid_unit_quantity_from_string[.6",
"unyt/tests/test_unyt_array.py::test_invalid_unit_quantity_from_string[infcm]",
"unyt/tests/test_unyt_array.py::test_constant_type",
"unyt/tests/test_unyt_array.py::test_composite_meshgrid",
"unyt/tests/test_unyt_array.py::test_reshape_quantity_to_array[1-expected_output_shape0]",
"unyt/tests/test_unyt_array.py::test_reshape_quantity_to_array[shape1-expected_output_shape1]",
"unyt/tests/test_unyt_array.py::test_reshape_quantity_to_array[shape2-expected_output_shape2]",
"unyt/tests/test_unyt_array.py::test_reshape_quantity_to_array[shape3-expected_output_shape3]",
"unyt/tests/test_unyt_array.py::test_reshape_quantity_noop[shape0]",
"unyt/tests/test_unyt_array.py::test_reshape_quantity_noop[None]"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2022-07-11T11:28:12Z" | bsd-3-clause |
|
yukinarit__pyserde-208 | diff --git a/pyproject.toml b/pyproject.toml
index c19a5cf..51ec0ca 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -54,7 +54,8 @@ pytest-cov = "*"
pytest-watch = "*"
pytest-flake8 = "*"
coverage = "==4.5.4"
-pdoc = { version = "~=8" }
+pdoc = "~=11"
+pygments = "<=2.11.2"
mypy = { version = "==0.931", markers = "platform_python_implementation!='PyPy'" }
more-itertools = "~=8.6.0"
pre-commit = "==v2.10.1"
diff --git a/serde/compat.py b/serde/compat.py
index 8c1af36..b5e2143 100644
--- a/serde/compat.py
+++ b/serde/compat.py
@@ -121,6 +121,11 @@ def typename(typ) -> str:
else:
return 'Union'
elif is_list(typ):
+ # Workaround for python 3.7.
+ # get_args for the bare List returns parameter T.
+ if typ is List:
+ return 'List'
+
args = type_args(typ)
if args:
et = typename(args[0])
@@ -128,6 +133,11 @@ def typename(typ) -> str:
else:
return 'List'
elif is_set(typ):
+ # Workaround for python 3.7.
+ # get_args for the bare Set returns parameter T.
+ if typ is Set:
+ return 'Set'
+
args = type_args(typ)
if args:
et = typename(args[0])
@@ -135,6 +145,11 @@ def typename(typ) -> str:
else:
return 'Set'
elif is_dict(typ):
+ # Workaround for python 3.7.
+ # get_args for the bare Dict returns parameter K, V.
+ if typ is Dict:
+ return 'Dict'
+
args = type_args(typ)
if args and len(args) == 2:
kt = typename(args[0])
diff --git a/serde/de.py b/serde/de.py
index e76660b..3416505 100644
--- a/serde/de.py
+++ b/serde/de.py
@@ -562,7 +562,9 @@ class Renderer:
res = self.default(arg, res)
if self.custom and not arg.deserializer:
- return self.custom_class_deserializer(arg, res)
+ # Rerender the code for default deserializer.
+ default = Renderer(self.func, self.cls, None).render(arg)
+ return self.custom_class_deserializer(arg, default)
else:
return res
| yukinarit/pyserde | 508c54d86a5e1fb954eea865e32ea426ee98f1cc | diff --git a/tests/test_compat.py b/tests/test_compat.py
index f0819ff..8991865 100644
--- a/tests/test_compat.py
+++ b/tests/test_compat.py
@@ -1,5 +1,6 @@
import sys
from dataclasses import dataclass
+from datetime import datetime
from typing import Dict, Generic, List, NewType, Optional, Set, Tuple, TypeVar, Union
import serde
@@ -67,9 +68,18 @@ def test_typename():
class Foo(Generic[T]):
nested: Bar[T]
- assert typename(Optional) == "Optional"
assert typename(Foo[int]) == "Foo"
assert typename(Foo) == "Foo"
+ assert typename(List[int]) == "List[int]"
+ assert typename(Optional) == "Optional"
+ assert typename(List) == "List"
+ assert typename(List[int]) == "List[int]"
+ assert typename(Tuple) == "Tuple"
+ assert typename(Tuple[int, str]) == "Tuple[int, str]"
+ assert typename(Dict) == "Dict"
+ assert typename(Dict[str, Foo]) == "Dict[str, Foo]"
+ assert typename(Set) == "Set"
+ assert typename(Set[int]) == "Set[int]"
def test_iter_types():
@@ -79,6 +89,17 @@ def test_iter_types():
assert [Tuple, int, str, bool, float] == list(iter_types(Tuple[int, str, bool, float]))
assert [PriOpt, Optional, int, Optional, str, Optional, float, Optional, bool] == list(iter_types(PriOpt))
+ @serde.serde
+ class Foo:
+ a: int
+ b: datetime
+ c: datetime
+ d: Optional[str] = None
+ e: Union[str, int] = 10
+ f: List[int] = serde.field(default_factory=list)
+
+ assert [Foo, int, datetime, datetime, Optional, str, Union, str, int, List, int] == list(iter_types(Foo))
+
def test_iter_unions():
assert [Union[str, int]] == list(iter_unions(Union[str, int]))
diff --git a/tests/test_custom.py b/tests/test_custom.py
index 060f046..dc75515 100644
--- a/tests/test_custom.py
+++ b/tests/test_custom.py
@@ -2,7 +2,7 @@
Tests for custom serializer/deserializer.
"""
from datetime import datetime
-from typing import Optional, Union
+from typing import List, Optional, Union
import pytest
@@ -81,14 +81,15 @@ def test_custom_class_serializer():
c: datetime
d: Optional[str] = None
e: Union[str, int] = 10
+ f: List[int] = field(default_factory=list)
dt = datetime(2021, 1, 1, 0, 0, 0)
- f = Foo(10, dt, dt)
+ f = Foo(10, dt, dt, f=[1, 2, 3])
- assert to_json(f) == '{"a": 10, "b": "01/01/21", "c": "01/01/21", "d": null, "e": 10}'
+ assert to_json(f) == '{"a": 10, "b": "01/01/21", "c": "01/01/21", "d": null, "e": 10, "f": [1, 2, 3]}'
assert f == from_json(Foo, to_json(f))
- assert to_tuple(f) == (10, '01/01/21', '01/01/21', None, 10)
+ assert to_tuple(f) == (10, '01/01/21', '01/01/21', None, 10, [1, 2, 3])
assert f == from_tuple(Foo, to_tuple(f))
def fallback(_, __):
| ArgumentError for List when using custom deserializer
Hey,
thanks for the fast fix on #190 ! While testing the fix I found the following:
```python
from serde import serde, SerdeSkip
from serde.json import from_json
from dataclasses import dataclass
from typing import Optional
def des(cls, o):
raise SerdeSkip()
@serde(deserializer=des)
@dataclass
class Foo:
a: list[str]
print(from_json(Foo, '{"a": []}')) # -> Foo(a=[])
print(from_json(Foo, '{"a": ["foo"]}')) # -> AttributeError: 'str' object has no attribute 'get'
```
Greetings
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_custom.py::test_custom_class_serializer"
] | [
"tests/test_compat.py::test_types",
"tests/test_compat.py::test_typename",
"tests/test_compat.py::test_iter_types",
"tests/test_compat.py::test_iter_unions",
"tests/test_compat.py::test_type_args",
"tests/test_compat.py::test_union_args",
"tests/test_compat.py::test_is_instance",
"tests/test_compat.py::test_is_generic",
"tests/test_custom.py::test_custom_field_serializer",
"tests/test_custom.py::test_raise_error",
"tests/test_custom.py::test_wrong_signature",
"tests/test_custom.py::test_field_serialize_override_class_serializer",
"tests/test_custom.py::test_override_by_default_serializer"
] | {
"failed_lite_validators": [
"has_issue_reference",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-03-21T15:34:35Z" | mit |
|
yukinarit__pyserde-229 | diff --git a/examples/union_operator.py b/examples/union_operator.py
index a6d2f68..cb78577 100644
--- a/examples/union_operator.py
+++ b/examples/union_operator.py
@@ -17,6 +17,7 @@ class Foo:
a: int | str
b: dict[str, int] | list[int]
c: Bar | Baz
+ d: str | None = None # Should be treated as Optional
def main():
diff --git a/serde/compat.py b/serde/compat.py
index b5e2143..dc8b5a5 100644
--- a/serde/compat.py
+++ b/serde/compat.py
@@ -354,16 +354,16 @@ def is_union(typ) -> bool:
True
"""
- is_union_type = False
+ # Python 3.10 Union operator e.g. str | int
if sys.version_info[:2] >= (3, 10):
try:
- is_union_type = isinstance(typ, types.UnionType) and not is_opt(typ)
+ if isinstance(typ, types.UnionType):
+ return True
except Exception:
pass
- typing_union = typing_inspect.is_union_type(typ) and not is_opt(typ)
-
- return is_union_type or typing_union
+ # typing.Union
+ return typing_inspect.is_union_type(typ)
def is_opt(typ) -> bool:
@@ -377,9 +377,22 @@ def is_opt(typ) -> bool:
>>> is_opt(None.__class__)
False
"""
+
+ # Python 3.10 Union operator e.g. str | None
+ is_union_type = False
+ if sys.version_info[:2] >= (3, 10):
+ try:
+ if isinstance(typ, types.UnionType):
+ is_union_type = True
+ except Exception:
+ pass
+
+ # typing.Optional
+ is_typing_union = typing_inspect.is_optional_type(typ)
+
args = type_args(typ)
if args:
- return typing_inspect.is_optional_type(typ) and len(args) == 2 and not is_none(args[0]) and is_none(args[1])
+ return (is_union_type or is_typing_union) and len(args) == 2 and not is_none(args[0]) and is_none(args[1])
else:
return typ is Optional
| yukinarit/pyserde | bd9039ef1ffac752f7566eb39fc2b3c0a18f7728 | diff --git a/tests/test_compat.py b/tests/test_compat.py
index 8991865..2f6ba0b 100644
--- a/tests/test_compat.py
+++ b/tests/test_compat.py
@@ -37,10 +37,10 @@ def test_types():
assert is_dict(Dict[str, int])
assert is_dict(Dict)
assert is_opt(Optional[int])
+ assert is_opt(Union[int, None])
assert is_union(Union[int, str])
assert is_union(Union[Optional[int], Optional[str]])
- assert is_opt(Optional[int])
- assert not is_union(Optional[int])
+ assert is_union(Optional[int])
assert not is_opt(Union[Optional[int], Optional[str]])
assert is_union(Union[Optional[int], Optional[str]])
@@ -58,6 +58,11 @@ def test_types():
assert is_tuple(tuple[int, int, int])
assert is_dict(dict[str, int])
+ if sys.version_info[:3] >= (3, 10, 0):
+ assert is_union(str | int)
+ assert is_union(str | None)
+ assert is_opt(str | None)
+
def test_typename():
@serde.serde
| Python 3.10 union operator with None (e.g. " str | None") can't capture missing field
I'm running Python 3.10 and Pyserde 0.7.2. This
```python
@serde
class Test:
x: str | None
print(from_json(Test, '{}'))
```
causes a crash
```
Traceback (most recent call last):
File "/home/seho/.local/lib/python3.10/site-packages/serde/de.py", line 304, in from_obj
return serde_scope.funcs[FROM_DICT](
File "<string>", line 11, in from_dict
KeyError: 'x'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/seho/pts15_test/deleteme.py", line 11, in <module>
print(from_json(Test, '{}'))
File "/home/seho/.local/lib/python3.10/site-packages/serde/json.py", line 47, in from_json
return from_dict(c, de.deserialize(s, **opts), reuse_instances=False)
File "/home/seho/.local/lib/python3.10/site-packages/serde/de.py", line 376, in from_dict
return from_obj(cls, o, named=True, reuse_instances=reuse_instances)
File "/home/seho/.local/lib/python3.10/site-packages/serde/de.py", line 353, in from_obj
raise SerdeError(e)
serde.compat.SerdeError: 'x'
```
While using `Optional[str]` works fine
```python
@serde
class Test:
x: Optional[str]
print(from_json(Test, '{}'))
```
Output: `test(x=None)` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_compat.py::test_types"
] | [
"tests/test_compat.py::test_typename",
"tests/test_compat.py::test_iter_types",
"tests/test_compat.py::test_iter_unions",
"tests/test_compat.py::test_type_args",
"tests/test_compat.py::test_union_args",
"tests/test_compat.py::test_is_instance",
"tests/test_compat.py::test_is_generic"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2022-05-16T14:07:02Z" | mit |
|
yukinarit__pyserde-264 | diff --git a/serde/de.py b/serde/de.py
index 240df8b..a88a2e7 100644
--- a/serde/de.py
+++ b/serde/de.py
@@ -648,14 +648,11 @@ class Renderer:
if data.get("f") is not None else None'
"""
value = arg[0]
- if has_default(arg):
- return self.render(value)
+ if arg.iterbased:
+ exists = f'{arg.data} is not None'
else:
- if arg.iterbased:
- exists = f'{arg.data} is not None'
- else:
- exists = f'{arg.datavar}.get("{arg.conv_name()}") is not None'
- return f'({self.render(value)}) if {exists} else None'
+ exists = f'{arg.datavar}.get("{arg.conv_name()}") is not None'
+ return f'({self.render(value)}) if {exists} else None'
def list(self, arg: DeField) -> str:
"""
| yukinarit/pyserde | 1f48c9ccd358f6d0eb5d0afd2ff87a0b47300ade | diff --git a/tests/test_union.py b/tests/test_union.py
index be7317a..e6fa792 100644
--- a/tests/test_union.py
+++ b/tests/test_union.py
@@ -225,6 +225,29 @@ def test_optional_union_with_complex_types():
assert a_none == from_dict(A, to_dict(a_none, reuse_instances=True), reuse_instances=True)
+def test_optional_complex_type_with_default():
+ for T, default in [
+ (IPv4Address, IPv4Address("127.0.0.1")),
+ (UUID, UUID("9c244009-c60d-452b-a378-b8afdc0c2d90")),
+ ]:
+
+ @serde
+ class A:
+ id: Optional[T] = None
+
+ a = A(default)
+ assert a == from_dict(A, to_dict(a, reuse_instances=False), reuse_instances=False)
+ assert a == from_dict(A, to_dict(a, reuse_instances=True), reuse_instances=True)
+
+ a_none = A(None)
+ assert a_none == from_dict(A, to_dict(a_none, reuse_instances=False), reuse_instances=False)
+ assert a_none == from_dict(A, to_dict(a_none, reuse_instances=True), reuse_instances=True)
+
+ a_default = A()
+ assert a_default == from_dict(A, to_dict(a_default, reuse_instances=False), reuse_instances=False)
+ assert a_default == from_dict(A, to_dict(a_default, reuse_instances=True), reuse_instances=True)
+
+
def test_union_with_complex_types_in_containers():
@serde
class A:
| Unable to deserialize null value for type `Optional[UUID] = None`
Hi, pyserde seems to mishandle this very specific corner case.
Minimum example:
```python
from serde import serde, to_dict, from_dict
from uuid import UUID
from typing import Optional
from dataclasses import dataclass
@serde
@dataclass
class NameId:
name: str
id: Optional[UUID] = None # <====== UUID and `None` here is the problem
x = NameId("Fred", None)
j = to_dict(x)
y = from_dict(NameId, j)
```
Everything before the last line works fine. The last line gives the error below.
If I remove the default for `id` (i.e., remove `= None`), it works fine.
If I change the type of `id` to `Optional[int] = None`, it works fine.
So it's specific to `Optional[UUID] = None`.
From the error, it seems like it's trying to parse `None` as a `UUID`.
Here's the error:
```
Traceback (most recent call last):
File "/Users/kevin.squire/Library/Caches/pypoetry/virtualenvs/pyserde-Y2i1skxI-py3.10/lib/python3.10/site-packages/serde/de.py", line 338, in from_obj
res = serde_scope.funcs[func_name](c, maybe_generic=maybe_generic, data=o, reuse_instances=reuse_instances)
File "<string>", line 13, in from_dict
File "/Users/kevin.squire/.pyenv/versions/3.10.5_x86/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/uuid.py", line 171, in __init__
raise TypeError('one of the hex, bytes, bytes_le, fields, '
TypeError: one of the hex, bytes, bytes_le, fields, or int arguments must be given
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/kevin.squire/tmp/pyserde/tmp/test.py", line 15, in <module>
y = from_dict(NameId, j)
File "/Users/kevin.squire/Library/Caches/pypoetry/virtualenvs/pyserde-Y2i1skxI-py3.10/lib/python3.10/site-packages/serde/de.py", line 414, in from_dict
return from_obj(cls, o, named=True, reuse_instances=reuse_instances)
File "/Users/kevin.squire/Library/Caches/pypoetry/virtualenvs/pyserde-Y2i1skxI-py3.10/lib/python3.10/site-packages/serde/de.py", line 391, in from_obj
raise SerdeError(e)
serde.compat.SerdeError: one of the hex, bytes, bytes_le, fields, or int arguments must be given
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_union.py::test_optional_complex_type_with_default"
] | [
"tests/test_union.py::test_union",
"tests/test_union.py::test_union_optional",
"tests/test_union.py::test_union_containers",
"tests/test_union.py::test_union_with_literal",
"tests/test_union.py::test_union_with_complex_types",
"tests/test_union.py::test_union_with_complex_types_and_reuse_instances",
"tests/test_union.py::test_optional_union_with_complex_types",
"tests/test_union.py::test_union_with_complex_types_in_containers",
"tests/test_union.py::test_union_exception_if_nothing_matches",
"tests/test_union.py::test_union_in_union",
"tests/test_union.py::test_union_in_other_type",
"tests/test_union.py::test_union_rename_all",
"tests/test_union.py::test_union_with_list_of_other_class",
"tests/test_union.py::test_union_with_union_in_nested_types",
"tests/test_union.py::test_union_with_union_in_nested_tuple",
"tests/test_union.py::test_generic_union",
"tests/test_union.py::test_external_tagging",
"tests/test_union.py::test_internal_tagging",
"tests/test_union.py::test_adjacent_tagging",
"tests/test_union.py::test_untagged"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2022-09-01T18:55:42Z" | mit |
|
yukinarit__pyserde-441 | diff --git a/serde/core.py b/serde/core.py
index 63449e2..7668d81 100644
--- a/serde/core.py
+++ b/serde/core.py
@@ -44,6 +44,7 @@ from .compat import (
is_list,
is_literal,
is_new_type_primitive,
+ is_any,
is_opt,
is_set,
is_tuple,
@@ -382,6 +383,8 @@ def is_instance(obj: Any, typ: Any) -> bool:
return isinstance(obj, inner)
else:
return False
+ elif is_any(typ):
+ return True
elif typ is Ellipsis:
return True
else:
| yukinarit/pyserde | 76e919cc5e2692eb2ba7d194af0655af898191ae | diff --git a/tests/test_union.py b/tests/test_union.py
index af02d6d..f482028 100644
--- a/tests/test_union.py
+++ b/tests/test_union.py
@@ -2,7 +2,7 @@ import logging
import sys
from dataclasses import dataclass
from ipaddress import IPv4Address
-from typing import Dict, FrozenSet, Generic, List, NewType, Optional, Tuple, TypeVar, Union
+from typing import Dict, FrozenSet, Generic, List, NewType, Optional, Tuple, TypeVar, Union, Any
from uuid import UUID
import pytest
@@ -772,3 +772,21 @@ def test_union_frozenset_with_prim():
a: Union[FrozenSet[int], int]
assert to_dict(Foo(frozenset({1}))) == {"a": {1}}
+
+
+def test_union_with_any():
+ @dataclass
+ class FooWithString:
+ foo: str
+
+ @dataclass
+ class BarWithDict:
+ bar: Dict[str, Any]
+
+ @serde(tagging=Untagged)
+ @dataclass
+ class Class:
+ foobars: List[Union[FooWithString, BarWithDict]]
+
+ c = Class([FooWithString("string"), BarWithDict({"key": "value"})])
+ assert c == from_json(Class, to_json(c))
| serde.compat.SerdeError: Can not serialize with untagged union of dict[str, Any]
`0.12.3` on Python 3.11.4:
```py
from dataclasses import dataclass
from typing import Any
from serde import Untagged, field, serde
from serde.yaml import from_yaml, to_yaml
@dataclass
class FooWithString:
foo: str
@dataclass
class BarWithDict:
bar: dict[str, Any] # remove [str, Any] to fix
@serde(tagging=Untagged)
@dataclass
class Klass:
foobars: list[FooWithString | BarWithDict]
good_yaml = """
foobars:
- foo: string
- bar:
key: value
"""
if __name__ == '__main__':
config = from_yaml(Klass, good_yaml)
print(to_yaml(config))
```
```
serde.compat.SerdeError: Can not serialize BarWithDict(bar={'key': 'value'}) of type BarWithDict for Union[FooWithString, BarWithDict]
```
---
Weirdly the more trivial case `list[BarWithDict]` works fine, as does just `BarWithDict`.
It's something specifically caused by it being in an untagged union list 🤔
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_union.py::test_union_with_any"
] | [
"tests/test_union.py::test_union",
"tests/test_union.py::test_union_optional",
"tests/test_union.py::test_union_containers",
"tests/test_union.py::test_union_with_literal",
"tests/test_union.py::test_union_with_complex_types",
"tests/test_union.py::test_union_with_complex_types_and_reuse_instances",
"tests/test_union.py::test_optional_union_with_complex_types",
"tests/test_union.py::test_optional_complex_type_with_default",
"tests/test_union.py::test_union_with_complex_types_in_containers",
"tests/test_union.py::test_union_exception_if_nothing_matches",
"tests/test_union.py::test_union_in_union",
"tests/test_union.py::test_union_in_other_type",
"tests/test_union.py::test_union_rename_all",
"tests/test_union.py::test_union_with_list_of_other_class",
"tests/test_union.py::test_union_with_union_in_nested_types",
"tests/test_union.py::test_union_with_union_in_nested_tuple",
"tests/test_union.py::test_generic_union",
"tests/test_union.py::test_external_tagging",
"tests/test_union.py::test_internal_tagging",
"tests/test_union.py::test_adjacent_tagging",
"tests/test_union.py::test_untagged",
"tests/test_union.py::test_newtype_and_untagged_union",
"tests/test_union.py::test_union_directly",
"tests/test_union.py::test_union_frozenset_with_prim"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2023-11-11T06:48:07Z" | mit |
|
yukinarit__pyserde-487 | diff --git a/serde/de.py b/serde/de.py
index 5451cf6..5674f0a 100644
--- a/serde/de.py
+++ b/serde/de.py
@@ -438,7 +438,10 @@ def from_obj(c: Type[T], o: Any, named: bool, reuse_instances: Optional[bool]) -
try:
thisfunc = functools.partial(from_obj, named=named, reuse_instances=reuse_instances)
if is_dataclass_without_de(c):
- deserialize(c)
+ # Do not automatically implement beartype if dataclass without serde decorator
+ # is passed, because it is surprising for users
+ # See https://github.com/yukinarit/pyserde/issues/480
+ deserialize(c, type_check=disabled)
res = deserializable_to_obj(c)
elif is_deserializable(c):
res = deserializable_to_obj(c)
diff --git a/serde/se.py b/serde/se.py
index eca1dcc..a69544f 100644
--- a/serde/se.py
+++ b/serde/se.py
@@ -366,7 +366,10 @@ def to_obj(
if o is None:
return None
if is_dataclass_without_se(o):
- serialize(type(o))
+ # Do not automatically implement beartype if dataclass without serde decorator
+ # is passed, because it is surprising for users
+ # See https://github.com/yukinarit/pyserde/issues/480
+ serialize(type(o), type_check=disabled)
return serializable_to_obj(o)
elif is_serializable(o):
return serializable_to_obj(o)
| yukinarit/pyserde | f4ab3800f4121a1be96d72fb1e237a1542972015 | diff --git a/tests/test_type_check.py b/tests/test_type_check.py
index 86caad6..9f3dd63 100644
--- a/tests/test_type_check.py
+++ b/tests/test_type_check.py
@@ -1,3 +1,4 @@
+from dataclasses import dataclass
import datetime
import pathlib
from beartype.roar import BeartypeCallHintViolation
@@ -15,6 +16,7 @@ from beartype.typing import (
import pytest
import serde
+import serde.json
from . import data
@@ -100,6 +102,18 @@ def test_type_check_strict(T: Any, data: Any, exc: bool) -> None:
serde.from_dict(C, d)
+def test_type_check_disabled_for_dataclass_without_serde() -> None:
+ @dataclass
+ class Foo:
+ value: int
+
+ f = Foo("100") # type: ignore
+ data = serde.json.to_json(f)
+ assert f == serde.json.from_json(Foo, data)
+
+ f = Foo("100") # type: ignore
+
+
def test_uncoercible() -> None:
@serde.serde(type_check=serde.coerce)
class Foo:
| Bear type checking "leaks" to classes without the @serde decorator
Hi,
With update 0.14, it seems that bear type checking is being applied to classes passed as arguments to `serde.json.to_json`, even if they do not have the `@serde` decorator applied to them.
In general I prefer to not use the `@serde` decorator in my model classes, instead using `serde` only at the I/O layer with the `serde.json.from_json` and `serde.json.to_json` functions.
However seems like after calling `to_json` into a dataclass without the `@serde` decorator, bear type checking is now applied to that class from that point onward, which is surprising.
Example:
```python
from dataclasses import dataclass
import serde.json
@dataclass
class Foo:
value: int
# This passes.
f = Foo("100")
data = serde.json.to_json(f, cls=Foo)
# After to_json(), this starts to fail with:
# beartype.roar.BeartypeCallHintParamViolation: Method __main__.Foo.__init__() parameter value='100' violates type hint <class 'int'>, as str '100' not instance of int.
f = Foo("100")
```
This is surprising to the user, even more so because model classes start to validate their types *after* some I/O has been performed, which might happen at different points in the application.
A workaround for now is to decorate `Foo` with `@serde(type_check=disabled)`, however this is not ideal given the functions `to_json` and `from_json` do not convey that they might change the runtime behavior of the class being passed as parameter.
> [!Note]
> This example is simplified, but in my code it was more complex, where I had an attribute declared as `tuple[int, ...]` but would accept any `Sequence[int]` at runtime, being converted to `tuple[int, ...]` during `__post_init__` to ensure the constructed object would have the correct runtime type. The reason for this is that the `Sequence[int]` comes from an external source, and sometimes would be provided as `list[int]` or `tuple[int, ...]`. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_type_check.py::test_type_check_disabled_for_dataclass_without_serde"
] | [
"tests/test_type_check.py::test_type_check_strict[int-10-False]",
"tests/test_type_check.py::test_type_check_strict[int-10.0-True]",
"tests/test_type_check.py::test_type_check_strict[int-10-True]",
"tests/test_type_check.py::test_type_check_strict[int-True-False]",
"tests/test_type_check.py::test_type_check_strict[float-10-True0]",
"tests/test_type_check.py::test_type_check_strict[float-10.0-False]",
"tests/test_type_check.py::test_type_check_strict[float-10-True1]",
"tests/test_type_check.py::test_type_check_strict[float-True-True]",
"tests/test_type_check.py::test_type_check_strict[str-10-True]",
"tests/test_type_check.py::test_type_check_strict[str-10.0-True]",
"tests/test_type_check.py::test_type_check_strict[str-10-False]",
"tests/test_type_check.py::test_type_check_strict[str-True-True]",
"tests/test_type_check.py::test_type_check_strict[bool-10-True0]",
"tests/test_type_check.py::test_type_check_strict[bool-10.0-True]",
"tests/test_type_check.py::test_type_check_strict[bool-10-True1]",
"tests/test_type_check.py::test_type_check_strict[bool-True-False]",
"tests/test_type_check.py::test_type_check_strict[list-data16-False]",
"tests/test_type_check.py::test_type_check_strict[list-data17-True]",
"tests/test_type_check.py::test_type_check_strict[list-data18-False]",
"tests/test_type_check.py::test_type_check_strict[list-data19-True]",
"tests/test_type_check.py::test_type_check_strict[list-data20-True]",
"tests/test_type_check.py::test_type_check_strict[list-data21-False]",
"tests/test_type_check.py::test_type_check_strict[list-data22-True]",
"tests/test_type_check.py::test_type_check_strict[list-data23-False]",
"tests/test_type_check.py::test_type_check_strict[list-data24-True]",
"tests/test_type_check.py::test_type_check_strict[list-data25-False]",
"tests/test_type_check.py::test_type_check_strict[list-data26-True]",
"tests/test_type_check.py::test_type_check_strict[list-data27-False]",
"tests/test_type_check.py::test_type_check_strict[dict-data28-False]",
"tests/test_type_check.py::test_type_check_strict[dict-data30-False]",
"tests/test_type_check.py::test_type_check_strict[dict-data31-True]",
"tests/test_type_check.py::test_type_check_strict[set-data32-False]",
"tests/test_type_check.py::test_type_check_strict[set-data33-False]",
"tests/test_type_check.py::test_type_check_strict[set-data34-True]",
"tests/test_type_check.py::test_type_check_strict[tuple-data35-False]",
"tests/test_type_check.py::test_type_check_strict[tuple-data36-True]",
"tests/test_type_check.py::test_type_check_strict[tuple-data37-False]",
"tests/test_type_check.py::test_type_check_strict[tuple-data38-True]",
"tests/test_type_check.py::test_type_check_strict[tuple-data39-False]",
"tests/test_type_check.py::test_type_check_strict[tuple-data40-True]",
"tests/test_type_check.py::test_type_check_strict[tuple-data41-False]",
"tests/test_type_check.py::test_type_check_strict[tuple-data42-False]",
"tests/test_type_check.py::test_type_check_strict[E-E.S-False]",
"tests/test_type_check.py::test_type_check_strict[E-IE.V0-True]",
"tests/test_type_check.py::test_type_check_strict[T45-10-False]",
"tests/test_type_check.py::test_type_check_strict[T46-foo-False]",
"tests/test_type_check.py::test_type_check_strict[T47-10.0-True]",
"tests/test_type_check.py::test_type_check_strict[T48-data48-False]",
"tests/test_type_check.py::test_type_check_strict[date-data49-False]",
"tests/test_type_check.py::test_type_check_strict[Path-data50-False]",
"tests/test_type_check.py::test_type_check_strict[Path-foo-True]",
"tests/test_type_check.py::test_uncoercible",
"tests/test_type_check.py::test_coerce"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2024-03-09T15:09:41Z" | mit |
|
zalando-stups__pierone-cli-33 | diff --git a/.gitignore b/.gitignore
index 1e365e8..e60d986 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,3 +12,4 @@ htmlcov/
virtualenv
*.sw*
.cache/
+.tox/
diff --git a/pierone/cli.py b/pierone/cli.py
index 467ff32..1af5790 100644
--- a/pierone/cli.py
+++ b/pierone/cli.py
@@ -1,20 +1,18 @@
import datetime
import os
import re
-
-import click
-
-import requests
import tarfile
import tempfile
import time
-import zign.api
-from clickclick import error, AliasedGroup, print_table, OutputFormat, UrlType
-from .api import docker_login, request, get_latest_tag, DockerImage
+import click
import pierone
+import requests
import stups_cli.config
+import zign.api
+from clickclick import AliasedGroup, OutputFormat, UrlType, error, print_table
+from .api import DockerImage, docker_login, get_latest_tag, request
KEYRING_KEY = 'pierone'
@@ -24,6 +22,48 @@ output_option = click.option('-o', '--output', type=click.Choice(['text', 'json'
help='Use alternative output format')
url_option = click.option('--url', help='Pier One URL', metavar='URI')
+clair_url_option = click.option('--clair-url', help='Clair URL', metavar='CLAIR_URI')
+
+CVE_STYLES = {
+ 'TOO_OLD': {
+ 'bold': True,
+ 'fg': 'red'
+ },
+ 'NOT_PROCESSED_YET': {
+ 'bold': True,
+ 'fg': 'red'
+ },
+ 'COULDNT_FIGURE_OUT': {
+ 'bold': True,
+ 'fg': 'red'
+ },
+ 'CRITICAL': {
+ 'bold': True,
+ 'fg': 'red'
+ },
+ 'HIGH': {
+ 'bold': True,
+ 'fg': 'red'
+ },
+ 'MEDIUM': {
+ 'fg': 'yellow'
+ },
+ 'LOW': {
+ 'fg': 'yellow'
+ },
+ 'NEGLIGIBLE': {
+ 'fg': 'yellow'
+ },
+ 'UNKNOWN': {
+ 'fg': 'yellow'
+ },
+ 'PENDING': {
+ 'fg': 'yellow'
+ },
+ 'NO_CVES_FOUND': {
+ 'fg': 'green'
+ }
+}
TEAM_PATTERN_STR = r'[a-z][a-z0-9-]+'
TEAM_PATTERN = re.compile(r'^{}$'.format(TEAM_PATTERN_STR))
@@ -54,6 +94,19 @@ def parse_time(s: str) -> float:
return None
+def parse_severity(value, clair_id_exists):
+ '''Parse severity values to displayable values'''
+ if value is None and clair_id_exists:
+ return 'NOT_PROCESSED_YET'
+ elif value is None:
+ return 'TOO_OLD'
+
+ value = re.sub('^clair:', '', value)
+ value = re.sub('(?P<upper_letter>(?<=[a-z])[A-Z])', '_\g<upper_letter>', value)
+
+ return value.upper()
+
+
def print_version(ctx, param, value):
if not value or ctx.resilient_parsing:
return
@@ -82,6 +135,28 @@ def set_pierone_url(config: dict, url: str) -> None:
return url
+def set_clair_url(config: dict, url: str) -> None:
+ '''Read Clair URL from cli, from config file or from stdin.'''
+ url = url or config.get('clair_url')
+
+ while not url:
+ url = click.prompt('Please enter the Clair URL', type=UrlType())
+
+ try:
+ requests.get(url, timeout=5)
+ except:
+ error('Could not reach {}'.format(url))
+ url = None
+
+ if '://' not in url:
+ # issue 63: gracefully handle URLs without scheme
+ url = 'https://{}'.format(url)
+
+ config['clair_url'] = url
+ stups_cli.config.store_config(config, 'pierone')
+ return url
+
+
@click.group(cls=AliasedGroup, context_settings=CONTEXT_SETTINGS)
@click.option('-V', '--version', is_flag=True, callback=print_version, expose_value=False, is_eager=True,
help='Print the current version number and exit.')
@@ -147,6 +222,19 @@ def get_tags(url, team, art, access_token):
return r.json()
+def get_clair_features(url, layer_id, access_token):
+ if layer_id is None:
+ return []
+
+ r = request(url, '/v1/layers/{}?vulnerabilities&features'.format(layer_id), access_token)
+ if r.status_code == 404:
+ # empty list of tags (layer does not exist)
+ return []
+ else:
+ r.raise_for_status()
+ return r.json()['Layer']['Features']
+
+
@cli.command()
@click.argument('team', callback=validate_team)
@url_option
@@ -184,14 +272,69 @@ def tags(config, team: str, artifact, url, output):
'artifact': art,
'tag': row['name'],
'created_by': row['created_by'],
- 'created_time': parse_time(row['created'])}
+ 'created_time': parse_time(row['created']),
+ 'severity_fix_available': parse_severity(
+ row.get('severity_fix_available'), row.get('clair_id', False)),
+ 'severity_no_fix_available': parse_severity(
+ row.get('severity_no_fix_available'), row.get('clair_id', False))}
for row in r])
# sorts are guaranteed to be stable, i.e. tags will be sorted by time (as returned from REST service)
rows.sort(key=lambda row: (row['team'], row['artifact']))
with OutputFormat(output):
- print_table(['team', 'artifact', 'tag', 'created_time', 'created_by'], rows,
- titles={'created_time': 'Created', 'created_by': 'By'})
+ titles = {
+ 'created_time': 'Created',
+ 'created_by': 'By',
+ 'severity_fix_available': 'Fixable CVE Severity',
+ 'severity_no_fix_available': 'Unfixable CVE Severity'
+ }
+ print_table(['team', 'artifact', 'tag', 'created_time', 'created_by',
+ 'severity_fix_available', 'severity_no_fix_available'],
+ rows, titles=titles, styles=CVE_STYLES)
+
+
[email protected]()
[email protected]('team', callback=validate_team)
[email protected]('artifact')
[email protected]('tag')
+@url_option
+@clair_url_option
+@output_option
[email protected]_obj
+def cves(config, team, artifact, tag, url, clair_url, output):
+ '''List all CVE's found by Clair service for a specific artifact tag'''
+ set_pierone_url(config, url)
+ set_clair_url(config, clair_url)
+
+ rows = []
+ token = get_token()
+ for artifact_tag in get_tags(config.get('url'), team, artifact, token):
+ if artifact_tag['name'] == tag:
+ installed_software = get_clair_features(config.get('clair_url'), artifact_tag.get('clair_id'), token)
+ for software_pkg in installed_software:
+ for cve in software_pkg.get('Vulnerabilities', []):
+ rows.append({
+ 'cve': cve['Name'],
+ 'severity': cve['Severity'].upper(),
+ 'affected_feature': '{}:{}'.format(software_pkg['Name'],
+ software_pkg['Version']),
+ 'fixing_feature': cve.get(
+ 'FixedBy') and '{}:{}'.format(software_pkg['Name'],
+ cve['FixedBy']),
+ 'link': cve['Link'],
+ })
+ severity_rating = ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW', 'NEGLIGIBLE', 'UNKNOWN', 'PENDING']
+ rows.sort(key=lambda row: severity_rating.index(row['severity']))
+ with OutputFormat(output):
+ titles = {
+ 'cve': 'CVE',
+ 'severity': 'Severity',
+ 'affected_feature': 'Affected Feature',
+ 'fixing_feature': 'Fixing Feature',
+ 'link': 'Link'
+ }
+ print_table(['cve', 'severity', 'affected_feature', 'fixing_feature', 'link'],
+ rows, titles=titles, styles=CVE_STYLES)
@cli.command()
diff --git a/tox.ini b/tox.ini
index aa079ec..4644fe1 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,2 +1,8 @@
[flake8]
max-line-length=120
+
+[tox]
+envlist=py34,py35
+
+[testenv]
+commands=python setup.py test
| zalando-stups/pierone-cli | 903f8e27f3e084fd9116929139a1ccd7f700f42f | diff --git a/setup.py b/setup.py
old mode 100644
new mode 100755
diff --git a/tests/fixtures/clair_response.json b/tests/fixtures/clair_response.json
new file mode 100644
index 0000000..2638daa
--- /dev/null
+++ b/tests/fixtures/clair_response.json
@@ -0,0 +1,70 @@
+{
+ "Layer": {
+ "Name": "sha256:0000000000000000000000000000000000000000000000000000000000000000",
+ "NamespaceName": "ubuntu:16.04",
+ "ParentName": "sha256:0000000000000000000000000000000000000000000000000000000000000000",
+ "IndexedByVersion": 2,
+ "Features": [
+ {
+ "Name": "python3.5",
+ "NamespaceName": "ubuntu:16.04",
+ "Version": "3.5.1-10",
+ "AddedBy": "sha256:0000000000000000000000000000000000000000000000000000000000000000"
+ },
+ {
+ "Name": "python-pip",
+ "NamespaceName": "ubuntu:16.04",
+ "Version": "8.1.1-2",
+ "Vulnerabilities": [
+ {
+ "Name": "CVE-2013-5123",
+ "NamespaceName": "ubuntu:16.04",
+ "Description": "The mirroring support (-M, --use-mirrors) was implemented without any sort of authenticity checks and is downloaded over plaintext HTTP. Further more by default it will dynamically discover the list of available mirrors by querying a DNS entry and extrapolating from that data. It does not attempt to use any sort of method of securing this querying of the DNS like DNSSEC. Software packages are downloaded over these insecure links, unpacked, and then typically the setup.py python file inside of them is executed.",
+ "Link": "http://people.ubuntu.com/~ubuntu-security/cve/CVE-2013-5123",
+ "Severity": "Medium"
+ },
+ {
+ "Name": "CVE-2014-8991",
+ "NamespaceName": "ubuntu:16.04",
+ "Description": "pip 1.3 through 1.5.6 allows local users to cause a denial of service (prevention of package installation) by creating a /tmp/pip-build-* file for another user.",
+ "Link": "http://people.ubuntu.com/~ubuntu-security/cve/CVE-2014-8991",
+ "Severity": "Low",
+ "Metadata": {
+ "NVD": {
+ "CVSSv2": {
+ "Score": 2.1,
+ "Vectors": "AV:L/AC:L/Au:N/C:N/I:N"
+ }
+ }
+ }
+ }
+ ],
+ "AddedBy": "sha256:0000000000000000000000000000000000000000000000000000000000000000"
+ },
+ {
+ "Name": "openssl",
+ "NamespaceName": "ubuntu:16.04",
+ "Version": "1.0.2g-1ubuntu4",
+ "Vulnerabilities": [
+ {
+ "Name": "CVE-2016-2108",
+ "NamespaceName": "ubuntu:16.04",
+ "Description": "The ASN.1 implementation in OpenSSL before 1.0.1o and 1.0.2 before 1.0.2c allows remote attackers to execute arbitrary code or cause a denial of service (buffer underflow and memory corruption) via an ANY field in crafted serialized data, aka the \"negative zero\" issue.",
+ "Link": "http://people.ubuntu.com/~ubuntu-security/cve/CVE-2016-2108",
+ "Severity": "High",
+ "Metadata": {
+ "NVD": {
+ "CVSSv2": {
+ "Score": 10,
+ "Vectors": "AV:N/AC:L/Au:N/C:C/I:C"
+ }
+ }
+ },
+ "FixedBy": "1.0.2g-1ubuntu4.1"
+ }
+ ],
+ "AddedBy": "sha256:0000000000000000000000000000000000000000000000000000000000000000"
+ }
+ ]
+ }
+}
diff --git a/tests/test_api.py b/tests/test_api.py
index 5cb2fc7..3548e01 100644
--- a/tests/test_api.py
+++ b/tests/test_api.py
@@ -1,9 +1,11 @@
import json
import os
from unittest.mock import MagicMock
-import yaml
-from pierone.api import docker_login, DockerImage, get_latest_tag, Unauthorized, image_exists
+
import pytest
+import yaml
+from pierone.api import (DockerImage, Unauthorized, docker_login,
+ get_latest_tag, image_exists)
def test_docker_login(monkeypatch, tmpdir):
@@ -12,22 +14,22 @@ def test_docker_login(monkeypatch, tmpdir):
response.status_code = 200
response.json.return_value = {'access_token': '12377'}
monkeypatch.setattr('requests.get', MagicMock(return_value=response))
- token = docker_login('https://pierone.example.org', 'services', 'mytok',
- 'myuser', 'mypass', 'https://token.example.org', use_keyring=False)
+ docker_login('https://pierone.example.org', 'services', 'mytok',
+ 'myuser', 'mypass', 'https://token.example.org', use_keyring=False)
path = os.path.expanduser('~/.docker/config.json')
with open(path) as fd:
data = yaml.safe_load(fd)
- assert {'auth': 'b2F1dGgyOjEyMzc3', 'email': '[email protected]'} == data.get('auths').get('https://pierone.example.org')
+ assert {'auth': 'b2F1dGgyOjEyMzc3', 'email': '[email protected]'} == data.get('auths').get('https://pierone.example.org')
def test_docker_login_service_token(monkeypatch, tmpdir):
monkeypatch.setattr('os.path.expanduser', lambda x: x.replace('~', str(tmpdir)))
monkeypatch.setattr('tokens.get', lambda x: '12377')
- token = docker_login('https://pierone.example.org', None, 'mytok', 'myuser', 'mypass', 'https://token.example.org')
+ docker_login('https://pierone.example.org', None, 'mytok', 'myuser', 'mypass', 'https://token.example.org')
path = os.path.expanduser('~/.docker/config.json')
with open(path) as fd:
data = yaml.safe_load(fd)
- assert {'auth': 'b2F1dGgyOjEyMzc3', 'email': '[email protected]'} == data.get('auths').get('https://pierone.example.org')
+ assert {'auth': 'b2F1dGgyOjEyMzc3', 'email': '[email protected]'} == data.get('auths').get('https://pierone.example.org')
def test_keep_dockercfg_entries(monkeypatch, tmpdir):
@@ -49,12 +51,12 @@ def test_keep_dockercfg_entries(monkeypatch, tmpdir):
with open(path, 'w') as fd:
json.dump(existing_data, fd)
- token = docker_login('https://pierone.example.org', 'services', 'mytok',
- 'myuser', 'mypass', 'https://token.example.org', use_keyring=False)
+ docker_login('https://pierone.example.org', 'services', 'mytok',
+ 'myuser', 'mypass', 'https://token.example.org', use_keyring=False)
with open(path) as fd:
data = yaml.safe_load(fd)
- assert {'auth': 'b2F1dGgyOjEyMzc3', 'email': '[email protected]'} == data.get('auths', {}).get('https://pierone.example.org')
- assert existing_data.get(key) == data.get(key)
+ assert {'auth': 'b2F1dGgyOjEyMzc3', 'email': '[email protected]'} == data.get('auths', {}).get('https://pierone.example.org')
+ assert existing_data.get(key) == data.get(key)
def test_get_latest_tag(monkeypatch):
diff --git a/tests/test_cli.py b/tests/test_cli.py
index 6f58d15..6282253 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -1,9 +1,9 @@
import json
import os
-from click.testing import CliRunner
+import re
from unittest.mock import MagicMock
-import yaml
-import zign.api
+
+from click.testing import CliRunner
from pierone.cli import cli
@@ -40,6 +40,7 @@ def test_login_given_url_option(monkeypatch, tmpdir):
runner = CliRunner()
config = {}
+
def store(data, section):
config.update(**data)
@@ -50,9 +51,9 @@ def test_login_given_url_option(monkeypatch, tmpdir):
monkeypatch.setattr('requests.get', lambda x, timeout: response)
with runner.isolated_filesystem():
- result = runner.invoke(cli, ['login'], catch_exceptions=False, input='pieroneurl\n')
+ runner.invoke(cli, ['login'], catch_exceptions=False, input='pieroneurl\n')
assert config == {'url': 'https://pieroneurl'}
- result = runner.invoke(cli, ['login', '--url', 'someotherregistry'], catch_exceptions=False)
+ runner.invoke(cli, ['login', '--url', 'someotherregistry'], catch_exceptions=False)
with open(os.path.join(str(tmpdir), '.docker/config.json')) as fd:
data = json.load(fd)
assert data['auths']['https://pieroneurl']['auth'] == 'b2F1dGgyOnRvazEyMw=='
@@ -65,7 +66,7 @@ def test_scm_source(monkeypatch, tmpdir):
response.json.return_value = {'url': 'git:somerepo', 'revision': 'myrev123'}
runner = CliRunner()
- monkeypatch.setattr('stups_cli.config.load_config', lambda x: {'url':'foobar'})
+ monkeypatch.setattr('stups_cli.config.load_config', lambda x: {'url': 'foobar'})
monkeypatch.setattr('zign.api.get_token', MagicMock(return_value='tok123'))
monkeypatch.setattr('pierone.cli.get_tags', MagicMock(return_value={}))
monkeypatch.setattr('os.path.expanduser', lambda x: x.replace('~', str(tmpdir)))
@@ -75,12 +76,13 @@ def test_scm_source(monkeypatch, tmpdir):
assert 'myrev123' in result.output
assert 'git:somerepo' in result.output
+
def test_image(monkeypatch, tmpdir):
response = MagicMock()
response.json.return_value = [{'name': '1.0', 'team': 'stups', 'artifact': 'kio'}]
runner = CliRunner()
- monkeypatch.setattr('stups_cli.config.load_config', lambda x: {'url':'foobar'})
+ monkeypatch.setattr('stups_cli.config.load_config', lambda x: {'url': 'foobar'})
monkeypatch.setattr('zign.api.get_token', MagicMock(return_value='tok123'))
monkeypatch.setattr('os.path.expanduser', lambda x: x.replace('~', str(tmpdir)))
monkeypatch.setattr('pierone.api.session.get', MagicMock(return_value=response))
@@ -93,16 +95,130 @@ def test_image(monkeypatch, tmpdir):
def test_tags(monkeypatch, tmpdir):
response = MagicMock()
- response.json.return_value = [{'name': '1.0', 'created_by': 'myuser', 'created': '2015-08-20T08:14:59.432Z'}]
+ response.json.return_value = [
+ # Former pierone payload
+ {
+ 'name': '1.0',
+ 'created_by': 'myuser',
+ 'created': '2015-08-20T08:14:59.432Z'
+ },
+ # New pierone payload with clair but no information about CVEs -- old images
+ {
+ "name": "1.1",
+ "created": "2016-05-19T15:23:41.065Z",
+ "created_by": "myuser",
+ "image": "sha256:here",
+ "clair_id": None,
+ "severity_fix_available": None,
+ "severity_no_fix_available": None
+ },
+ # New pierone payload with clair but no information about CVEs -- still processing
+ {
+ "name": "1.1",
+ "created": "2016-05-19T15:23:41.065Z",
+ "created_by": "myuser",
+ "image": "sha256:here",
+ "clair_id": "sha256:here",
+ "severity_fix_available": None,
+ "severity_no_fix_available": None
+ },
+ # New pierone payload with clair but could not figure out
+ {
+ "name": "1.1",
+ "created": "2016-05-19T15:23:41.065Z",
+ "created_by": "myuser",
+ "image": "sha256:here",
+ "clair_id": "sha256:here",
+ "severity_fix_available": "clair:CouldntFigureOut",
+ "severity_no_fix_available": "clair:CouldntFigureOut"
+ },
+ # New pierone payload with clair with no CVEs found
+ {
+ "name": "1.1",
+ "created": "2016-05-19T15:23:41.065Z",
+ "created_by": "myuser",
+ "image": "sha256:here",
+ "clair_id": "sha256:here",
+ "severity_fix_available": "clair:NoCVEsFound",
+ "severity_no_fix_available": "clair:NoCVEsFound"
+ },
+ # New pierone payload with clair input and info about CVEs
+ {
+ "name": "1.2",
+ "created": "2016-05-23T13:29:17.753Z",
+ "created_by": "myuser",
+ "image": "sha256:here",
+ "clair_id": "sha256:here",
+ "severity_fix_available": "High",
+ "severity_no_fix_available": "Medium"
+ }
+ ]
runner = CliRunner()
- monkeypatch.setattr('stups_cli.config.load_config', lambda x: {'url':'foobar'})
+ monkeypatch.setattr('stups_cli.config.load_config', lambda x: {'url': 'foobar'})
monkeypatch.setattr('zign.api.get_token', MagicMock(return_value='tok123'))
monkeypatch.setattr('os.path.expanduser', lambda x: x.replace('~', str(tmpdir)))
monkeypatch.setattr('pierone.api.session.get', MagicMock(return_value=response))
with runner.isolated_filesystem():
result = runner.invoke(cli, ['tags', 'myteam', 'myart'], catch_exceptions=False)
assert '1.0' in result.output
+ assert 'Fixable CVE Severity' in result.output
+ assert 'Unfixable CVE Severity' in result.output
+ assert 'TOO_OLD' in result.output
+ assert 'NOT_PROCESSED_YET' in result.output
+ assert 'NO_CVES_FOUND' in result.output
+ assert re.search('HIGH\s+MEDIUM', result.output), 'Should how information about CVEs'
+
+
+def test_cves(monkeypatch, tmpdir):
+ pierone_service_payload = [
+ # Former pierone payload
+ {
+ 'name': '1.0',
+ 'created_by': 'myuser',
+ 'created': '2015-08-20T08:14:59.432Z'
+ },
+ # New pierone payload with clair but no information about CVEs
+ {
+ "name": "1.1",
+ "created": "2016-05-19T15:23:41.065Z",
+ "created_by": "myuser",
+ "image": "sha256:here",
+ "clair_id": None,
+ "severity_fix_available": None,
+ "severity_no_fix_available": None
+ },
+ # New pierone payload with clair input and info about CVEs
+ {
+ "name": "1.2",
+ "created": "2016-05-23T13:29:17.753Z",
+ "created_by": "myuser",
+ "image": "sha256:here",
+ "clair_id": "sha256:here",
+ "severity_fix_available": "High",
+ "severity_no_fix_available": "Medium"
+ }
+ ]
+
+ with open(os.path.join(os.path.dirname(__file__),
+ 'fixtures', 'clair_response.json'), 'r') as fixture:
+ clair_service_payload = json.loads(fixture.read())
+
+ response = MagicMock()
+ response.json.side_effect = [
+ pierone_service_payload,
+ clair_service_payload
+ ]
+
+ runner = CliRunner()
+ monkeypatch.setattr('stups_cli.config.load_config', lambda x: {'url': 'foobar', 'clair_url': 'barfoo'})
+ monkeypatch.setattr('zign.api.get_token', MagicMock(return_value='tok123'))
+ monkeypatch.setattr('os.path.expanduser', lambda x: x.replace('~', str(tmpdir)))
+ monkeypatch.setattr('pierone.api.session.get', MagicMock(return_value=response))
+ with runner.isolated_filesystem():
+ result = runner.invoke(cli, ['cves', 'myteam', 'myart', '1.2'], catch_exceptions=False)
+ assert 'CVE-2013-5123' in result.output
+ assert re.match('[^\n]+\n[^\n]+HIGH', result.output), 'Results should be ordered by highest priority'
def test_latest(monkeypatch, tmpdir):
| Display Clair security information.
PierOne now supports Clair for vulnerability scanning. Pierone now exposes the following three information for each tag:
- clair_id
- severity_fix_available
- severity_no_fix_available
The PierOne CLI should now also enhance the `tags` subcommand with these information and provide a new `cves` subcommand to display full CVE reports.
$ pierone tags foo bar
Team | Artifact | Tag | Created | By | Fixable CVE Severity | Unfixable CVE Severity |
--------|-----------|-------|------------|-----|-----------------------|--------------------------
foo | bar | 1.0 | 5d ago | example | **Critical** | Medium |
foo | bar | 1.1 | 2d ago | example | **Critical** | Medium |
foo | bar | 2.0 | 1d ago | example | None | Medium |
`High` and `Critical` severities should be highlighted.
$ pierone cves foo bar 1.0
CVE | Severity | Affected Feature | Fixing Feature | Link
-------|------------|------------------------|---------------------|-------
CVE-2014-9471 | Low | coreutils:8.23-4 | coreutils:9.23-5 | https://security-tracker.debian.org/tracker/CVE-2014-9471
Again, `High` and `Critical` needs to be highlighted and the whole table should be sorted by severity. PierOne source contains an ordered list of possible values.
The information for this output can be retrieved via the [Clair API](https://github.com/coreos/clair/blob/master/api/v1/README.md#get-layersname) using the PierOne provided Clair ID. For this, the PierOne CLI will need to learn about the Clair API's endpoint. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_cli.py::test_tags",
"tests/test_cli.py::test_cves"
] | [
"tests/test_api.py::test_docker_login_service_token",
"tests/test_api.py::test_get_latest_tag",
"tests/test_api.py::test_get_latest_tag_IOException",
"tests/test_api.py::test_get_latest_tag_non_json",
"tests/test_api.py::test_unauthorized",
"tests/test_api.py::test_image_exists",
"tests/test_api.py::test_image_exists_IOException",
"tests/test_api.py::test_image_exists_but_other_version",
"tests/test_api.py::test_image_not_exists",
"tests/test_cli.py::test_version",
"tests/test_cli.py::test_login",
"tests/test_cli.py::test_login_given_url_option",
"tests/test_cli.py::test_scm_source",
"tests/test_cli.py::test_image",
"tests/test_cli.py::test_latest",
"tests/test_cli.py::test_latest_not_found",
"tests/test_cli.py::test_url_without_scheme"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2016-05-26T16:17:11Z" | apache-2.0 |
|
zalando-stups__pierone-cli-37 | diff --git a/pierone/cli.py b/pierone/cli.py
index 1af5790..50dba86 100644
--- a/pierone/cli.py
+++ b/pierone/cli.py
@@ -232,7 +232,8 @@ def get_clair_features(url, layer_id, access_token):
return []
else:
r.raise_for_status()
- return r.json()['Layer']['Features']
+
+ return r.json()['Layer'].get('Features', [])
@cli.command()
| zalando-stups/pierone-cli | 991c05e9c7496b2aac071d85d0a9ca6b8afcf9dd | diff --git a/tests/test_cli.py b/tests/test_cli.py
index 6282253..087d27d 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -221,6 +221,61 @@ def test_cves(monkeypatch, tmpdir):
assert re.match('[^\n]+\n[^\n]+HIGH', result.output), 'Results should be ordered by highest priority'
+def test_no_cves_found(monkeypatch, tmpdir):
+ pierone_service_payload = [
+ # Former pierone payload
+ {
+ 'name': '1.0',
+ 'created_by': 'myuser',
+ 'created': '2015-08-20T08:14:59.432Z'
+ },
+ # New pierone payload with clair but no information about CVEs
+ {
+ "name": "1.1",
+ "created": "2016-05-19T15:23:41.065Z",
+ "created_by": "myuser",
+ "image": "sha256:here",
+ "clair_id": None,
+ "severity_fix_available": None,
+ "severity_no_fix_available": None
+ },
+ # New pierone payload with clair input and info about CVEs
+ {
+ "name": "1.2",
+ "created": "2016-05-23T13:29:17.753Z",
+ "created_by": "myuser",
+ "image": "sha256:here",
+ "clair_id": "sha256:here",
+ "severity_fix_available": "High",
+ "severity_no_fix_available": "Medium"
+ }
+ ]
+
+ no_cves_clair_payload = {
+ "Layer": {
+ "Name": "sha256:0000000000000000000000000000000000000000000000000000000000000000",
+ "NamespaceName": "ubuntu:16.04",
+ "ParentName": "sha256:0000000000000000000000000000000000000000000000000000000000000000",
+ "IndexedByVersion": 2
+ }
+ }
+
+ response = MagicMock()
+ response.json.side_effect = [
+ pierone_service_payload,
+ no_cves_clair_payload
+ ]
+
+ runner = CliRunner()
+ monkeypatch.setattr('stups_cli.config.load_config', lambda x: {'url': 'foobar', 'clair_url': 'barfoo'})
+ monkeypatch.setattr('zign.api.get_token', MagicMock(return_value='tok123'))
+ monkeypatch.setattr('os.path.expanduser', lambda x: x.replace('~', str(tmpdir)))
+ monkeypatch.setattr('pierone.api.session.get', MagicMock(return_value=response))
+ with runner.isolated_filesystem():
+ result = runner.invoke(cli, ['cves', 'myteam', 'myart', '1.2'], catch_exceptions=False)
+ assert re.match('^[^\n]+\n$', result.output), 'No results should be shown'
+
+
def test_latest(monkeypatch, tmpdir):
response = MagicMock()
response.json.return_value = [
| pierone fails with backtrace when the CVE status is COULDNT_FIGURE_OUT
```
Traceback (most recent call last):
File "/usr/local/bin/pierone", line 11, in <module>
sys.exit(main())
File "/usr/local/lib/python3.4/dist-packages/pierone/cli.py", line 485, in main
cli()
File "/usr/local/lib/python3.4/dist-packages/click/core.py", line 716, in __call__
return self.main(*args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/click/core.py", line 696, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python3.4/dist-packages/click/core.py", line 1060, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python3.4/dist-packages/click/core.py", line 889, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python3.4/dist-packages/click/core.py", line 534, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/click/decorators.py", line 27, in new_func
return f(get_current_context().obj, *args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/pierone/cli.py", line 313, in cves
installed_software = get_clair_features(config.get('clair_url'), artifact_tag.get('clair_id'), token)
File "/usr/local/lib/python3.4/dist-packages/pierone/cli.py", line 235, in get_clair_features
return r.json()['Layer']['Features']
KeyError: 'Features'
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_cli.py::test_no_cves_found"
] | [
"tests/test_cli.py::test_version",
"tests/test_cli.py::test_login",
"tests/test_cli.py::test_login_given_url_option",
"tests/test_cli.py::test_scm_source",
"tests/test_cli.py::test_image",
"tests/test_cli.py::test_tags",
"tests/test_cli.py::test_cves",
"tests/test_cli.py::test_latest",
"tests/test_cli.py::test_latest_not_found",
"tests/test_cli.py::test_url_without_scheme"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2016-05-31T08:47:53Z" | apache-2.0 |
|
zalando-stups__pierone-cli-49 | diff --git a/.travis.yml b/.travis.yml
index e417a33..7c746c5 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -4,6 +4,7 @@ python:
install:
- pip install -r requirements.txt
- pip install coveralls
+ - pip install flake8 # forcing installation of flake8, might be removed after https://gitlab.com/pycqa/flake8/issues/164 gets fixed.
script:
- python setup.py test
- python setup.py flake8
diff --git a/pierone/cli.py b/pierone/cli.py
index 90bb5c2..8918a42 100644
--- a/pierone/cli.py
+++ b/pierone/cli.py
@@ -8,7 +8,9 @@ import pierone
import requests
import stups_cli.config
import zign.api
-from clickclick import AliasedGroup, OutputFormat, UrlType, error, print_table
+from clickclick import (AliasedGroup, OutputFormat, UrlType, error,
+ fatal_error, print_table)
+from requests import RequestException
from .api import (DockerImage, Unauthorized, docker_login, get_image_tags,
get_latest_tag, parse_time, request)
@@ -76,6 +78,17 @@ def print_version(ctx, param, value):
ctx.exit()
+def validate_pierone_url(url: str) -> None:
+ ping_url = url.rstrip('/') + '/swagger.json'
+ try:
+ response = requests.get(ping_url, timeout=5)
+ response.raise_for_status()
+ if 'Pier One API' not in response.text:
+ fatal_error('ERROR: Did not find a valid Pier One registry at {}'.format(url))
+ except RequestException:
+ fatal_error('ERROR: Could not reach {}'.format(ping_url))
+
+
def set_pierone_url(config: dict, url: str) -> None:
'''Read Pier One URL from cli, from config file or from stdin.'''
url = url or config.get('url')
@@ -93,6 +106,7 @@ def set_pierone_url(config: dict, url: str) -> None:
# issue 63: gracefully handle URLs without scheme
url = 'https://{}'.format(url)
+ validate_pierone_url(url)
config['url'] = url
return url
| zalando-stups/pierone-cli | 9f99c8f5a054c35b623c0601e66da0c15fdb578a | diff --git a/tests/test_cli.py b/tests/test_cli.py
index e76073c..0bdd2fe 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -3,8 +3,17 @@ import os
import re
from unittest.mock import MagicMock
+import pytest
from click.testing import CliRunner
from pierone.cli import cli
+from requests import RequestException
+
+
[email protected](autouse=True)
+def valid_pierone_url(monkeypatch):
+ response = MagicMock()
+ response.text = 'Pier One API'
+ monkeypatch.setattr('requests.get', lambda *args, **kw: response)
def test_version(monkeypatch):
@@ -16,22 +25,47 @@ def test_version(monkeypatch):
def test_login(monkeypatch, tmpdir):
- response = MagicMock()
-
runner = CliRunner()
monkeypatch.setattr('stups_cli.config.load_config', lambda x: {})
monkeypatch.setattr('pierone.api.get_named_token', MagicMock(return_value={'access_token': 'tok123'}))
monkeypatch.setattr('os.path.expanduser', lambda x: x.replace('~', str(tmpdir)))
- monkeypatch.setattr('requests.get', lambda x, timeout: response)
with runner.isolated_filesystem():
result = runner.invoke(cli, ['login'], catch_exceptions=False, input='pieroneurl\n')
+ assert 'Storing Docker client configuration' in result.output
+ assert result.output.rstrip().endswith('OK')
with open(os.path.join(str(tmpdir), '.docker/config.json')) as fd:
data = json.load(fd)
assert data['auths']['https://pieroneurl']['auth'] == 'b2F1dGgyOnRvazEyMw=='
- assert 'Storing Docker client configuration' in result.output
- assert result.output.rstrip().endswith('OK')
+
+
+def test_invalid_url_for_login(monkeypatch, tmpdir):
+ runner = CliRunner()
+ response = MagicMock()
+
+ monkeypatch.setattr('stups_cli.config.load_config', lambda x: {})
+ monkeypatch.setattr('pierone.api.get_named_token', MagicMock(return_value={'access_token': 'tok123'}))
+ monkeypatch.setattr('os.path.expanduser', lambda x: x.replace('~', str(tmpdir)))
+
+ # Missing Pier One header
+ response.text = 'Not valid API'
+ monkeypatch.setattr('requests.get', lambda *args, **kw: response)
+
+ with runner.isolated_filesystem():
+ result = runner.invoke(cli, ['login'], catch_exceptions=False, input='pieroneurl\n')
+ assert 'ERROR: Did not find a valid Pier One registry at https://pieroneurl' in result.output
+ assert result.exit_code == 1
+ assert not os.path.exists(os.path.join(str(tmpdir), '.docker/config.json'))
+
+ # Not a valid header
+ response.raise_for_status = MagicMock(side_effect=RequestException)
+ monkeypatch.setattr('requests.get', lambda *args, **kw: response)
+ with runner.isolated_filesystem():
+ result = runner.invoke(cli, ['login'], catch_exceptions=False, input='pieroneurl\n')
+ assert 'ERROR: Could not reach https://pieroneurl' in result.output
+ assert result.exit_code == 1
+ assert not os.path.exists(os.path.join(str(tmpdir), '.docker/config.json'))
def test_login_arg_user(monkeypatch, tmpdir):
@@ -95,8 +129,6 @@ def test_login_env_user(monkeypatch, tmpdir):
def test_login_given_url_option(monkeypatch, tmpdir):
- response = MagicMock()
-
runner = CliRunner()
config = {}
@@ -108,7 +140,6 @@ def test_login_given_url_option(monkeypatch, tmpdir):
monkeypatch.setattr('stups_cli.config.store_config', store)
monkeypatch.setattr('pierone.api.get_named_token', MagicMock(return_value={'access_token': 'tok123'}))
monkeypatch.setattr('os.path.expanduser', lambda x: x.replace('~', str(tmpdir)))
- monkeypatch.setattr('requests.get', lambda x, timeout: response)
with runner.isolated_filesystem():
runner.invoke(cli, ['login'], catch_exceptions=False, input='pieroneurl\n')
| Pierone login accepts any URL
Would be nice to validate if the pierone URL is actually valid. Maybe pinging the address to see if it works and showing an error. The current behaviour leads to user that committed a typo in the pierone URL to think they are logged-in and getting error from `docker push` later with a not very helpful message.
### Current behaviour
Example of what currently happens:
```
$ pierone login --url registry.does-not-exist.example.com
Getting OAuth2 token "pierone".. OK
Storing Docker client configuration in /home/master/.docker/config.json.. OK
```
Then trying to push image using docker cli:
```
$ docker push pierone.opensource.zalan.do/bus/hello:b17
The push refers to a repository [pierone.opensource.zalan.do/bus/hello]
9c445b8a75e0: Preparing
8a48ff634f1d: Preparing
...
19429b698a22: Waiting
9436069b92a3: Waiting
no basic auth credentials
```
This leads users to think there is a problem with Pierone registry or with Docker which is misleading.
### Suggested behaviour
When trying to login in pierone with a URL of non-pierone server:
```
$ pierone login --url registry.does-not-exist.example.com
ERROR: Not found a valid Pierone registry at registry.does-not-exist.example.com
```
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_cli.py::test_invalid_url_for_login"
] | [
"tests/test_cli.py::test_version",
"tests/test_cli.py::test_login",
"tests/test_cli.py::test_login_arg_user",
"tests/test_cli.py::test_login_zign_user",
"tests/test_cli.py::test_login_env_user",
"tests/test_cli.py::test_login_given_url_option",
"tests/test_cli.py::test_scm_source",
"tests/test_cli.py::test_image",
"tests/test_cli.py::test_tags",
"tests/test_cli.py::test_tags_versions_limit",
"tests/test_cli.py::test_cves",
"tests/test_cli.py::test_no_cves_found",
"tests/test_cli.py::test_latest",
"tests/test_cli.py::test_latest_not_found",
"tests/test_cli.py::test_url_without_scheme"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2016-07-19T12:50:26Z" | apache-2.0 |
|
zalando-stups__pierone-cli-61 | diff --git a/pierone/api.py b/pierone/api.py
index 35542be..9b0c76a 100644
--- a/pierone/api.py
+++ b/pierone/api.py
@@ -71,6 +71,9 @@ def docker_login_with_token(url, access_token):
basic_auth = codecs.encode('oauth2:{}'.format(access_token).encode('utf-8'), 'base64').strip().decode('utf-8')
if 'auths' not in dockercfg:
dockercfg['auths'] = {}
+ if 'credsStore' in dockercfg:
+ del dockercfg['credsStore']
+
dockercfg['auths'][url] = {'auth': basic_auth,
'email': '[email protected]'}
with Action('Storing Docker client configuration in {}..'.format(path)):
| zalando-stups/pierone-cli | 0afce92aedf654855ad35b90623410e6d6c261dd | diff --git a/tests/test_api.py b/tests/test_api.py
index 62e1f0a..3ee83be 100644
--- a/tests/test_api.py
+++ b/tests/test_api.py
@@ -21,6 +21,29 @@ def test_docker_login(monkeypatch, tmpdir):
assert {'auth': 'b2F1dGgyOjEyMzc3',
'email': '[email protected]'} == data.get('auths').get('https://pierone.example.org')
+def test_docker_login_with_credsstore(monkeypatch, tmpdir):
+ monkeypatch.setattr('os.path.expanduser', lambda x: x.replace('~', str(tmpdir)))
+ monkeypatch.setattr('pierone.api.get_token', MagicMock(return_value='12377'))
+ path = os.path.expanduser('~/.docker/config.json')
+ os.makedirs(os.path.dirname(path))
+ with open(path, 'w') as fd:
+ json.dump({
+ "auths": {
+ "https://pierone.stups.zalan.do": {
+ "auth": "xxx",
+ "email": "[email protected]"
+ }
+ },
+ "credsStore": "osxkeychain"
+ }, fd)
+ docker_login('https://pierone.example.org', 'services', 'mytok',
+ 'myuser', 'mypass', 'https://token.example.org', use_keyring=False)
+ with open(path) as fd:
+ data = yaml.safe_load(fd)
+ assert {'auth': 'b2F1dGgyOjEyMzc3',
+ 'email': '[email protected]'} == data.get('auths').get('https://pierone.example.org')
+ assert 'credsStore' not in data
+
def test_docker_login_service_token(monkeypatch, tmpdir):
monkeypatch.setattr('os.path.expanduser', lambda x: x.replace('~', str(tmpdir)))
| no basic auth credentials
Today I had an auth issue. While trying to do `docker push` I was getting the following log:
➜ pierone login
Getting OAuth2 token "pierone".. OK
Storing Docker client configuration in /Users/whoever/.docker/config.json.. OK
➜ docker push myrepo/...
The push refers to a repository [myrepo/...]
a5f591aacc10: Preparing
...
cb11ba605400: Waiting
no basic auth credentials
Recreating `~/config.json` saved me.
There was `"credsStore": "osxkeychain"` setting In the previous version of the `~/config.json` which was causing me troubles.
BTW
mac os 10.12.3
pierone cli 1.1.27
docker 17.06.0-ce, build 02c1d87 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_api.py::test_docker_login_with_credsstore"
] | [
"tests/test_api.py::test_docker_login",
"tests/test_api.py::test_docker_login_service_token",
"tests/test_api.py::test_docker_login_with_iid",
"tests/test_api.py::test_keep_dockercfg_entries",
"tests/test_api.py::test_get_latest_tag",
"tests/test_api.py::test_get_latest_tag_IOException",
"tests/test_api.py::test_get_latest_tag_non_json",
"tests/test_api.py::test_image_exists",
"tests/test_api.py::test_image_exists_IOException",
"tests/test_api.py::test_image_exists_but_other_version",
"tests/test_api.py::test_image_not_exists",
"tests/test_api.py::test_get_image_tags",
"tests/test_api.py::test_get_image_tag",
"tests/test_api.py::test_get_image_tag_that_does_not_exist"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2017-08-25T13:13:09Z" | apache-2.0 |
|
zalando-stups__senza-280 | diff --git a/senza/manaus/acm.py b/senza/manaus/acm.py
index 0c16faa..ad918e8 100644
--- a/senza/manaus/acm.py
+++ b/senza/manaus/acm.py
@@ -80,16 +80,16 @@ class ACMCertificate:
arn = certificate['CertificateArn']
subject_alternative_name = certificate['SubjectAlternativeNames']
domain_validation_options = certificate['DomainValidationOptions']
- serial = certificate['Serial']
subject = certificate['Subject']
- issuer = certificate['Issuer']
created_at = certificate['CreatedAt']
- issued_at = certificate['IssuedAt']
status = certificate['Status']
- not_before = certificate['NotBefore']
- not_after = certificate['NotAfter']
signature_algorithm = certificate['SignatureAlgorithm']
in_use_by = certificate['InUseBy']
+ serial = certificate.get('Serial')
+ issuer = certificate.get('Issuer')
+ issued_at = certificate.get('IssuedAt')
+ not_before = certificate.get('NotBefore')
+ not_after = certificate.get('NotAfter')
revoked_at = certificate.get('RevokedAt')
revocation_reason = certificate.get('RevocationReason')
| zalando-stups/senza | 46c3172d27a4e02375f71a3aee408e73c668b5e0 | diff --git a/tests/test_manaus/test_acm.py b/tests/test_manaus/test_acm.py
index 13691ed..51e12d4 100644
--- a/tests/test_manaus/test_acm.py
+++ b/tests/test_manaus/test_acm.py
@@ -85,6 +85,24 @@ CERT2 = {'CertificateArn': 'arn:aws:acm:eu-west-1:cert2',
'*.senza.aws.example.net',
'*.app.example.net']}
+CERT_VALIDATION_TIMED_OUT = {
+ 'KeyAlgorithm': 'RSA-2048',
+ 'DomainName': 'alpha.example.org',
+ 'InUseBy': [],
+ 'CreatedAt': datetime(2016, 7, 11, 15, 15, 30),
+ 'SubjectAlternativeNames': ['alpha.example.org'],
+ 'SignatureAlgorithm': 'SHA256WITHRSA',
+ 'Status': 'VALIDATION_TIMED_OUT',
+ 'DomainValidationOptions': [{'DomainName': 'alpha.example.org',
+ 'ValidationEmails': ['[email protected]',
+ '[email protected]',
+ '[email protected]',
+ '[email protected]',
+ '[email protected]'],
+ 'ValidationDomain': 'alpha.example.org'}],
+ 'CertificateArn': 'arn:aws:acm:eu-central-1:123123:certificate/f8a0fa1a-381b-44b6-ab10-1b94ba1480a1',
+ 'Subject': 'CN=alpha.example.org'}
+
def test_certificate_valid():
certificate1 = ACMCertificate.from_boto_dict(CERT1)
@@ -108,6 +126,9 @@ def test_certificate_valid():
assert not certificate1_revoked.is_valid(when=datetime(2013, 4, 2, 10, 11, 12,
tzinfo=timezone.utc))
+ cert_invalid = ACMCertificate.from_boto_dict(CERT_VALIDATION_TIMED_OUT)
+ assert not cert_invalid.is_valid()
+
def test_certificate_comparison():
cert2 = CERT1.copy()
| ACM Cert lookup fails with KeyError
```
Generating Cloud Formation template.. EXCEPTION OCCURRED: 'Serial'
Unknown Error: 'Serial'.
Please create an issue with the content of /tmp/senza-traceback-078eseqg
$ cat /tmp/senza-traceback-078eseqg
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/senza/error_handling.py", line 69, in __call__
self.function(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/click/core.py", line 716, in __call__
return self.main(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/click/core.py", line 696, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python3.5/dist-packages/click/core.py", line 1060, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python3.5/dist-packages/click/core.py", line 889, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python3.5/dist-packages/click/core.py", line 534, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/senza/cli.py", line 555, in create
data = create_cf_template(definition, region, version, parameter, force, parameter_file)
File "/usr/local/lib/python3.5/dist-packages/senza/cli.py", line 638, in create_cf_template
data = evaluate(definition.copy(), args, account_info, force)
File "/usr/local/lib/python3.5/dist-packages/senza/cli.py", line 239, in evaluate
definition = componentfn(definition, configuration, args, info, force, account_info)
File "/usr/local/lib/python3.5/dist-packages/senza/components/weighted_dns_elastic_load_balancer.py", line 29, in component_weighted_dns_elastic_load_balancer
return component_elastic_load_balancer(definition, configuration, args, info, force, account_info)
File "/usr/local/lib/python3.5/dist-packages/senza/components/elastic_load_balancer.py", line 110, in component_elastic_load_balancer
listeners = configuration.get('Listeners') or get_listeners(subdomain, main_zone, configuration)
File "/usr/local/lib/python3.5/dist-packages/senza/components/elastic_load_balancer.py", line 48, in get_listeners
reverse=True)
File "/usr/local/lib/python3.5/dist-packages/senza/manaus/acm.py", line 173, in get_certificates
certificate = ACMCertificate.get_by_arn(arn)
File "/usr/local/lib/python3.5/dist-packages/senza/manaus/acm.py", line 110, in get_by_arn
return cls.from_boto_dict(certificate)
File "/usr/local/lib/python3.5/dist-packages/senza/manaus/acm.py", line 83, in from_boto_dict
serial = certificate['Serial']
KeyError: 'Serial'
```
The cert has status "'VALIDATION_TIMED_OUT" in the error case. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_manaus/test_acm.py::test_certificate_valid"
] | [
"tests/test_manaus/test_acm.py::test_certificate_comparison",
"tests/test_manaus/test_acm.py::test_certificate_get_by_arn",
"tests/test_manaus/test_acm.py::test_certificate_matches",
"tests/test_manaus/test_acm.py::test_get_certificates",
"tests/test_manaus/test_acm.py::test_arn_is_acm_certificate"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2016-07-26T14:24:47Z" | apache-2.0 |
|
zalando-stups__senza-282 | diff --git a/senza/components/elastic_load_balancer.py b/senza/components/elastic_load_balancer.py
index 347b515..5644c13 100644
--- a/senza/components/elastic_load_balancer.py
+++ b/senza/components/elastic_load_balancer.py
@@ -2,6 +2,7 @@ import click
from clickclick import fatal_error
from senza.aws import resolve_security_groups
+from ..cli import AccountArguments, TemplateArguments
from ..manaus import ClientError
from ..manaus.iam import IAM, IAMServerCertificate
from ..manaus.acm import ACM, ACMCertificate
@@ -23,13 +24,14 @@ def get_load_balancer_name(stack_name: str, stack_version: str):
return '{}-{}'.format(stack_name[:l], stack_version)
-def get_listeners(subdomain, main_zone, configuration):
+def get_listeners(subdomain, main_zone, configuration,
+ account_info: AccountArguments):
ssl_cert = configuration.get('SSLCertificateId')
if ACMCertificate.arn_is_acm_certificate(ssl_cert):
# check if certificate really exists
try:
- ACMCertificate.get_by_arn(ssl_cert)
+ ACMCertificate.get_by_arn(account_info.Region, ssl_cert)
except ClientError as e:
error_msg = e.response['Error']['Message']
fatal_error(error_msg)
@@ -44,7 +46,8 @@ def get_listeners(subdomain, main_zone, configuration):
iam_pattern = main_zone.lower().rstrip('.').replace('.', '-')
name = '{sub}.{zone}'.format(sub=subdomain,
zone=main_zone.rstrip('.'))
- acm_certificates = sorted(ACM.get_certificates(domain_name=name),
+ acm = ACM(account_info.Region)
+ acm_certificates = sorted(acm.get_certificates(domain_name=name),
reverse=True)
else:
iam_pattern = ''
@@ -79,9 +82,13 @@ def get_listeners(subdomain, main_zone, configuration):
]
-def component_elastic_load_balancer(definition, configuration, args, info, force, account_info):
+def component_elastic_load_balancer(definition,
+ configuration: dict,
+ args: TemplateArguments,
+ info: dict,
+ force,
+ account_info: AccountArguments):
lb_name = configuration["Name"]
-
# domains pointing to the load balancer
subdomain = ''
main_zone = None
@@ -107,7 +114,7 @@ def component_elastic_load_balancer(definition, configuration, args, info, force
subdomain = domain['Subdomain']
main_zone = domain['Zone'] # type: str
- listeners = configuration.get('Listeners') or get_listeners(subdomain, main_zone, configuration)
+ listeners = configuration.get('Listeners') or get_listeners(subdomain, main_zone, configuration, account_info)
health_check_protocol = "HTTP"
allowed_health_check_protocols = ("HTTP", "TCP", "UDP", "SSL")
diff --git a/senza/manaus/acm.py b/senza/manaus/acm.py
index ad918e8..d28fe26 100644
--- a/senza/manaus/acm.py
+++ b/senza/manaus/acm.py
@@ -101,11 +101,11 @@ class ACMCertificate:
revoked_at, revocation_reason)
@classmethod
- def get_by_arn(cls, arn: str) -> "ACMCertificate":
+ def get_by_arn(cls, region: str, arn: str) -> "ACMCertificate":
"""
Gets a ACMCertificate based on ARN alone
"""
- client = boto3.client('acm')
+ client = boto3.client('acm', region)
certificate = client.describe_certificate(CertificateArn=arn)['Certificate']
return cls.from_boto_dict(certificate)
@@ -156,21 +156,26 @@ class ACM:
See http://boto3.readthedocs.io/en/latest/reference/services/acm.html
"""
- @staticmethod
- def get_certificates(valid_only: bool=True,
+ def __init__(self, region=str):
+ self.region = region
+
+ def get_certificates(self,
+ *,
+ valid_only: bool=True,
domain_name: Optional[str]=None) -> Iterator[ACMCertificate]:
"""
Gets certificates from ACM. By default it returns all valid certificates
+ :param region: AWS region
:param valid_only: Return only valid certificates
:param domain_name: Return only certificates that match the domain
"""
# TODO implement pagination
- client = boto3.client('acm')
+ client = boto3.client('acm', self.region)
certificates = client.list_certificates()['CertificateSummaryList']
for summary in certificates:
arn = summary['CertificateArn']
- certificate = ACMCertificate.get_by_arn(arn)
+ certificate = ACMCertificate.get_by_arn(self.region, arn)
if valid_only and not certificate.is_valid():
pass
elif domain_name is not None and not certificate.matches(domain_name):
| zalando-stups/senza | 56b109cbf40fe05f508580ad2fce9d07e60075e6 | diff --git a/tests/test_manaus/test_acm.py b/tests/test_manaus/test_acm.py
index 51e12d4..f022ff2 100644
--- a/tests/test_manaus/test_acm.py
+++ b/tests/test_manaus/test_acm.py
@@ -148,7 +148,8 @@ def test_certificate_get_by_arn(monkeypatch):
m_client.describe_certificate.return_value = {'Certificate': CERT1}
monkeypatch.setattr('boto3.client', m_client)
- certificate1 = ACMCertificate.get_by_arn('arn:aws:acm:eu-west-1:cert')
+ certificate1 = ACMCertificate.get_by_arn('dummy-region',
+ 'arn:aws:acm:eu-west-1:cert')
assert certificate1.domain_name == '*.senza.example.com'
assert certificate1.is_valid(when=datetime(2016, 4, 5, 12, 14, 14,
tzinfo=timezone.utc))
@@ -183,7 +184,7 @@ def test_get_certificates(monkeypatch):
tzinfo=timezone.utc)
monkeypatch.setattr('senza.manaus.acm.datetime', m_datetime)
- acm = ACM()
+ acm = ACM('dummy-region')
certificates_default = list(acm.get_certificates())
assert len(certificates_default) == 1 # Cert2 is excluded because it's REVOKED
assert certificates_default[0].arn == 'arn:aws:acm:eu-west-1:cert1'
| NoRegionError: You must specify a region.
When trying to run `senza create` I am getting this error:
```
$ senza create --region eu-central-1 --force ../hello-flask/hello.yaml v56 ImageVersion=bus56 --stacktrace-visible
Generating Cloud Formation template.. EXCEPTION OCCURRED: You must specify a region.
Traceback (most recent call last):
File "/Users/rcaricio/.virtualenvs/lizzy-init/bin/senza", line 11, in <module>
sys.exit(main())
File "/Users/rcaricio/.virtualenvs/lizzy-init/lib/python3.5/site-packages/senza/cli.py", line 1492, in main
HandleExceptions(cli)()
File "/Users/rcaricio/.virtualenvs/lizzy-init/lib/python3.5/site-packages/senza/error_handling.py", line 99, in __call__
self.die_unknown_error(e)
File "/Users/rcaricio/.virtualenvs/lizzy-init/lib/python3.5/site-packages/senza/error_handling.py", line 57, in die_unknown_error
raise e
File "/Users/rcaricio/.virtualenvs/lizzy-init/lib/python3.5/site-packages/senza/error_handling.py", line 69, in __call__
self.function(*args, **kwargs)
File "/Users/rcaricio/.virtualenvs/lizzy-init/lib/python3.5/site-packages/click/core.py", line 716, in __call__
return self.main(*args, **kwargs)
File "/Users/rcaricio/.virtualenvs/lizzy-init/lib/python3.5/site-packages/click/core.py", line 696, in main
rv = self.invoke(ctx)
File "/Users/rcaricio/.virtualenvs/lizzy-init/lib/python3.5/site-packages/click/core.py", line 1060, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/Users/rcaricio/.virtualenvs/lizzy-init/lib/python3.5/site-packages/click/core.py", line 889, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/Users/rcaricio/.virtualenvs/lizzy-init/lib/python3.5/site-packages/click/core.py", line 534, in invoke
return callback(*args, **kwargs)
File "/Users/rcaricio/.virtualenvs/lizzy-init/lib/python3.5/site-packages/senza/cli.py", line 555, in create
data = create_cf_template(definition, region, version, parameter, force, parameter_file)
File "/Users/rcaricio/.virtualenvs/lizzy-init/lib/python3.5/site-packages/senza/cli.py", line 638, in create_cf_template
data = evaluate(definition.copy(), args, account_info, force)
File "/Users/rcaricio/.virtualenvs/lizzy-init/lib/python3.5/site-packages/senza/cli.py", line 239, in evaluate
definition = componentfn(definition, configuration, args, info, force, account_info)
File "/Users/rcaricio/.virtualenvs/lizzy-init/lib/python3.5/site-packages/senza/components/weighted_dns_elastic_load_balancer.py", line 29, in component_weighted_dns_elastic_load_balancer
return component_elastic_load_balancer(definition, configuration, args, info, force, account_info)
File "/Users/rcaricio/.virtualenvs/lizzy-init/lib/python3.5/site-packages/senza/components/elastic_load_balancer.py", line 110, in component_elastic_load_balancer
listeners = configuration.get('Listeners') or get_listeners(subdomain, main_zone, configuration)
File "/Users/rcaricio/.virtualenvs/lizzy-init/lib/python3.5/site-packages/senza/components/elastic_load_balancer.py", line 48, in get_listeners
reverse=True)
File "/Users/rcaricio/.virtualenvs/lizzy-init/lib/python3.5/site-packages/senza/manaus/acm.py", line 169, in get_certificates
client = boto3.client('acm')
File "/Users/rcaricio/.virtualenvs/lizzy-init/lib/python3.5/site-packages/boto3/__init__.py", line 79, in client
return _get_default_session().client(*args, **kwargs)
File "/Users/rcaricio/.virtualenvs/lizzy-init/lib/python3.5/site-packages/boto3/session.py", line 250, in client
aws_session_token=aws_session_token, config=config)
File "/Users/rcaricio/.virtualenvs/lizzy-init/lib/python3.5/site-packages/botocore/session.py", line 818, in create_client
client_config=config, api_version=api_version)
File "/Users/rcaricio/.virtualenvs/lizzy-init/lib/python3.5/site-packages/botocore/client.py", line 69, in create_client
verify, credentials, scoped_config, client_config, endpoint_bridge)
File "/Users/rcaricio/.virtualenvs/lizzy-init/lib/python3.5/site-packages/botocore/client.py", line 199, in _get_client_args
service_name, region_name, endpoint_url, is_secure)
File "/Users/rcaricio/.virtualenvs/lizzy-init/lib/python3.5/site-packages/botocore/client.py", line 322, in resolve
service_name, region_name)
File "/Users/rcaricio/.virtualenvs/lizzy-init/lib/python3.5/site-packages/botocore/regions.py", line 122, in construct_endpoint
partition, service_name, region_name)
File "/Users/rcaricio/.virtualenvs/lizzy-init/lib/python3.5/site-packages/botocore/regions.py", line 135, in _endpoint_for_partition
raise NoRegionError()
botocore.exceptions.NoRegionError: You must specify a region.
```
Senza version `1.0.91`
Does not happen with older versions of Senza though.
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_manaus/test_acm.py::test_certificate_get_by_arn",
"tests/test_manaus/test_acm.py::test_get_certificates"
] | [
"tests/test_manaus/test_acm.py::test_arn_is_acm_certificate",
"tests/test_manaus/test_acm.py::test_certificate_valid",
"tests/test_manaus/test_acm.py::test_certificate_comparison",
"tests/test_manaus/test_acm.py::test_certificate_matches"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2016-07-27T07:31:57Z" | apache-2.0 |
|
zalando-stups__senza-304 | diff --git a/senza/cli.py b/senza/cli.py
index f863831..fdb07f6 100755
--- a/senza/cli.py
+++ b/senza/cli.py
@@ -35,14 +35,16 @@ from .aws import (StackReference, get_account_alias, get_account_id,
from .components import evaluate_template, get_component
from .components.stups_auto_configuration import find_taupage_image
from .error_handling import HandleExceptions
-from .exceptions import VPCError
+from .manaus.ec2 import EC2
+from .manaus.exceptions import VPCError
from .manaus.route53 import Route53, Route53Record
from .patch import patch_auto_scaling_group
from .respawn import get_auto_scaling_group, respawn_auto_scaling_group
from .stups.piu import Piu
from .templates import get_template_description, get_templates
from .templates._helper import get_mint_bucket_name
-from .traffic import change_version_traffic, get_records, print_version_traffic, resolve_to_ip_addresses
+from .traffic import (change_version_traffic, get_records,
+ print_version_traffic, resolve_to_ip_addresses)
from .utils import (camel_case_to_underscore, ensure_keys, named_value,
pystache_render)
@@ -316,22 +318,21 @@ class AccountArguments:
@property
def VpcID(self):
if self.__VpcID is None:
- ec2 = boto3.resource('ec2', self.Region)
- vpc_list = list()
- for vpc in ec2.vpcs.all(): # don't use the list from blow. .all() use a internal pageing!
- if vpc.is_default:
- self.__VpcID = vpc.vpc_id
- break
- vpc_list.append(vpc)
- else:
- if len(vpc_list) == 1:
- # Use the only one VPC if no default VPC found
- self.__VpcID = vpc_list[0].vpc_id
- elif len(vpc_list) > 1:
- raise VPCError('Multiple VPCs are only supported if one '
- 'VPC is the default VPC (IsDefault=true)!')
- else:
- raise VPCError('Can\'t find any VPC!')
+ ec2 = EC2(self.Region)
+ try:
+ vpc = ec2.get_default_vpc()
+ except VPCError as error:
+ if sys.stdin.isatty() and error.number_of_vpcs:
+ # if running in interactive terminal and there are VPCs
+ # to choose from
+ vpcs = ec2.get_all_vpcs()
+ options = [(vpc.vpc_id, str(vpc)) for vpc in vpcs]
+ print("Can't find a default VPC")
+ vpc = choice("Select VPC to use",
+ options=options)
+ else: # if not running in interactive terminal (e.g Jenkins)
+ raise
+ self.__VpcID = vpc.vpc_id
return self.__VpcID
@property
diff --git a/senza/exceptions.py b/senza/exceptions.py
index 822221f..cdf4812 100644
--- a/senza/exceptions.py
+++ b/senza/exceptions.py
@@ -1,6 +1,6 @@
class SenzaException(Exception):
"""
- Base class for Senza execeptions
+ Base class for Senza exceptions
"""
@@ -11,15 +11,6 @@ class InvalidState(SenzaException):
"""
-class VPCError(SenzaException, AttributeError):
- """
- Error raised when there are issues with VPCs configuration
- """
-
- def __init__(self, message):
- super().__init__(message)
-
-
class PiuNotFound(SenzaException, FileNotFoundError):
"""
Error raised when piu executable is not found
diff --git a/senza/manaus/ec2.py b/senza/manaus/ec2.py
new file mode 100644
index 0000000..9ea2600
--- /dev/null
+++ b/senza/manaus/ec2.py
@@ -0,0 +1,84 @@
+from collections import OrderedDict
+from typing import Dict, List, Iterator
+
+import boto3
+
+from .exceptions import VPCError
+
+
+class EC2VPC:
+
+ """
+ See:
+ http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#vpc
+ """
+
+ def __init__(self,
+ vpc_id: str,
+ is_default: bool,
+ tags: List[Dict[str, str]]):
+ self.vpc_id = vpc_id
+ self.is_default = is_default
+ self.tags = OrderedDict([(t['Key'], t['Value']) for t in tags]) # type: Dict[str, str]
+
+ self.name = self.tags.get('Name', self.vpc_id)
+
+ def __str__(self):
+ return '{name} ({vpc_id})'.format_map(vars(self))
+
+ def __repr__(self):
+ return '<EC2VPC: {name} ({vpc_id})>'.format_map(vars(self))
+
+ @classmethod
+ def from_boto_vpc(cls, vpc) -> "EC2VPC":
+ """
+ Converts an ec2.VPC as returned by resource.vpcs.all()
+
+ See:
+ http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#vpc
+ """
+
+ return cls(vpc.vpc_id, vpc.is_default, vpc.tags)
+
+
+class EC2:
+
+ def __init__(self, region: str):
+ self.region = region
+
+ def get_all_vpcs(self) -> Iterator[EC2VPC]:
+ """
+ Get all VPCs from the account
+ """
+ resource = boto3.resource('ec2', self.region)
+
+ for vpc in resource.vpcs.all():
+ yield EC2VPC.from_boto_vpc(vpc)
+
+ def get_default_vpc(self) -> EC2VPC:
+ """
+ Get one VPC from the account, either the default or, if only one
+ exists, that one.
+ """
+ resource = boto3.resource('ec2', self.region)
+
+ number_of_vpcs = 0
+ # We shouldn't use the list with .all() because it has internal paging!
+ for vpc_number, vpc in enumerate(resource.vpcs.all(), start=1):
+ number_of_vpcs = vpc_number
+
+ if vpc.is_default:
+ return EC2VPC.from_boto_vpc(vpc)
+
+ if vpc_number == 1:
+ first_vpc = vpc
+
+ if number_of_vpcs == 0:
+ raise VPCError("Can't find any VPC!", number_of_vpcs)
+ elif number_of_vpcs == 1:
+ # Use the only one VPC if it's not the default VPC found
+ return EC2VPC.from_boto_vpc(first_vpc)
+ else:
+ raise VPCError("Multiple VPCs are only supported if one "
+ "VPC is the default VPC (IsDefault=true)!",
+ number_of_vpcs)
diff --git a/senza/manaus/exceptions.py b/senza/manaus/exceptions.py
index 08b63be..d07b441 100644
--- a/senza/manaus/exceptions.py
+++ b/senza/manaus/exceptions.py
@@ -1,6 +1,6 @@
class ManausException(Exception):
"""
- Base class for Manaus execeptions
+ Base class for Manaus exceptions
"""
@@ -36,3 +36,13 @@ class RecordNotFound(ManausException):
def __init__(self, name: str):
super().__init__('Route 53 Record not found: {}'.format(name))
+
+
+class VPCError(ManausException, AttributeError):
+ """
+ Error raised when there are issues with VPCs configuration
+ """
+
+ def __init__(self, message: str, number_of_vpcs: int=None):
+ super().__init__(message)
+ self.number_of_vpcs = number_of_vpcs
diff --git a/senza/manaus/route53.py b/senza/manaus/route53.py
index 0075eb0..6aab215 100644
--- a/senza/manaus/route53.py
+++ b/senza/manaus/route53.py
@@ -112,8 +112,9 @@ class Route53HostedZone:
'ResourceRecordSet': record.boto_dict}
change_batch['Changes'].append(change)
- client.change_resource_record_sets(HostedZoneId=self.id,
- ChangeBatch=change_batch)
+ if change_batch['Changes']:
+ client.change_resource_record_sets(HostedZoneId=self.id,
+ ChangeBatch=change_batch)
return change_batch
| zalando-stups/senza | 87feda79265966aa5d6a67f3a652e2f0d7961e64 | diff --git a/tests/test_manaus/test_ec2.py b/tests/test_manaus/test_ec2.py
new file mode 100644
index 0000000..36f1588
--- /dev/null
+++ b/tests/test_manaus/test_ec2.py
@@ -0,0 +1,95 @@
+from unittest.mock import MagicMock
+
+import pytest
+from senza.manaus.ec2 import EC2, EC2VPC
+from senza.manaus.exceptions import VPCError
+
+
+def test_from_boto_vpc():
+ mock_vpc = MagicMock()
+ mock_vpc.vpc_id = 'vpc-id'
+ mock_vpc.is_default = True
+ mock_vpc.tags = [{'Key': 'mykey', 'Value': 'myvalue'},
+ {'Key': 'theanswer', 'Value': '42'},
+ {'Key': 'Name', 'Value': 'my-vpc'}]
+ vpc = EC2VPC.from_boto_vpc(mock_vpc)
+
+ assert vpc.vpc_id == 'vpc-id'
+ assert vpc.is_default
+ assert vpc.tags['mykey'] == 'myvalue'
+ assert vpc.tags['theanswer'] == '42'
+ assert vpc.name == 'my-vpc'
+
+
+def test_get_default_vpc(monkeypatch):
+ mock_vpc1 = MagicMock()
+ mock_vpc1.vpc_id = 'vpc-id1'
+ mock_vpc1.is_default = True
+ mock_vpc1.tags = []
+
+ mock_vpc2 = MagicMock()
+ mock_vpc2.vpc_id = 'vpc-id2'
+ mock_vpc2.is_default = False
+ mock_vpc2.tags = []
+
+ mock_vpc3 = MagicMock()
+ mock_vpc3.vpc_id = 'vpc-id3'
+ mock_vpc3.is_default = False
+ mock_vpc3.tags = []
+
+ m_resource = MagicMock()
+ m_resource.return_value = m_resource
+ monkeypatch.setattr('boto3.resource', m_resource)
+
+ ec2 = EC2('eu-test-1')
+
+ # return default vpc
+ m_resource.vpcs.all.return_value = [mock_vpc1, mock_vpc2]
+ vpc1 = ec2.get_default_vpc()
+ assert vpc1.vpc_id == 'vpc-id1'
+
+ # ony one, non default
+ m_resource.vpcs.all.return_value = [mock_vpc2]
+ vpc2 = ec2.get_default_vpc()
+ assert vpc2.vpc_id == 'vpc-id2'
+
+ # no vpcs
+ m_resource.vpcs.all.return_value = []
+ with pytest.raises(VPCError) as exc_info:
+ ec2.get_default_vpc()
+ assert str(exc_info.value) == "Can't find any VPC!"
+
+ # no vpcs
+ m_resource.vpcs.all.return_value = [mock_vpc2, mock_vpc3]
+ with pytest.raises(VPCError) as exc_info:
+ ec2.get_default_vpc()
+
+ assert str(exc_info.value) == ("Multiple VPCs are only supported if one "
+ "VPC is the default VPC (IsDefault=true)!")
+
+
+def test_get_all_vpc(monkeypatch):
+ mock_vpc1 = MagicMock()
+ mock_vpc1.vpc_id = 'vpc-id1'
+ mock_vpc1.is_default = True
+ mock_vpc1.tags = []
+
+ mock_vpc2 = MagicMock()
+ mock_vpc2.vpc_id = 'vpc-id2'
+ mock_vpc2.is_default = False
+ mock_vpc2.tags = []
+
+ mock_vpc3 = MagicMock()
+ mock_vpc3.vpc_id = 'vpc-id3'
+ mock_vpc3.is_default = False
+ mock_vpc3.tags = []
+
+ m_resource = MagicMock()
+ m_resource.return_value = m_resource
+ monkeypatch.setattr('boto3.resource', m_resource)
+
+ ec2 = EC2('eu-test-1')
+
+ m_resource.vpcs.all.return_value = [mock_vpc1, mock_vpc2, mock_vpc3]
+ vpcs = list(ec2.get_all_vpcs())
+ assert len(vpcs) == 3
diff --git a/tests/test_manaus/test_route53.py b/tests/test_manaus/test_route53.py
index 2441ba1..24c5441 100644
--- a/tests/test_manaus/test_route53.py
+++ b/tests/test_manaus/test_route53.py
@@ -209,6 +209,12 @@ def test_hosted_zone_upsert(monkeypatch):
ChangeBatch={'Changes': expected_changes,
'Comment': 'test'})
+ m_client.change_resource_record_sets.reset_mock()
+ change_batch2 = hosted_zone.upsert([], comment="test")
+ assert change_batch2['Comment'] == "test"
+ assert change_batch2['Changes'] == []
+ m_client.change_resource_record_sets.assert_not_called()
+
def test_hosted_zone_create(monkeypatch):
m_client = MagicMock()
| Only call API for Route53 config if there is changes to be made
Only call AWS API when there is actual changes to be made.
Users reporting this exception:
```
raise ParamValidationError(report=report.generate_report())
botocore.exceptions.ParamValidationError: Parameter validation failed:
Invalid length for parameter ChangeBatch.Changes, value: 0, valid range: 1-inf
```
Error comes from https://github.com/zalando-stups/senza/blob/master/senza/manaus/route53.py#L114-L115 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_manaus/test_ec2.py::test_from_boto_vpc",
"tests/test_manaus/test_ec2.py::test_get_default_vpc",
"tests/test_manaus/test_ec2.py::test_get_all_vpc",
"tests/test_manaus/test_route53.py::test_hosted_zone_from_boto_dict",
"tests/test_manaus/test_route53.py::test_record_from_boto_dict",
"tests/test_manaus/test_route53.py::test_route53_hosted_zones",
"tests/test_manaus/test_route53.py::test_route53_hosted_zones_paginated",
"tests/test_manaus/test_route53.py::test_get_records",
"tests/test_manaus/test_route53.py::test_route53_record_boto_dict",
"tests/test_manaus/test_route53.py::test_hosted_zone_upsert",
"tests/test_manaus/test_route53.py::test_hosted_zone_create",
"tests/test_manaus/test_route53.py::test_hosted_zone_delete",
"tests/test_manaus/test_route53.py::test_to_alias",
"tests/test_manaus/test_route53.py::test_convert_domain_records_to_alias",
"tests/test_manaus/test_route53.py::test_hosted_zone_get_by_domain_name",
"tests/test_manaus/test_route53.py::test_hosted_zone_get_by_id",
"tests/test_manaus/test_route53.py::test_get_by_domain_name"
] | [] | {
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2016-08-09T13:36:53Z" | apache-2.0 |
|
zalando-stups__senza-349 | diff --git a/senza/manaus/ec2.py b/senza/manaus/ec2.py
index 9ea2600..6dee960 100644
--- a/senza/manaus/ec2.py
+++ b/senza/manaus/ec2.py
@@ -1,5 +1,5 @@
from collections import OrderedDict
-from typing import Dict, List, Iterator
+from typing import Dict, List, Iterator, Optional
import boto3
@@ -16,9 +16,10 @@ class EC2VPC:
def __init__(self,
vpc_id: str,
is_default: bool,
- tags: List[Dict[str, str]]):
+ tags: Optional[List[Dict[str, str]]]):
self.vpc_id = vpc_id
self.is_default = is_default
+ tags = tags or [] # type: List[Dict[str, str]]
self.tags = OrderedDict([(t['Key'], t['Value']) for t in tags]) # type: Dict[str, str]
self.name = self.tags.get('Name', self.vpc_id)
| zalando-stups/senza | e0331771ea0cc64d3ba5896f31d954f832a82ba9 | diff --git a/tests/test_manaus/test_ec2.py b/tests/test_manaus/test_ec2.py
index 36f1588..4dd7ae6 100644
--- a/tests/test_manaus/test_ec2.py
+++ b/tests/test_manaus/test_ec2.py
@@ -37,6 +37,11 @@ def test_get_default_vpc(monkeypatch):
mock_vpc3.is_default = False
mock_vpc3.tags = []
+ mock_vpc4 = MagicMock()
+ mock_vpc4.vpc_id = 'vpc-id4'
+ mock_vpc4.is_default = True
+ mock_vpc4.tags = None
+
m_resource = MagicMock()
m_resource.return_value = m_resource
monkeypatch.setattr('boto3.resource', m_resource)
@@ -59,11 +64,16 @@ def test_get_default_vpc(monkeypatch):
ec2.get_default_vpc()
assert str(exc_info.value) == "Can't find any VPC!"
- # no vpcs
+ # multiple vpcs
m_resource.vpcs.all.return_value = [mock_vpc2, mock_vpc3]
with pytest.raises(VPCError) as exc_info:
ec2.get_default_vpc()
+ # no tags in vpc return default vpc
+ m_resource.vpcs.all.return_value = [mock_vpc4, mock_vpc2]
+ vpc3 = ec2.get_default_vpc()
+ assert vpc3.vpc_id == 'vpc-id4'
+
assert str(exc_info.value) == ("Multiple VPCs are only supported if one "
"VPC is the default VPC (IsDefault=true)!")
| Better error message for "create" and VPC tags
When trying to create a stack with a VPC that has no tags the user gets the following message:
```
senza create deploy-definition.yaml 1 0.1
Generating Cloud Formation template.. EXCEPTION OCCURRED: 'NoneType' object is not iterable
Unknown Error: 'NoneType' object is not iterable.
Please create an issue with the content of /var/folders/yd/p61l98fn2g9fffwgjs819gr1sprr6d/T/senza-traceback-xgrqlxbj
```
In /var/folders/yd/p61l98fn2g9fffwgjs819gr1sprr6d/T/senza-traceback-xgrqlxbj:
```
Traceback (most recent call last):
File "/usr/local/lib/python3.5/site-packages/senza/error_handling.py", line 76, in __call__
self.function(*args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/click/core.py", line 716, in __call__
return self.main(*args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/click/core.py", line 696, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python3.5/site-packages/click/core.py", line 1060, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python3.5/site-packages/click/core.py", line 889, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python3.5/site-packages/click/core.py", line 534, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/senza/cli.py", line 663, in create
data = create_cf_template(definition, region, version, parameter, force, parameter_file)
File "/usr/local/lib/python3.5/site-packages/senza/cli.py", line 746, in create_cf_template
data = evaluate(definition.copy(), args, account_info, force)
File "/usr/local/lib/python3.5/site-packages/senza/cli.py", line 242, in evaluate
definition = componentfn(definition, configuration, args, info, force, account_info)
File "/usr/local/lib/python3.5/site-packages/senza/components/stups_auto_configuration.py", line 31, in component_stups_auto_configuration
vpc_id = configuration.get('VpcId', account_info.VpcID)
File "/usr/local/lib/python3.5/site-packages/senza/cli.py", line 329, in VpcID
vpc = ec2.get_default_vpc()
File "/usr/local/lib/python3.5/site-packages/senza/manaus/ec2.py", line 71, in get_default_vpc
return EC2VPC.from_boto_vpc(vpc)
File "/usr/local/lib/python3.5/site-packages/senza/manaus/ec2.py", line 41, in from_boto_vpc
return cls(vpc.vpc_id, vpc.is_default, vpc.tags)
File "/usr/local/lib/python3.5/site-packages/senza/manaus/ec2.py", line 22, in __init__
self.tags = OrderedDict([(t['Key'], t['Value']) for t in tags]) # type: Dict[str, str]
TypeError: 'NoneType' object is not iterable
```
The error message should be more descriptive. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_manaus/test_ec2.py::test_get_default_vpc"
] | [
"tests/test_manaus/test_ec2.py::test_from_boto_vpc",
"tests/test_manaus/test_ec2.py::test_get_all_vpc"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2016-09-12T07:22:12Z" | apache-2.0 |
|
zalando-stups__senza-365 | diff --git a/senza/manaus/cloudformation.py b/senza/manaus/cloudformation.py
index b8529be..a53b2e9 100644
--- a/senza/manaus/cloudformation.py
+++ b/senza/manaus/cloudformation.py
@@ -124,6 +124,11 @@ class CloudFormationStack:
for resource in resources:
resource_type = resource["ResourceType"]
if resource_type == ResourceType.route53_record_set:
+ physical_resource_id = resource.get('PhysicalResourceId')
+ if physical_resource_id is None:
+ # if there is no Physical Resource Id we can't fetch the
+ # record
+ continue
records = Route53.get_records(name=resource['PhysicalResourceId'])
for record in records:
if (record.set_identifier is None or
| zalando-stups/senza | fe537a4234d2dd978ef0ff04fba8e5507dad203d | diff --git a/tests/test_manaus/test_cloudformation.py b/tests/test_manaus/test_cloudformation.py
index f700c77..44b868a 100644
--- a/tests/test_manaus/test_cloudformation.py
+++ b/tests/test_manaus/test_cloudformation.py
@@ -99,6 +99,12 @@ def test_cf_resources(monkeypatch):
'PhysicalResourceId': 'myapp1.example.com',
'ResourceStatus': 'CREATE_COMPLETE',
'ResourceType': 'AWS::Route53::RecordSet'},
+ {'LastUpdatedTimestamp': datetime(2016, 7, 20, 7, 3,
+ 45, 70000,
+ tzinfo=timezone.utc),
+ 'LogicalResourceId': 'ThisWillBeIgnored',
+ 'ResourceStatus': 'CREATE_COMPLETE',
+ 'ResourceType': 'AWS::Route53::RecordSet'},
{'LastUpdatedTimestamp': datetime(2016, 7, 20, 7, 3,
43, 871000,
tzinfo=timezone.utc),
| Unknown Error: 'PhysicalResourceId'
I got a `senza delete` error:
Unknown Error: 'PhysicalResourceId'.
Please create an issue with the content of /tmp/senza-traceback-8ecz_cyz
****************************************senza-traceback-8ecz_cyz****************************************************
`Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/senza/error_handling.py", line 82, in __call__
self.function(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/click/core.py", line 716, in __call__
return self.main(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/click/core.py", line 696, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python3.5/dist-packages/click/core.py", line 1060, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python3.5/dist-packages/click/core.py", line 889, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python3.5/dist-packages/click/core.py", line 534, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/senza/cli.py", line 835, in delete
for r in stack.resources:
File "/usr/local/lib/python3.5/dist-packages/senza/manaus/cloudformation.py", line 127, in resources
records = Route53.get_records(name=resource['PhysicalResourceId'])
KeyError: 'PhysicalResourceId'` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_manaus/test_cloudformation.py::test_cf_resources"
] | [
"tests/test_manaus/test_cloudformation.py::test_get_by_stack_name",
"tests/test_manaus/test_cloudformation.py::test_get_stacks",
"tests/test_manaus/test_cloudformation.py::test_get_by_stack_name_not_found",
"tests/test_manaus/test_cloudformation.py::test_template",
"tests/test_manaus/test_cloudformation.py::test_stack_update"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2016-09-28T08:02:15Z" | apache-2.0 |
|
zalando-stups__senza-372 | diff --git a/senza/aws.py b/senza/aws.py
index 1284ba3..c7f0468 100644
--- a/senza/aws.py
+++ b/senza/aws.py
@@ -55,13 +55,12 @@ def is_status_complete(status: str):
def get_security_group(region: str, sg_name: str):
ec2 = boto3.resource('ec2', region)
try:
- sec_groups = list(ec2.security_groups.filter(
- Filters=[{'Name': 'group-name', 'Values': [sg_name]}]
- ))
- if not sec_groups:
- return None
- # FIXME: What if we have 2 VPC, with a SG with the same name?!
- return sec_groups[0]
+ # first try by tag name then by group-name (cannot be changed)
+ for _filter in [{'Name': 'tag:Name', 'Values': [sg_name]}, {'Name': 'group-name', 'Values': [sg_name]}]:
+ sec_groups = list(ec2.security_groups.filter(Filters=[_filter]))
+ if sec_groups:
+ # FIXME: What if we have 2 VPC, with a SG with the same name?!
+ return sec_groups[0]
except ClientError as e:
error_code = extract_client_error_code(e)
if error_code == 'InvalidGroup.NotFound':
| zalando-stups/senza | 56e263195218e3fe052e95221b2d9528c4343264 | diff --git a/tests/test_aws.py b/tests/test_aws.py
index 4ca762a..8dd5b44 100644
--- a/tests/test_aws.py
+++ b/tests/test_aws.py
@@ -14,6 +14,21 @@ def test_get_security_group(monkeypatch):
assert results == get_security_group('myregion', 'group_inexistant')
+def test_get_security_group_by_tag_name(monkeypatch):
+
+ def mock_filter(Filters):
+ if Filters[0]['Name'] == 'tag:Name' and Filters[0]['Values'] == ['my-sg']:
+ sg = MagicMock()
+ sg.id = 'sg-123'
+ return [sg]
+
+ ec2 = MagicMock()
+ ec2.security_groups.filter = mock_filter
+ monkeypatch.setattr('boto3.resource', MagicMock(return_value=ec2))
+
+ assert get_security_group('myregion', 'my-sg').id == 'sg-123'
+
+
def test_resolve_security_groups(monkeypatch):
ec2 = MagicMock()
ec2.security_groups.filter = MagicMock(side_effect=[
| Lookup SecurityGroups by the tag "Name" rather than GroupName
Both AWS API and CloudFormation allow to refer to a security group by its name if the operation runs in EC2 Classic or the default VPC. Unfortunately it uses the `GroupName` attribute that is automatically generated by AWS if the SG is a part of CloudFormation stack.
It would be a good idea to extend Senza to lookup SG during the CF template generation phase and to use the _tag_ `Name` instead. The tag can be set by another ("system") Senza stack definition, thus allowing the cross-stack references.
Another option would be to support the new cross-stack references that are recently introduced by Amazon: https://aws.amazon.com/blogs/aws/aws-cloudformation-update-yaml-cross-stack-references-simplified-substitution/ | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_aws.py::test_get_security_group_by_tag_name"
] | [
"tests/test_aws.py::test_get_security_group",
"tests/test_aws.py::test_resolve_security_groups",
"tests/test_aws.py::test_create",
"tests/test_aws.py::test_encrypt",
"tests/test_aws.py::test_list_kms_keys",
"tests/test_aws.py::test_get_vpc_attribute",
"tests/test_aws.py::test_get_account_id",
"tests/test_aws.py::test_get_account_alias",
"tests/test_aws.py::test_resolve_referenced_resource",
"tests/test_aws.py::test_resolve_referenced_resource_with_update_complete_status",
"tests/test_aws.py::test_resolve_referenced_output_when_stack_is_in_update_complete_status",
"tests/test_aws.py::test_parse_time",
"tests/test_aws.py::test_required_capabilities",
"tests/test_aws.py::test_resolve_topic_arn",
"tests/test_aws.py::test_matches_any",
"tests/test_aws.py::test_get_tag"
] | {
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
} | "2016-09-30T08:21:15Z" | apache-2.0 |
|
zalando-stups__senza-374 | diff --git a/senza/aws.py b/senza/aws.py
index 1284ba3..c7f0468 100644
--- a/senza/aws.py
+++ b/senza/aws.py
@@ -55,13 +55,12 @@ def is_status_complete(status: str):
def get_security_group(region: str, sg_name: str):
ec2 = boto3.resource('ec2', region)
try:
- sec_groups = list(ec2.security_groups.filter(
- Filters=[{'Name': 'group-name', 'Values': [sg_name]}]
- ))
- if not sec_groups:
- return None
- # FIXME: What if we have 2 VPC, with a SG with the same name?!
- return sec_groups[0]
+ # first try by tag name then by group-name (cannot be changed)
+ for _filter in [{'Name': 'tag:Name', 'Values': [sg_name]}, {'Name': 'group-name', 'Values': [sg_name]}]:
+ sec_groups = list(ec2.security_groups.filter(Filters=[_filter]))
+ if sec_groups:
+ # FIXME: What if we have 2 VPC, with a SG with the same name?!
+ return sec_groups[0]
except ClientError as e:
error_code = extract_client_error_code(e)
if error_code == 'InvalidGroup.NotFound':
diff --git a/senza/subcommands/root.py b/senza/subcommands/root.py
index 9162122..e5dab09 100644
--- a/senza/subcommands/root.py
+++ b/senza/subcommands/root.py
@@ -6,6 +6,7 @@ from typing import Optional
import click
import requests
import senza
+import sys
from clickclick import AliasedGroup, warning
from ..arguments import GLOBAL_OPTIONS, region_option
@@ -81,6 +82,8 @@ def check_senza_version(current_version: str):
Checks if senza is updated and prints a warning with instructions to update
if it's not.
"""
+ if not sys.stdout.isatty():
+ return
current_version = LooseVersion(current_version)
try:
latest_version = get_latest_version()
| zalando-stups/senza | 56e263195218e3fe052e95221b2d9528c4343264 | diff --git a/tests/test_aws.py b/tests/test_aws.py
index 4ca762a..8dd5b44 100644
--- a/tests/test_aws.py
+++ b/tests/test_aws.py
@@ -14,6 +14,21 @@ def test_get_security_group(monkeypatch):
assert results == get_security_group('myregion', 'group_inexistant')
+def test_get_security_group_by_tag_name(monkeypatch):
+
+ def mock_filter(Filters):
+ if Filters[0]['Name'] == 'tag:Name' and Filters[0]['Values'] == ['my-sg']:
+ sg = MagicMock()
+ sg.id = 'sg-123'
+ return [sg]
+
+ ec2 = MagicMock()
+ ec2.security_groups.filter = mock_filter
+ monkeypatch.setattr('boto3.resource', MagicMock(return_value=ec2))
+
+ assert get_security_group('myregion', 'my-sg').id == 'sg-123'
+
+
def test_resolve_security_groups(monkeypatch):
ec2 = MagicMock()
ec2.security_groups.filter = MagicMock(side_effect=[
diff --git a/tests/test_subcommands/test_root.py b/tests/test_subcommands/test_root.py
index 796d6c9..86f5a4f 100644
--- a/tests/test_subcommands/test_root.py
+++ b/tests/test_subcommands/test_root.py
@@ -34,8 +34,23 @@ def mock_warning(monkeypatch):
return mock
+@fixture()
+def mock_tty(monkeypatch):
+ # check_senza_version only prints if we have a TTY
+ monkeypatch.setattr('sys.stdout.isatty', lambda: True)
+
+
+def test_check_senza_version_notty(monkeypatch, mock_get_app_dir, mock_get, mock_warning):
+ with TemporaryDirectory() as temp_dir:
+ mock_get_app_dir.return_value = temp_dir
+ monkeypatch.setattr("senza.subcommands.root.__file__",
+ '/home/someuser/pymodules/root.py')
+ check_senza_version("0.40")
+ mock_warning.assert_not_called()
+
+
def test_check_senza_version(monkeypatch,
- mock_get_app_dir, mock_get, mock_warning):
+ mock_get_app_dir, mock_get, mock_warning, mock_tty):
with TemporaryDirectory() as temp_dir_1:
mock_get_app_dir.return_value = temp_dir_1
@@ -72,7 +87,7 @@ def test_check_senza_version(monkeypatch,
)
-def test_check_senza_version_timeout(mock_get_app_dir, mock_get, mock_warning):
+def test_check_senza_version_timeout(mock_get_app_dir, mock_get, mock_warning, mock_tty):
with TemporaryDirectory() as temp_dir:
mock_get_app_dir.return_value = temp_dir
mock_get.side_effect = Timeout
@@ -83,7 +98,8 @@ def test_check_senza_version_timeout(mock_get_app_dir, mock_get, mock_warning):
def test_check_senza_version_outdated_cache(monkeypatch, # noqa: F811
mock_get_app_dir,
mock_get,
- mock_warning):
+ mock_warning,
+ mock_tty):
monkeypatch.setattr("senza.subcommands.root.__file__",
'/usr/pymodules/root.py')
with TemporaryDirectory() as temp_dir:
@@ -106,7 +122,8 @@ def test_check_senza_version_outdated_cache(monkeypatch, # noqa: F811
def test_check_senza_version_exception(monkeypatch,
mock_get_app_dir,
mock_get,
- mock_warning):
+ mock_warning,
+ mock_tty):
mock_sentry = MagicMock()
monkeypatch.setattr("senza.subcommands.root.sentry", mock_sentry)
with TemporaryDirectory() as temp_dir:
| Senza version warning should not be printed for non-TTYs (piping result to awk etc)
The Senza version check currently destroys popular shell scripting such as:
```
senza li -o tsv | tail -n +2 | awk '{ print $1 }'
```
We should only print the warning if `sys.stdout` is a TTY. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_aws.py::test_get_security_group_by_tag_name",
"tests/test_subcommands/test_root.py::test_check_senza_version_notty"
] | [
"tests/test_aws.py::test_get_security_group",
"tests/test_aws.py::test_resolve_security_groups",
"tests/test_aws.py::test_create",
"tests/test_aws.py::test_encrypt",
"tests/test_aws.py::test_list_kms_keys",
"tests/test_aws.py::test_get_vpc_attribute",
"tests/test_aws.py::test_get_account_id",
"tests/test_aws.py::test_get_account_alias",
"tests/test_aws.py::test_resolve_referenced_resource",
"tests/test_aws.py::test_resolve_referenced_resource_with_update_complete_status",
"tests/test_aws.py::test_resolve_referenced_output_when_stack_is_in_update_complete_status",
"tests/test_aws.py::test_parse_time",
"tests/test_aws.py::test_required_capabilities",
"tests/test_aws.py::test_resolve_topic_arn",
"tests/test_aws.py::test_matches_any",
"tests/test_aws.py::test_get_tag",
"tests/test_subcommands/test_root.py::test_check_senza_version",
"tests/test_subcommands/test_root.py::test_check_senza_version_timeout",
"tests/test_subcommands/test_root.py::test_check_senza_version_outdated_cache",
"tests/test_subcommands/test_root.py::test_check_senza_version_exception",
"tests/test_subcommands/test_root.py::test_version"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2016-09-30T08:47:52Z" | apache-2.0 |
|
zalando-stups__senza-397 | diff --git a/senza/subcommands/root.py b/senza/subcommands/root.py
index a121009..e163658 100644
--- a/senza/subcommands/root.py
+++ b/senza/subcommands/root.py
@@ -99,9 +99,9 @@ def check_senza_version(current_version: str):
if latest_version is not None and current_version < latest_version:
if __file__.startswith('/home'):
# if it's installed in the user folder
- cmd = "pip install --upgrade stups-senza"
+ cmd = "pip3 install --upgrade stups-senza"
else:
- cmd = "sudo pip install --upgrade stups-senza"
+ cmd = "sudo pip3 install --upgrade stups-senza"
warning("Your senza version ({current}) is outdated. "
"Please install the new one using '{cmd}'".format(current=current_version,
cmd=cmd))
| zalando-stups/senza | 7d3726dec5badf48bab03bcee60eee43281b512c | diff --git a/tests/test_subcommands/test_root.py b/tests/test_subcommands/test_root.py
index 86f5a4f..c16be12 100644
--- a/tests/test_subcommands/test_root.py
+++ b/tests/test_subcommands/test_root.py
@@ -71,7 +71,7 @@ def test_check_senza_version(monkeypatch,
check_senza_version("0.40")
mock_warning.assert_called_once_with(
"Your senza version (0.40) is outdated. "
- "Please install the new one using 'pip install --upgrade stups-senza'"
+ "Please install the new one using 'pip3 install --upgrade stups-senza'"
)
with TemporaryDirectory() as temp_dir_4:
@@ -83,7 +83,7 @@ def test_check_senza_version(monkeypatch,
mock_warning.assert_called_once_with(
"Your senza version (0.40) is outdated. "
"Please install the new one using "
- "'sudo pip install --upgrade stups-senza'"
+ "'sudo pip3 install --upgrade stups-senza'"
)
@@ -115,7 +115,7 @@ def test_check_senza_version_outdated_cache(monkeypatch, # noqa: F811
mock_warning.assert_called_once_with(
"Your senza version (0.40) is outdated. "
"Please install the new one using "
- "'sudo pip install --upgrade stups-senza'"
+ "'sudo pip3 install --upgrade stups-senza'"
)
| Discrepancy between README and error messages
README.md states:
`sudo pip3 install --upgrade stups-senza`
But if you have an old version of senza installed, the reported message is:
`...Please install the new one using 'sudo pip install --upgrade stups-senza'`
Note that `pip3` is specified in README and `pip` is specified in the error message.
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_subcommands/test_root.py::test_check_senza_version",
"tests/test_subcommands/test_root.py::test_check_senza_version_outdated_cache"
] | [
"tests/test_subcommands/test_root.py::test_check_senza_version_notty",
"tests/test_subcommands/test_root.py::test_check_senza_version_timeout",
"tests/test_subcommands/test_root.py::test_check_senza_version_exception",
"tests/test_subcommands/test_root.py::test_version"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2016-10-14T14:42:48Z" | apache-2.0 |
|
zalando-stups__senza-414 | diff --git a/senza/components/coreos_auto_configuration.py b/senza/components/coreos_auto_configuration.py
new file mode 100644
index 0000000..707fdaf
--- /dev/null
+++ b/senza/components/coreos_auto_configuration.py
@@ -0,0 +1,23 @@
+import requests
+
+from senza.components.subnet_auto_configuration import component_subnet_auto_configuration
+from senza.utils import ensure_keys
+
+
+def find_coreos_image(release_channel: str, region: str):
+ '''Find the latest CoreOS AMI'''
+
+ response = requests.get('https://coreos.com/dist/aws/aws-{}.json'.format(release_channel), timeout=5)
+ response.raise_for_status()
+ data = response.json()
+ return data[region]['hvm']
+
+
+def component_coreos_auto_configuration(definition, configuration, args, info, force, account_info):
+ ami_id = find_coreos_image(configuration.get('ReleaseChannel') or 'stable', args.region)
+ configuration = ensure_keys(configuration, "Images", 'LatestCoreOSImage', args.region)
+ configuration["Images"]['LatestCoreOSImage'][args.region] = ami_id
+
+ component_subnet_auto_configuration(definition, configuration, args, info, force, account_info)
+
+ return definition
| zalando-stups/senza | 6cc75c6fdeb0ad9d9066e4658331ba9270a16f06 | diff --git a/tests/test_components.py b/tests/test_components.py
index e9a3f7c..d109065 100644
--- a/tests/test_components.py
+++ b/tests/test_components.py
@@ -11,6 +11,7 @@ from senza.components.auto_scaling_group import (component_auto_scaling_group,
normalize_asg_success,
normalize_network_threshold,
to_iso8601_duration)
+from senza.components.coreos_auto_configuration import component_coreos_auto_configuration
from senza.components.elastic_load_balancer import (component_elastic_load_balancer,
get_load_balancer_name)
from senza.components.elastic_load_balancer_v2 import component_elastic_load_balancer_v2
@@ -1094,3 +1095,29 @@ def test_component_subnet_auto_configuration(monkeypatch):
}
result = component_subnet_auto_configuration(definition, configuration, args, info, False, MagicMock())
assert ['subnet-1', 'subnet-2'] == result['Mappings']['ServerSubnets']['foo']['Subnets']
+
+
+def test_component_coreos_auto_configuration(monkeypatch):
+ configuration = {
+ 'ReleaseChannel': 'gamma'
+ }
+ info = {'StackName': 'foobar', 'StackVersion': '0.1'}
+ definition = {"Resources": {}}
+
+ args = MagicMock()
+ args.region = "foo"
+
+ subnet1 = MagicMock()
+ subnet1.id = 'subnet-1'
+
+ ec2 = MagicMock()
+ ec2.subnets.filter.return_value = [subnet1]
+
+ get = MagicMock()
+ get.return_value.json.return_value = {'foo': {'hvm': 'ami-007'}}
+
+ monkeypatch.setattr('boto3.resource', lambda *args: ec2)
+ monkeypatch.setattr('requests.get', get)
+ result = component_coreos_auto_configuration(definition, configuration, args, info, False, MagicMock())
+ assert 'ami-007' == result['Mappings']['Images']['foo']['LatestCoreOSImage']
+
| CoreOS Auto Configuration Component
We are currently testing [Kubernetes on AWS](https://github.com/zalando-incubator/kubernetes-on-aws) with CoreOS AMIs. We take the AMI ID from https://coreos.com/dist/aws/aws-stable.json and put it into the Senza definition YAML manually. It would be better to have a Senza component to automatically find and use the latest CoreOS AMI (similar to what the `StupsAutoConfiguration` component does for Taupage).
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_components.py::test_invalid_component",
"tests/test_components.py::test_component_iam_role",
"tests/test_components.py::test_get_merged_policies",
"tests/test_components.py::test_component_load_balancer_healthcheck",
"tests/test_components.py::test_component_load_balancer_idletimeout",
"tests/test_components.py::test_component_load_balancer_cert_arn",
"tests/test_components.py::test_component_load_balancer_http_only",
"tests/test_components.py::test_component_load_balancer_listeners_ssl",
"tests/test_components.py::test_component_load_balancer_namelength",
"tests/test_components.py::test_component_stups_auto_configuration",
"tests/test_components.py::test_component_stups_auto_configuration_vpc_id",
"tests/test_components.py::test_component_redis_node",
"tests/test_components.py::test_component_redis_cluster",
"tests/test_components.py::test_component_taupage_auto_scaling_group_user_data_without_ref",
"tests/test_components.py::test_component_taupage_auto_scaling_group_user_data_with_ref",
"tests/test_components.py::test_component_taupage_auto_scaling_group_user_data_with_lists_and_empty_dict",
"tests/test_components.py::test_component_auto_scaling_group_configurable_properties",
"tests/test_components.py::test_component_auto_scaling_group_custom_tags",
"tests/test_components.py::test_component_auto_scaling_group_configurable_properties2",
"tests/test_components.py::test_component_auto_scaling_group_metric_type",
"tests/test_components.py::test_component_auto_scaling_group_optional_metric_type",
"tests/test_components.py::test_to_iso8601_duration",
"tests/test_components.py::test_normalize_asg_success",
"tests/test_components.py::test_normalize_network_threshold",
"tests/test_components.py::test_check_application_id",
"tests/test_components.py::test_check_application_version",
"tests/test_components.py::test_get_load_balancer_name",
"tests/test_components.py::test_weighted_dns_load_balancer_v2",
"tests/test_components.py::test_max_description_length",
"tests/test_components.py::test_template_parameters",
"tests/test_components.py::test_component_load_balancer_default_internal_scheme",
"tests/test_components.py::test_component_load_balancer_v2_default_internal_scheme",
"tests/test_components.py::test_component_load_balancer_v2_target_group_vpc_id",
"tests/test_components.py::test_component_subnet_auto_configuration",
"tests/test_components.py::test_component_coreos_auto_configuration"
] | [] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_added_files"
],
"has_test_patch": true,
"is_lite": false
} | "2016-11-03T15:08:53Z" | apache-2.0 |
|
zalando-stups__senza-428 | diff --git a/senza/aws.py b/senza/aws.py
index 0f87a7e..e07f65d 100644
--- a/senza/aws.py
+++ b/senza/aws.py
@@ -9,6 +9,7 @@ import yaml
from botocore.exceptions import ClientError
from click import FileError
+from .exceptions import SecurityGroupNotFound
from .manaus.boto_proxy import BotoClientProxy
from .manaus.utils import extract_client_error_code
from .stack_references import check_file_exceptions
@@ -108,14 +109,14 @@ def resolve_security_group(security_group, region: str):
if isinstance(security_group, dict):
sg = resolve_referenced_resource(security_group, region)
if not sg:
- raise ValueError('Referenced Security Group "{}" does not exist'.format(security_group))
+ raise SecurityGroupNotFound(security_group)
return sg
elif security_group.startswith('sg-'):
return security_group
else:
sg = get_security_group(region, security_group)
if not sg:
- raise ValueError('Security Group "{}" does not exist'.format(security_group))
+ raise SecurityGroupNotFound(security_group)
return sg.id
diff --git a/senza/error_handling.py b/senza/error_handling.py
index e56378b..32ffb02 100644
--- a/senza/error_handling.py
+++ b/senza/error_handling.py
@@ -15,7 +15,7 @@ from clickclick import fatal_error
from raven import Client
from .configuration import configuration
-from .exceptions import InvalidDefinition, PiuNotFound
+from .exceptions import InvalidDefinition, PiuNotFound, SecurityGroupNotFound
from .manaus.exceptions import (ELBNotFound, HostedZoneNotFound, InvalidState,
RecordNotFound)
from .manaus.utils import extract_client_error_code
@@ -112,7 +112,7 @@ class HandleExceptions:
sys.stdout.flush()
if is_credentials_expired_error(client_error):
die_fatal_error('AWS credentials have expired.\n'
- 'Use the "mai" command line tool to get a new '
+ 'Use the "zaws" command line tool to get a new '
'temporary access key.')
elif is_access_denied_error(client_error):
die_fatal_error(
@@ -136,6 +136,10 @@ class HandleExceptions:
except (ELBNotFound, HostedZoneNotFound, RecordNotFound,
InvalidDefinition, InvalidState) as error:
die_fatal_error(error)
+ except SecurityGroupNotFound as error:
+ message = ("{}\nRun `senza init` to (re-)create "
+ "the security group.").format(error)
+ die_fatal_error(message)
except Exception as unknown_exception:
# Catch All
self.die_unknown_error(unknown_exception)
diff --git a/senza/exceptions.py b/senza/exceptions.py
index 5b57980..ff84c81 100644
--- a/senza/exceptions.py
+++ b/senza/exceptions.py
@@ -41,3 +41,15 @@ class InvalidDefinition(SenzaException):
def __str__(self):
return ("{path} is not a valid senza definition: "
"{reason}".format_map(vars(self)))
+
+
+class SecurityGroupNotFound(SenzaException):
+ """
+ Exception raised when a Security Group is not found
+ """
+
+ def __init__(self, security_group: str):
+ self.security_group = security_group
+
+ def __str__(self):
+ return 'Security Group "{}" does not exist.'.format(self.security_group)
| zalando-stups/senza | a72ed3ba8f330170d7dc9e923bd18294a03186af | diff --git a/tests/test_error_handling.py b/tests/test_error_handling.py
index 2df4395..c3c367f 100644
--- a/tests/test_error_handling.py
+++ b/tests/test_error_handling.py
@@ -7,7 +7,7 @@ import botocore.exceptions
import senza.error_handling
import yaml
from pytest import fixture, raises
-from senza.exceptions import PiuNotFound
+from senza.exceptions import PiuNotFound, SecurityGroupNotFound
from senza.manaus.exceptions import ELBNotFound, InvalidState
@@ -225,6 +225,18 @@ def test_yaml_error(capsys):
assert 'Please quote all variable values' in err
+def test_sg_not_found(capsys):
+ func = MagicMock(side_effect=SecurityGroupNotFound('my-app'))
+
+ with raises(SystemExit):
+ senza.error_handling.HandleExceptions(func)()
+
+ out, err = capsys.readouterr()
+
+ assert err == ('Security Group "my-app" does not exist.\n'
+ 'Run `senza init` to (re-)create the security group.\n')
+
+
def test_unknown_error(capsys, mock_tempfile, mock_raven):
senza.error_handling.sentry = senza.error_handling.setup_sentry(None)
func = MagicMock(side_effect=Exception("something"))
| Exception in senza create witout senza init
senza throws exception when security group is missing. It can check this condition and suggest using "senza init" to create the group.
```
EXCEPTION OCCURRED: Security Group "app-something" does not exist
Unknown Error: Security Group "app-something" does not exist.
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/senza/error_handling.py", line 104, in __call__
self.function(*args, **kwargs)
File "/home/someuser/.local/lib/python3.5/site-packages/click/core.py", line 716, in __call__
return self.main(*args, **kwargs)
File "/home/someuser/.local/lib/python3.5/site-packages/click/core.py", line 696, in main
rv = self.invoke(ctx)
File "/home/someuser/.local/lib/python3.5/site-packages/click/core.py", line 1060, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/home/someuser/.local/lib/python3.5/site-packages/click/core.py", line 889, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/home/someuser/.local/lib/python3.5/site-packages/click/core.py", line 534, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/senza/cli.py", line 576, in create
data = create_cf_template(definition, region, version, parameter, force, parameter_file)
File "/usr/local/lib/python3.5/dist-packages/senza/cli.py", line 659, in create_cf_template
data = evaluate(definition.copy(), args, account_info, force)
File "/usr/local/lib/python3.5/dist-packages/senza/cli.py", line 238, in evaluate
definition = componentfn(definition, configuration, args, info, force, account_info)
File "/usr/local/lib/python3.5/dist-packages/senza/components/taupage_auto_scaling_group.py", line 81, in component_taupage_auto_scaling_group
definition = component_auto_scaling_group(definition, configuration, args, info, force, account_info)
File "/usr/local/lib/python3.5/dist-packages/senza/components/auto_scaling_group.py", line 99, in component_auto_scaling_group
resolve_security_groups(configuration["SecurityGroups"], args.region)
File "/usr/local/lib/python3.5/dist-packages/senza/aws.py", line 126, in resolve_security_groups
result.append(resolve_security_group(security_group, region))
File "/usr/local/lib/python3.5/dist-packages/senza/aws.py", line 119, in resolve_security_group
raise ValueError('Security Group "{}" does not exist'.format(security_group))
ValueError: Security Group "app-something" does not exist
```
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_error_handling.py::test_store_exception",
"tests/test_error_handling.py::test_store_nested_exception",
"tests/test_error_handling.py::test_missing_credentials",
"tests/test_error_handling.py::test_access_denied",
"tests/test_error_handling.py::test_expired_credentials",
"tests/test_error_handling.py::test_unknown_ClientError_raven",
"tests/test_error_handling.py::test_unknown_ClientError_no_stack_trace",
"tests/test_error_handling.py::test_piu_not_found",
"tests/test_error_handling.py::test_elb_not_found",
"tests/test_error_handling.py::test_invalid_state",
"tests/test_error_handling.py::test_validation",
"tests/test_error_handling.py::test_sg_not_found",
"tests/test_error_handling.py::test_unknown_error",
"tests/test_error_handling.py::test_unknown_error_sentry"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2017-01-06T08:35:04Z" | apache-2.0 |
|
zalando-stups__senza-521 | diff --git a/requirements.txt b/requirements.txt
index 4b612cc..969c68d 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -7,6 +7,6 @@ dnspython>=1.15.0
stups-pierone>=1.0.34
boto3>=1.3.0
botocore>=1.4.10
-pytest>=2.7.3
+pytest>=3.6.3
raven
typing
diff --git a/setup.py b/setup.py
index b038fc5..4d36574 100755
--- a/setup.py
+++ b/setup.py
@@ -131,7 +131,7 @@ def setup_package():
install_requires=install_reqs,
setup_requires=['flake8'],
cmdclass=cmdclass,
- tests_require=['pytest-cov', 'pytest', 'mock', 'responses'],
+ tests_require=['pytest-cov', 'pytest>=3.6.3', 'mock', 'responses'],
command_options=command_options,
entry_points={'console_scripts': CONSOLE_SCRIPTS,
'senza.templates': ['bgapp = senza.templates.bgapp',
diff --git a/spotinst/components/elastigroup.py b/spotinst/components/elastigroup.py
index aa916e9..8280ed4 100644
--- a/spotinst/components/elastigroup.py
+++ b/spotinst/components/elastigroup.py
@@ -20,7 +20,12 @@ from spotinst import MissingSpotinstAccount
SPOTINST_LAMBDA_FORMATION_ARN = 'arn:aws:lambda:{}:178579023202:function:spotinst-cloudformation'
SPOTINST_API_URL = 'https://api.spotinst.io'
-ELASTIGROUP_DEFAULT_STRATEGY = {"risk": 100, "availabilityVsCost": "balanced", "utilizeReservedInstances": True}
+ELASTIGROUP_DEFAULT_STRATEGY = {
+ "risk": 100,
+ "availabilityVsCost": "balanced",
+ "utilizeReservedInstances": True,
+ "fallbackToOd": True,
+}
ELASTIGROUP_DEFAULT_PRODUCT = "Linux/UNIX"
@@ -33,7 +38,7 @@ def component_elastigroup(definition, configuration, args, info, force, account_
"""
definition = ensure_keys(ensure_keys(definition, "Resources"), "Mappings", "Senza", "Info")
if "SpotinstAccessToken" not in definition["Mappings"]["Senza"]["Info"]:
- raise click.UsageError("You have to specificy your SpotinstAccessToken attribute inside the SenzaInfo "
+ raise click.UsageError("You have to specify your SpotinstAccessToken attribute inside the SenzaInfo "
"to be able to use Elastigroups")
configuration = ensure_keys(configuration, "Elastigroup")
@@ -332,6 +337,7 @@ def extract_load_balancer_name(configuration, elastigroup_config: dict):
if "ElasticLoadBalancer" in configuration:
load_balancer_refs = configuration.pop("ElasticLoadBalancer")
+ health_check_type = "ELB"
if isinstance(load_balancer_refs, str):
load_balancers.append({
"name": {"Ref": load_balancer_refs},
@@ -344,6 +350,7 @@ def extract_load_balancer_name(configuration, elastigroup_config: dict):
"type": "CLASSIC"
})
if "ElasticLoadBalancerV2" in configuration:
+ health_check_type = "TARGET_GROUP"
load_balancer_refs = configuration.pop("ElasticLoadBalancerV2")
if isinstance(load_balancer_refs, str):
load_balancers.append({
@@ -358,16 +365,13 @@ def extract_load_balancer_name(configuration, elastigroup_config: dict):
})
if len(load_balancers) > 0:
- # use ELB health check by default when there are LBs
- health_check_type = "ELB"
launch_spec_config["loadBalancersConfig"] = {"loadBalancers": load_balancers}
- if "healthCheckType" in launch_spec_config:
- health_check_type = launch_spec_config["healthCheckType"]
- elif "HealthCheckType" in configuration:
- health_check_type = configuration["HealthCheckType"]
+ health_check_type = launch_spec_config.get("healthCheckType",
+ configuration.get("HealthCheckType", health_check_type))
+ grace_period = launch_spec_config.get("healthCheckGracePeriod",
+ configuration.get('HealthCheckGracePeriod', 300))
launch_spec_config["healthCheckType"] = health_check_type
- grace_period = launch_spec_config.get("healthCheckGracePeriod", configuration.get('HealthCheckGracePeriod', 300))
launch_spec_config["healthCheckGracePeriod"] = grace_period
@@ -432,20 +436,16 @@ def extract_instance_types(configuration, elastigroup_config):
are no SpotAlternatives the Elastigroup will have the same ondemand type as spot alternative
If there's already a compute.instanceTypes config it will be left untouched
"""
- elastigroup_config = ensure_keys(ensure_keys(elastigroup_config, "strategy"), "compute")
+ elastigroup_config = ensure_keys(elastigroup_config, "compute")
compute_config = elastigroup_config["compute"]
- instance_type = configuration.pop("InstanceType", None)
+
+ if "InstanceType" not in configuration:
+ raise click.UsageError("You need to specify the InstanceType attribute to be able to use Elastigroups")
+ instance_type = configuration.pop("InstanceType")
spot_alternatives = configuration.pop("SpotAlternatives", None)
if "instanceTypes" not in compute_config:
- if not (instance_type or spot_alternatives):
- raise click.UsageError("You have to specify one of InstanceType or SpotAlternatives")
instance_types = {}
- strategy = elastigroup_config["strategy"]
- if instance_type:
- instance_types.update({"ondemand": instance_type})
- strategy.update({"fallbackToOd": True})
- else:
- strategy.update({"fallbackToOd": False})
+ instance_types.update({"ondemand": instance_type})
if spot_alternatives:
instance_types.update({"spot": spot_alternatives})
else:
| zalando-stups/senza | d5477538a198df36914cdd2dbe9e10accb4dec5f | diff --git a/tests/test_elastigroup.py b/tests/test_elastigroup.py
index f77ccc1..022c0a8 100644
--- a/tests/test_elastigroup.py
+++ b/tests/test_elastigroup.py
@@ -442,7 +442,7 @@ def test_load_balancers():
"healthCheckGracePeriod": 300,
}}},
},
- { # 1 application load balancer from Taupage, healthcheck type set to ELB (default grace period)
+ { # 1 application load balancer from Taupage, healthcheck type set to TARGET_GROUP (default grace period)
"input": {"ElasticLoadBalancerV2": "bar"},
"given_config": {},
"expected_config": {"compute": {"launchSpecification": {
@@ -451,11 +451,12 @@ def test_load_balancers():
{"arn": {"Ref": "barTargetGroup"}, "type": "TARGET_GROUP"},
],
},
- "healthCheckType": "ELB",
+ "healthCheckType": "TARGET_GROUP",
"healthCheckGracePeriod": 300,
}}},
},
- { # multiple application load balancers from Taupage, healthcheck type set to ELB (default grace period)
+ { # multiple application load balancers from Taupage, healthcheck type set to TARGET_GROUP
+ # (default grace period)
"input": {"ElasticLoadBalancerV2": ["foo", "bar"]},
"given_config": {},
"expected_config": {"compute": {"launchSpecification": {
@@ -465,11 +466,11 @@ def test_load_balancers():
{"arn": {"Ref": "barTargetGroup"}, "type": "TARGET_GROUP"},
],
},
- "healthCheckType": "ELB",
+ "healthCheckType": "TARGET_GROUP",
"healthCheckGracePeriod": 300,
}}},
},
- { # mixed load balancers from Taupage, healthcheck type set to ELB and custom Taupage grace period
+ { # mixed load balancers from Taupage, healthcheck type set to TARGET_GROUP and custom Taupage grace period
"input": {
"ElasticLoadBalancer": "foo",
"ElasticLoadBalancerV2": "bar",
@@ -483,7 +484,7 @@ def test_load_balancers():
{"arn": {"Ref": "barTargetGroup"}, "type": "TARGET_GROUP"},
],
},
- "healthCheckType": "ELB",
+ "healthCheckType": "TARGET_GROUP",
"healthCheckGracePeriod": 42,
}}},
},
@@ -598,9 +599,11 @@ def test_extract_security_group_ids(monkeypatch):
assert test_case["expected_sgs"] == got["compute"]["launchSpecification"].get("securityGroupIds")
-def test_missing_instance_types():
+def test_missing_instance_type():
with pytest.raises(click.UsageError):
extract_instance_types({}, {})
+ with pytest.raises(click.UsageError):
+ extract_instance_types({"SpotAlternatives": ["foo", "bar", "baz"]}, {})
def test_extract_instance_types():
@@ -608,20 +611,12 @@ def test_extract_instance_types():
{ # minimum accepted behavior, on demand instance type from typical Senza
"input": {"InstanceType": "foo"},
"given_config": {},
- "expected_config": {"compute": {"instanceTypes": {"ondemand": "foo", "spot": ["foo"]}},
- "strategy": {"fallbackToOd": True}},
+ "expected_config": {"compute": {"instanceTypes": {"ondemand": "foo", "spot": ["foo"]}}},
},
{ # both on demand instance type from typical Senza and spot alternatives specified
"input": {"InstanceType": "foo", "SpotAlternatives": ["bar", "baz"]},
"given_config": {},
- "expected_config": {"compute": {"instanceTypes": {"ondemand": "foo", "spot": ["bar", "baz"]}},
- "strategy": {"fallbackToOd": True}},
- },
- { # only spot alternatives specified
- "input": {"SpotAlternatives": ["foo", "bar"]},
- "given_config": {},
- "expected_config": {"compute": {"instanceTypes": {"spot": ["foo", "bar"]}},
- "strategy": {"fallbackToOd": False}},
+ "expected_config": {"compute": {"instanceTypes": {"ondemand": "foo", "spot": ["bar", "baz"]}}},
},
]
for test_case in test_cases:
| Fix Elastigroup healthCheckType
The current implementation always set the Elastigroup's healthCheckType to "ELB" if there are any load balancers, regardless of their types.
The [API clearly states](https://api.spotinst.com/elastigroup/amazon-web-services-2/create/#compute.launchSpecification.healthCheckType) that ELB is for classic ELBs and TARGET_GROUP should be used for ALBs. See [Spotinst's recommendation](https://github.com/zalando-stups/senza/pull/516#pullrequestreview-136726224). | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_elastigroup.py::test_extract_instance_types",
"tests/test_elastigroup.py::test_load_balancers",
"tests/test_elastigroup.py::test_missing_instance_type"
] | [
"tests/test_elastigroup.py::test_extract_subnets",
"tests/test_elastigroup.py::test_detailed_monitoring",
"tests/test_elastigroup.py::test_missing_access_token",
"tests/test_elastigroup.py::test_public_ips",
"tests/test_elastigroup.py::test_extract_instance_profile",
"tests/test_elastigroup.py::test_standard_tags",
"tests/test_elastigroup.py::test_component_elastigroup_defaults",
"tests/test_elastigroup.py::test_auto_scaling_rules",
"tests/test_elastigroup.py::test_product",
"tests/test_elastigroup.py::test_block_mappings",
"tests/test_elastigroup.py::test_extract_security_group_ids",
"tests/test_elastigroup.py::test_spotinst_account_resolution_failure",
"tests/test_elastigroup.py::test_prediction_strategy",
"tests/test_elastigroup.py::test_autoscaling_capacity",
"tests/test_elastigroup.py::test_extract_image_id",
"tests/test_elastigroup.py::test_spotinst_account_resolution"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2018-07-14T17:31:04Z" | apache-2.0 |
|
zalando-stups__senza-522 | diff --git a/spotinst/components/elastigroup.py b/spotinst/components/elastigroup.py
index aa916e9..dca20f4 100644
--- a/spotinst/components/elastigroup.py
+++ b/spotinst/components/elastigroup.py
@@ -20,7 +20,12 @@ from spotinst import MissingSpotinstAccount
SPOTINST_LAMBDA_FORMATION_ARN = 'arn:aws:lambda:{}:178579023202:function:spotinst-cloudformation'
SPOTINST_API_URL = 'https://api.spotinst.io'
-ELASTIGROUP_DEFAULT_STRATEGY = {"risk": 100, "availabilityVsCost": "balanced", "utilizeReservedInstances": True}
+ELASTIGROUP_DEFAULT_STRATEGY = {
+ "risk": 100,
+ "availabilityVsCost": "balanced",
+ "utilizeReservedInstances": True,
+ "fallbackToOd": True,
+}
ELASTIGROUP_DEFAULT_PRODUCT = "Linux/UNIX"
@@ -432,20 +437,16 @@ def extract_instance_types(configuration, elastigroup_config):
are no SpotAlternatives the Elastigroup will have the same ondemand type as spot alternative
If there's already a compute.instanceTypes config it will be left untouched
"""
- elastigroup_config = ensure_keys(ensure_keys(elastigroup_config, "strategy"), "compute")
+ elastigroup_config = ensure_keys(elastigroup_config, "compute")
compute_config = elastigroup_config["compute"]
- instance_type = configuration.pop("InstanceType", None)
+
+ if "InstanceType" not in configuration:
+ raise click.UsageError("You need to specify the InstanceType attribute to be able to use Elastigroups")
+ instance_type = configuration.pop("InstanceType")
spot_alternatives = configuration.pop("SpotAlternatives", None)
if "instanceTypes" not in compute_config:
- if not (instance_type or spot_alternatives):
- raise click.UsageError("You have to specify one of InstanceType or SpotAlternatives")
instance_types = {}
- strategy = elastigroup_config["strategy"]
- if instance_type:
- instance_types.update({"ondemand": instance_type})
- strategy.update({"fallbackToOd": True})
- else:
- strategy.update({"fallbackToOd": False})
+ instance_types.update({"ondemand": instance_type})
if spot_alternatives:
instance_types.update({"spot": spot_alternatives})
else:
| zalando-stups/senza | d5477538a198df36914cdd2dbe9e10accb4dec5f | diff --git a/tests/test_elastigroup.py b/tests/test_elastigroup.py
index f77ccc1..0fcb9e4 100644
--- a/tests/test_elastigroup.py
+++ b/tests/test_elastigroup.py
@@ -598,9 +598,11 @@ def test_extract_security_group_ids(monkeypatch):
assert test_case["expected_sgs"] == got["compute"]["launchSpecification"].get("securityGroupIds")
-def test_missing_instance_types():
+def test_missing_instance_type():
with pytest.raises(click.UsageError):
extract_instance_types({}, {})
+ with pytest.raises(click.UsageError):
+ extract_instance_types({"SpotAlternatives": ["foo", "bar", "baz"]}, {})
def test_extract_instance_types():
@@ -608,20 +610,12 @@ def test_extract_instance_types():
{ # minimum accepted behavior, on demand instance type from typical Senza
"input": {"InstanceType": "foo"},
"given_config": {},
- "expected_config": {"compute": {"instanceTypes": {"ondemand": "foo", "spot": ["foo"]}},
- "strategy": {"fallbackToOd": True}},
+ "expected_config": {"compute": {"instanceTypes": {"ondemand": "foo", "spot": ["foo"]}}},
},
{ # both on demand instance type from typical Senza and spot alternatives specified
"input": {"InstanceType": "foo", "SpotAlternatives": ["bar", "baz"]},
"given_config": {},
- "expected_config": {"compute": {"instanceTypes": {"ondemand": "foo", "spot": ["bar", "baz"]}},
- "strategy": {"fallbackToOd": True}},
- },
- { # only spot alternatives specified
- "input": {"SpotAlternatives": ["foo", "bar"]},
- "given_config": {},
- "expected_config": {"compute": {"instanceTypes": {"spot": ["foo", "bar"]}},
- "strategy": {"fallbackToOd": False}},
+ "expected_config": {"compute": {"instanceTypes": {"ondemand": "foo", "spot": ["bar", "baz"]}}},
},
]
for test_case in test_cases:
| Make Elastigroup's On Demand not optional
The current implementation allows users not to specify the `InstanceType` attribute which would later be translated to the Elastigroups `ondemand` attribute. [This attribute is mandatory according to the API](https://api.spotinst.com/elastigroup/amazon-web-services-2/create/#compute.instanceTypes.ondemand) and [Spotint's recommendations](https://github.com/zalando-stups/senza/pull/516#pullrequestreview-136726224). The stack would not be created.
The fallbackToOd should always be set to True given that `ondemand` is mandatory. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_elastigroup.py::test_extract_instance_types",
"tests/test_elastigroup.py::test_missing_instance_type"
] | [
"tests/test_elastigroup.py::test_autoscaling_capacity",
"tests/test_elastigroup.py::test_block_mappings",
"tests/test_elastigroup.py::test_standard_tags",
"tests/test_elastigroup.py::test_auto_scaling_rules",
"tests/test_elastigroup.py::test_detailed_monitoring",
"tests/test_elastigroup.py::test_extract_instance_profile",
"tests/test_elastigroup.py::test_load_balancers",
"tests/test_elastigroup.py::test_product",
"tests/test_elastigroup.py::test_extract_subnets",
"tests/test_elastigroup.py::test_public_ips",
"tests/test_elastigroup.py::test_component_elastigroup_defaults",
"tests/test_elastigroup.py::test_spotinst_account_resolution",
"tests/test_elastigroup.py::test_missing_access_token",
"tests/test_elastigroup.py::test_extract_image_id",
"tests/test_elastigroup.py::test_spotinst_account_resolution_failure",
"tests/test_elastigroup.py::test_extract_security_group_ids",
"tests/test_elastigroup.py::test_prediction_strategy"
] | {
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
} | "2018-07-14T18:04:16Z" | apache-2.0 |
|
zalando-stups__senza-535 | diff --git a/senza/components/elastigroup.py b/senza/components/elastigroup.py
index 7d39d6b..301359a 100644
--- a/senza/components/elastigroup.py
+++ b/senza/components/elastigroup.py
@@ -64,7 +64,7 @@ def component_elastigroup(definition, configuration, args, info, force, account_
extract_instance_profile(args, definition, configuration, elastigroup_config)
# cfn definition
access_token = _extract_spotinst_access_token(definition)
- config_name = configuration["Name"] + "Config"
+ config_name = configuration["Name"]
definition["Resources"][config_name] = {
"Type": "Custom::elastigroup",
"Properties": {
| zalando-stups/senza | 935f4111323f6b98ff136ae44a0d57825ac763c7 | diff --git a/tests/test_elastigroup.py b/tests/test_elastigroup.py
index 339bf4e..b98621e 100644
--- a/tests/test_elastigroup.py
+++ b/tests/test_elastigroup.py
@@ -44,7 +44,7 @@ def test_component_elastigroup_defaults(monkeypatch):
result = component_elastigroup(definition, configuration, args, info, False, mock_account_info)
- properties = result["Resources"]["eg1Config"]["Properties"]
+ properties = result["Resources"]["eg1"]["Properties"]
assert properties["accountId"] == 'act-12345abcdef'
assert properties["group"]["capacity"] == {"target": 1, "minimum": 1, "maximum": 1}
instance_types = properties["group"]["compute"]["instanceTypes"]
| Spotinst elastigroup adds "Config" to resource name
This invalidates many existing Senza templates. It should keep the original name | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_elastigroup.py::test_component_elastigroup_defaults"
] | [
"tests/test_elastigroup.py::test_block_mappings",
"tests/test_elastigroup.py::test_extract_instance_profile",
"tests/test_elastigroup.py::test_spotinst_account_resolution",
"tests/test_elastigroup.py::test_extract_security_group_ids",
"tests/test_elastigroup.py::test_load_balancers",
"tests/test_elastigroup.py::test_autoscaling_capacity",
"tests/test_elastigroup.py::test_extract_subnets",
"tests/test_elastigroup.py::test_spotinst_account_resolution_failure",
"tests/test_elastigroup.py::test_public_ips",
"tests/test_elastigroup.py::test_auto_scaling_rules",
"tests/test_elastigroup.py::test_prediction_strategy",
"tests/test_elastigroup.py::test_extract_instance_types",
"tests/test_elastigroup.py::test_standard_tags",
"tests/test_elastigroup.py::test_detailed_monitoring",
"tests/test_elastigroup.py::test_extract_image_id",
"tests/test_elastigroup.py::test_missing_access_token",
"tests/test_elastigroup.py::test_product",
"tests/test_elastigroup.py::test_missing_instance_type"
] | {
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
} | "2018-09-04T14:15:05Z" | apache-2.0 |
|
zalando-stups__senza-565 | diff --git a/senza/components/elastigroup.py b/senza/components/elastigroup.py
index 42e9e6d..391ee91 100644
--- a/senza/components/elastigroup.py
+++ b/senza/components/elastigroup.py
@@ -138,7 +138,7 @@ def component_elastigroup(definition, configuration, args, info, force, account_
extract_user_data(configuration, elastigroup_config, info, force, account_info)
extract_load_balancer_name(configuration, elastigroup_config)
extract_public_ips(configuration, elastigroup_config)
- extract_image_id(elastigroup_config)
+ extract_image_id(configuration, elastigroup_config)
extract_security_group_ids(configuration, elastigroup_config, args)
extract_instance_types(configuration, elastigroup_config)
extract_autoscaling_capacity(configuration, elastigroup_config)
@@ -497,7 +497,7 @@ def extract_public_ips(configuration, elastigroup_config):
]
-def extract_image_id(elastigroup_config: dict):
+def extract_image_id(configuration, elastigroup_config: dict):
"""
This function identifies whether a senza formatted AMI mapping is configured,
if so it transforms it into a Spotinst Elastigroup AMI API configuration
@@ -506,7 +506,8 @@ def extract_image_id(elastigroup_config: dict):
launch_spec_config = elastigroup_config["compute"]["launchSpecification"]
if "imageId" not in launch_spec_config.keys():
- launch_spec_config["imageId"] = {"Fn::FindInMap": ["Images", {"Ref": "AWS::Region"}, "LatestTaupageImage"]}
+ image_key = configuration.get("Image", "LatestTaupageImage")
+ launch_spec_config["imageId"] = {"Fn::FindInMap": ["Images", {"Ref": "AWS::Region"}, image_key]}
def extract_security_group_ids(configuration, elastigroup_config: dict, args):
| zalando-stups/senza | 235c2a4b25bdd9dffdc36e0a2bbe16704788a407 | diff --git a/tests/test_elastigroup.py b/tests/test_elastigroup.py
index 78725db..7213a8b 100644
--- a/tests/test_elastigroup.py
+++ b/tests/test_elastigroup.py
@@ -62,7 +62,8 @@ def test_component_elastigroup_defaults(monkeypatch):
assert {'tagKey': 'StackName', 'tagValue': 'foobar'} in tags
assert {'tagKey': 'StackVersion', 'tagValue': '0.1'} in tags
assert properties["group"]["compute"]["product"] == ELASTIGROUP_DEFAULT_PRODUCT
- assert properties["group"]["compute"]["subnetIds"] == {"Fn::FindInMap": ["ServerSubnets", {"Ref": "AWS::Region"}, "Subnets"]}
+ assert properties["group"]["compute"]["subnetIds"] == {
+ "Fn::FindInMap": ["ServerSubnets", {"Ref": "AWS::Region"}, "Subnets"]}
assert properties["group"]["region"] == "reg1"
assert properties["group"]["strategy"] == ELASTIGROUP_DEFAULT_STRATEGY
@@ -666,19 +667,28 @@ def test_public_ips():
def test_extract_image_id():
test_cases = [
{ # default behavior - set latest taupage image
+ "input": {},
"given_config": {},
"expected_config": {"compute": {"launchSpecification": {
"imageId": {"Fn::FindInMap": ["Images", {"Ref": "AWS::Region"}, "LatestTaupageImage"]}
}}},
},
{ # leave imageId untouched
+ "input": {},
"given_config": {"compute": {"launchSpecification": {"imageId": "fake-id"}}},
"expected_config": {"compute": {"launchSpecification": {"imageId": "fake-id"}}},
},
+ { # use specified image from the Senza mapping
+ "input": {"Image": "Foo"},
+ "given_config": {},
+ "expected_config": {"compute": {"launchSpecification": {
+ "imageId": {"Fn::FindInMap": ["Images", {"Ref": "AWS::Region"}, "Foo"]}
+ }}},
+ }
]
for test_case in test_cases:
got = test_case["given_config"]
- extract_image_id(got)
+ extract_image_id(test_case["input"], got)
assert test_case["expected_config"] == got
| Allow Elastigroup component to use custom Taupage AMI
Currently, Elastigroup components [always use the latest production Taupage AMI](https://github.com/zalando-stups/senza/blob/235c2a4b25bdd9dffdc36e0a2bbe16704788a407/senza/components/elastigroup.py#L509).
When the attribute `Image` is specified that setting should be honored, allowing users to easily specify one of the other [existing options](https://stups.readthedocs.io/en/latest/components/senza.html#senza-stupsautoconfiguration) - `LatestTaupageStagingImage` or `LatestTaupageDevImage`
The current workaround is to customize use the `Elastigroup` attribute:
```yaml
Elastigroup:
compute:
launchSpecification:
imageId: <ami-id>
```
Which requires users to know in advance the AMI ID and hardcode it. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_elastigroup.py::test_extract_image_id"
] | [
"tests/test_elastigroup.py::test_product",
"tests/test_elastigroup.py::test_load_balancers",
"tests/test_elastigroup.py::test_extract_security_group_ids",
"tests/test_elastigroup.py::test_spotinst_account_resolution",
"tests/test_elastigroup.py::test_extract_instance_profile",
"tests/test_elastigroup.py::test_patch_cross_stack_policy_errors",
"tests/test_elastigroup.py::test_component_elastigroup_defaults",
"tests/test_elastigroup.py::test_prediction_strategy",
"tests/test_elastigroup.py::test_autoscaling_capacity",
"tests/test_elastigroup.py::test_spotinst_account_resolution_failure",
"tests/test_elastigroup.py::test_extract_instance_types",
"tests/test_elastigroup.py::test_extract_subnets",
"tests/test_elastigroup.py::test_missing_instance_type",
"tests/test_elastigroup.py::test_detailed_monitoring",
"tests/test_elastigroup.py::test_patch_cross_stack_policy",
"tests/test_elastigroup.py::test_auto_scaling_rules",
"tests/test_elastigroup.py::test_block_mappings",
"tests/test_elastigroup.py::test_missing_access_token",
"tests/test_elastigroup.py::test_public_ips",
"tests/test_elastigroup.py::test_multiple_target_groups",
"tests/test_elastigroup.py::test_raw_user_data_and_base64_encoding_cf_function_used",
"tests/test_elastigroup.py::test_standard_tags"
] | {
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
} | "2019-05-22T15:10:01Z" | apache-2.0 |
|
zalando-stups__zign-14 | diff --git a/zign/api.py b/zign/api.py
index d98ed9a..065afae 100644
--- a/zign/api.py
+++ b/zign/api.py
@@ -100,6 +100,11 @@ def get_named_token(scope, realm, name, user, password, url=None,
if existing_token:
return existing_token
+ if name and not realm:
+ access_token = get_service_token(name, scope)
+ if access_token:
+ return {'access_token': access_token}
+
config = get_config()
url = url or config.get('url')
@@ -153,6 +158,21 @@ def is_user_scope(scope: str):
return scope in set(['uid', 'cn'])
+def get_service_token(name: str, scopes: list):
+ '''Get service token (tokens lib) if possible, otherwise return None'''
+ tokens.manage(name, scopes)
+ try:
+ access_token = tokens.get(name)
+ except tokens.ConfigurationError:
+ # will be thrown if configuration is missing (e.g. OAUTH2_ACCESS_TOKEN_URL)
+ access_token = None
+ except tokens.InvalidCredentialsError:
+ # will be thrown if $CREDENTIALS_DIR/*.json cannot be read
+ access_token = None
+
+ return access_token
+
+
def get_token(name: str, scopes: list):
'''Get an OAuth token, either from Token Service
or directly from OAuth provider (using the Python tokens library)'''
@@ -163,14 +183,7 @@ def get_token(name: str, scopes: list):
if token:
return token['access_token']
- tokens.manage(name, scopes)
- try:
- access_token = tokens.get(name)
- except tokens.ConfigurationError:
- access_token = None
- except tokens.InvalidCredentialsError:
- access_token = None
-
+ access_token = get_service_token(name, scopes)
if access_token:
return access_token
| zalando-stups/zign | 46f296b8952b518c9f93d398ef890d5d4001a37a | diff --git a/tests/test_api.py b/tests/test_api.py
index ad3cc20..e6e2f6c 100644
--- a/tests/test_api.py
+++ b/tests/test_api.py
@@ -1,4 +1,5 @@
import pytest
+import time
import tokens
import zign.api
@@ -72,3 +73,18 @@ def test_get_token_fallback_success(monkeypatch):
monkeypatch.setattr('zign.api.get_new_token', lambda *args, **kwargs: {'access_token': 'tt77'})
assert zign.api.get_token('mytok', ['myscope']) == 'tt77'
+
+
+def test_get_named_token_existing(monkeypatch):
+ existing = {'mytok': {'access_token': 'tt77', 'creation_time': time.time() - 10, 'expires_in': 3600}}
+ monkeypatch.setattr('zign.api.get_tokens', lambda: existing)
+ tok = zign.api.get_named_token(scope=['myscope'], realm=None, name='mytok', user='myusr', password='mypw')
+ assert tok['access_token'] == 'tt77'
+
+
+def test_get_named_token_services(monkeypatch):
+ response = MagicMock(status_code=401)
+ monkeypatch.setattr('requests.get', MagicMock(return_value=response))
+ monkeypatch.setattr('tokens.get', lambda x: 'svcmytok123')
+ tok = zign.api.get_named_token(scope=['myscope'], realm=None, name='mytok', user='myusr', password='mypw')
+ assert tok['access_token'] == 'svcmytok123'
| Transparently get service tokens via "tokens" library if possible
We already have the `zign.api.get_token` function and we should consider getting service tokens transparently also when using `zign token` directly. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_api.py::test_get_named_token_services"
] | [
"tests/test_api.py::test_get_new_token_invalid_json",
"tests/test_api.py::test_get_new_token_missing_access_token",
"tests/test_api.py::test_get_token_existing",
"tests/test_api.py::test_get_token_configuration_error",
"tests/test_api.py::test_get_token_service_success",
"tests/test_api.py::test_get_token_fallback_success",
"tests/test_api.py::test_get_named_token_existing"
] | {
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
} | "2016-04-19T17:40:40Z" | apache-2.0 |
|
zalando-stups__zign-47 | diff --git a/zign/cli.py b/zign/cli.py
index 2fabfb2..b6cd3e0 100644
--- a/zign/cli.py
+++ b/zign/cli.py
@@ -87,7 +87,8 @@ def token(name, authorize_url, client_id, business_partner_id, refresh):
'''Create a new Platform IAM token or use an existing one.'''
try:
- token = get_token_implicit_flow(name, authorize_url, client_id, business_partner_id, refresh)
+ token = get_token_implicit_flow(name, authorize_url=authorize_url, client_id=client_id,
+ business_partner_id=business_partner_id, refresh=refresh)
except AuthenticationFailed as e:
raise click.UsageError(e)
access_token = token.get('access_token')
| zalando-stups/zign | fec2ac288a3d4ba1d5082e8daa2feea0e1eb9ec1 | diff --git a/tests/test_cli.py b/tests/test_cli.py
new file mode 100644
index 0000000..8b23802
--- /dev/null
+++ b/tests/test_cli.py
@@ -0,0 +1,19 @@
+from click.testing import CliRunner
+from unittest.mock import MagicMock
+from zign.cli import cli
+
+
+def test_token(monkeypatch):
+ token = 'abc-123'
+
+ get_token_implicit_flow = MagicMock()
+ get_token_implicit_flow.return_value = {'access_token': token, 'expires_in': 1, 'token_type': 'test'}
+ monkeypatch.setattr('zign.cli.get_token_implicit_flow', get_token_implicit_flow)
+
+ runner = CliRunner()
+
+ with runner.isolated_filesystem():
+ result = runner.invoke(cli, ['token', '-n', 'mytok', '--refresh'], catch_exceptions=False)
+
+ assert token == result.output.rstrip().split('\n')[-1]
+ get_token_implicit_flow.assert_called_with('mytok', authorize_url=None, business_partner_id=None, client_id=None, refresh=True)
| --refresh doesn't do anything useful
The `--refresh` flag doesn't do anything for named tokens.
```
$ ztoken token --refresh -n postman | md5sum
34e6b2a7a14439271f077690eba31fa3 -
$ ztoken token --refresh -n postman | md5sum
34e6b2a7a14439271f077690eba31fa3 -
```
I expected this to request a new token using the existing refresh token.
Interestingly it also does weird things when requesting an unnamed token (`ztoken token --refresh`). Then a browser window is always opened and after successful authentication you get
```
{
"error": "invalid_client",
"error_description": "invalid client"
}
```
The reason for that seems to be wrong creation of the URL. It points to `.../oauth2/authorize?business_partner_id=True&client_id=ztoken&redirect_uri=http://localhost:8081&response_type=token` (True as business_partner_id).
---
There is also the general weirdness of different behavior of when new tokens are created. Creating an unnamed token just records the refresh token but not the token and no lifetime. This way every run of `ztoken` has to create a new token and so `--refresh` would be pointless there. Creating a named token records the lifetime and seems to return the same token every time as long as it is valid. Even if the `--refresh` thing were fixed, this dichotomy would not go away. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_cli.py::test_token"
] | [] | {
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
} | "2017-03-09T08:16:54Z" | apache-2.0 |
|
zamzterz__Flask-pyoidc-28 | diff --git a/src/flask_pyoidc/flask_pyoidc.py b/src/flask_pyoidc/flask_pyoidc.py
index 89d05d9..e03b18d 100644
--- a/src/flask_pyoidc/flask_pyoidc.py
+++ b/src/flask_pyoidc/flask_pyoidc.py
@@ -74,11 +74,10 @@ class OIDCAuthentication(object):
OIDC identity provider.
"""
- def __init__(self, flask_app, client_registration_info=None,
+ def __init__(self, app=None, client_registration_info=None,
issuer=None, provider_configuration_info=None,
userinfo_endpoint_method='POST',
extra_request_args=None):
- self.app = flask_app
self.userinfo_endpoint_method = userinfo_endpoint_method
self.extra_request_args = extra_request_args or {}
@@ -102,21 +101,23 @@ class OIDCAuthentication(object):
self.client_registration_info = client_registration_info or {}
+ self.logout_view = None
+ self._error_view = None
+ if app:
+ self.init_app(app)
+
+ def init_app(self, app):
# setup redirect_uri as a flask route
- self.app.add_url_rule('/redirect_uri', 'redirect_uri', self._handle_authentication_response)
+ app.add_url_rule('/redirect_uri', 'redirect_uri', self._handle_authentication_response)
# dynamically add the Flask redirect uri to the client info
- with self.app.app_context():
- self.client_registration_info['redirect_uris'] \
- = url_for('redirect_uri')
+ with app.app_context():
+ self.client_registration_info['redirect_uris'] = url_for('redirect_uri')
# if non-discovery client add the provided info from the constructor
- if client_registration_info and 'client_id' in client_registration_info:
+ if 'client_id' in self.client_registration_info:
# static client info provided
- self.client.store_registration_info(RegistrationRequest(**client_registration_info))
-
- self.logout_view = None
- self._error_view = None
+ self.client.store_registration_info(RegistrationRequest(**self.client_registration_info))
def _authenticate(self, interactive=True):
if 'client_id' not in self.client_registration_info:
@@ -124,7 +125,7 @@ class OIDCAuthentication(object):
# do dynamic registration
if self.logout_view:
# handle support for logout
- with self.app.app_context():
+ with current_app.app_context():
post_logout_redirect_uri = url_for(self.logout_view.__name__, _external=True)
logger.debug('built post_logout_redirect_uri=%s', post_logout_redirect_uri)
self.client_registration_info['post_logout_redirect_uris'] = [post_logout_redirect_uri]
| zamzterz/Flask-pyoidc | e4e2d4ffa36b0689b5d1c42cb612e1bdfb4cc638 | diff --git a/tests/test_flask_pyoidc.py b/tests/test_flask_pyoidc.py
index b7ce050..80161c8 100644
--- a/tests/test_flask_pyoidc.py
+++ b/tests/test_flask_pyoidc.py
@@ -50,14 +50,19 @@ class TestOIDCAuthentication(object):
self.app = Flask(__name__)
self.app.config.update({'SERVER_NAME': 'localhost', 'SECRET_KEY': 'test_key'})
+ def get_instance(self, kwargs):
+ authn = OIDCAuthentication(**kwargs)
+ authn.init_app(self.app)
+ return authn
+
@responses.activate
def test_store_internal_redirect_uri_on_static_client_reg(self):
responses.add(responses.GET, ISSUER + '/.well-known/openid-configuration',
body=json.dumps(dict(issuer=ISSUER, token_endpoint=ISSUER + '/token')),
content_type='application/json')
- authn = OIDCAuthentication(self.app, issuer=ISSUER,
- client_registration_info=dict(client_id='abc', client_secret='foo'))
+ authn = self.get_instance(dict(issuer=ISSUER,
+ client_registration_info=dict(client_id='abc', client_secret='foo')))
assert len(authn.client.registration_response['redirect_uris']) == 1
assert authn.client.registration_response['redirect_uris'][0] == 'http://localhost/redirect_uri'
@@ -69,9 +74,9 @@ class TestOIDCAuthentication(object):
state = 'state'
nonce = 'nonce'
sub = 'foobar'
- authn = OIDCAuthentication(self.app, provider_configuration_info={'issuer': ISSUER, 'token_endpoint': '/token'},
- client_registration_info={'client_id': 'foo'},
- userinfo_endpoint_method=method)
+ authn = self.get_instance(dict(provider_configuration_info={'issuer': ISSUER, 'token_endpoint': '/token'},
+ client_registration_info={'client_id': 'foo'},
+ userinfo_endpoint_method=method))
authn.client.do_access_token_request = MagicMock(
return_value=AccessTokenResponse(**{'id_token': IdToken(**{'sub': sub, 'nonce': nonce}),
'access_token': 'access_token'})
@@ -87,9 +92,9 @@ class TestOIDCAuthentication(object):
def test_no_userinfo_request_is_done_if_no_userinfo_endpoint_method_is_specified(self):
state = 'state'
- authn = OIDCAuthentication(self.app, provider_configuration_info={'issuer': ISSUER},
- client_registration_info={'client_id': 'foo'},
- userinfo_endpoint_method=None)
+ authn = self.get_instance(dict(provider_configuration_info={'issuer': ISSUER},
+ client_registration_info={'client_id': 'foo'},
+ userinfo_endpoint_method=None))
userinfo_request_mock = MagicMock()
authn.client.do_user_info_request = userinfo_request_mock
authn._do_userinfo_request(state, None)
@@ -97,9 +102,9 @@ class TestOIDCAuthentication(object):
def test_authenticatate_with_extra_request_parameters(self):
extra_params = {"foo": "bar", "abc": "xyz"}
- authn = OIDCAuthentication(self.app, provider_configuration_info={'issuer': ISSUER},
- client_registration_info={'client_id': 'foo'},
- extra_request_args=extra_params)
+ authn = self.get_instance(dict(provider_configuration_info={'issuer': ISSUER},
+ client_registration_info={'client_id': 'foo'},
+ extra_request_args=extra_params))
with self.app.test_request_context('/'):
a = authn._authenticate()
@@ -107,8 +112,8 @@ class TestOIDCAuthentication(object):
assert set(extra_params.items()).issubset(set(request_params.items()))
def test_reauthenticate_if_no_session(self):
- authn = OIDCAuthentication(self.app, provider_configuration_info={'issuer': ISSUER},
- client_registration_info={'client_id': 'foo'})
+ authn = self.get_instance(dict(provider_configuration_info={'issuer': ISSUER},
+ client_registration_info={'client_id': 'foo'}))
client_mock = MagicMock()
callback_mock = MagicMock()
callback_mock.__name__ = 'test_callback' # required for Python 2
@@ -119,8 +124,9 @@ class TestOIDCAuthentication(object):
assert not callback_mock.called
def test_reauthenticate_silent_if_refresh_expired(self):
- authn = OIDCAuthentication(self.app, provider_configuration_info={'issuer': ISSUER},
- client_registration_info={'client_id': 'foo', 'session_refresh_interval_seconds': 1})
+ authn = self.get_instance(dict(provider_configuration_info={'issuer': ISSUER},
+ client_registration_info={'client_id': 'foo',
+ 'session_refresh_interval_seconds': 1}))
client_mock = MagicMock()
callback_mock = MagicMock()
callback_mock.__name__ = 'test_callback' # required for Python 2
@@ -133,9 +139,9 @@ class TestOIDCAuthentication(object):
assert not callback_mock.called
def test_dont_reauthenticate_silent_if_authentication_not_expired(self):
- authn = OIDCAuthentication(self.app, provider_configuration_info={'issuer': ISSUER},
- client_registration_info={'client_id': 'foo',
- 'session_refresh_interval_seconds': 999})
+ authn = self.get_instance(dict(provider_configuration_info={'issuer': ISSUER},
+ client_registration_info={'client_id': 'foo',
+ 'session_refresh_interval_seconds': 999}))
client_mock = MagicMock()
callback_mock = MagicMock()
callback_mock.__name__ = 'test_callback' # required for Python 2
@@ -164,11 +170,11 @@ class TestOIDCAuthentication(object):
responses.add(responses.POST, userinfo_endpoint,
body=json.dumps(userinfo_response),
content_type='application/json')
- authn = OIDCAuthentication(self.app,
- provider_configuration_info={'issuer': ISSUER,
- 'token_endpoint': token_endpoint,
- 'userinfo_endpoint': userinfo_endpoint},
- client_registration_info={'client_id': 'foo', 'client_secret': 'foo'})
+ authn = self.get_instance(dict(
+ provider_configuration_info={'issuer': ISSUER,
+ 'token_endpoint': token_endpoint,
+ 'userinfo_endpoint': userinfo_endpoint},
+ client_registration_info={'client_id': 'foo', 'client_secret': 'foo'}))
self.app.config.update({'SESSION_PERMANENT': True})
with self.app.test_request_context('/redirect_uri?state=test&code=test'):
@@ -182,11 +188,11 @@ class TestOIDCAuthentication(object):
def test_logout(self):
end_session_endpoint = 'https://provider.example.com/end_session'
post_logout_uri = 'https://client.example.com/post_logout'
- authn = OIDCAuthentication(self.app,
- provider_configuration_info={'issuer': ISSUER,
- 'end_session_endpoint': end_session_endpoint},
- client_registration_info={'client_id': 'foo',
- 'post_logout_redirect_uris': [post_logout_uri]})
+ authn = self.get_instance(dict(
+ provider_configuration_info={'issuer': ISSUER,
+ 'end_session_endpoint': end_session_endpoint},
+ client_registration_info={'client_id': 'foo',
+ 'post_logout_redirect_uris': [post_logout_uri]}))
id_token = IdToken(**{'sub': 'sub1', 'nonce': 'nonce'})
with self.app.test_request_context('/logout'):
flask.session['access_token'] = 'abcde'
@@ -206,10 +212,10 @@ class TestOIDCAuthentication(object):
def test_logout_handles_provider_without_end_session_endpoint(self):
post_logout_uri = 'https://client.example.com/post_logout'
- authn = OIDCAuthentication(self.app,
- provider_configuration_info={'issuer': ISSUER},
- client_registration_info={'client_id': 'foo',
- 'post_logout_redirect_uris': [post_logout_uri]})
+ authn = self.get_instance(dict(
+ provider_configuration_info={'issuer': ISSUER},
+ client_registration_info={'client_id': 'foo',
+ 'post_logout_redirect_uris': [post_logout_uri]}))
id_token = IdToken(**{'sub': 'sub1', 'nonce': 'nonce'})
with self.app.test_request_context('/logout'):
flask.session['access_token'] = 'abcde'
@@ -224,11 +230,11 @@ class TestOIDCAuthentication(object):
def test_oidc_logout_redirects_to_provider(self):
end_session_endpoint = 'https://provider.example.com/end_session'
post_logout_uri = 'https://client.example.com/post_logout'
- authn = OIDCAuthentication(self.app,
- provider_configuration_info={'issuer': ISSUER,
- 'end_session_endpoint': end_session_endpoint},
- client_registration_info={'client_id': 'foo',
- 'post_logout_redirect_uris': [post_logout_uri]})
+ authn = self.get_instance(dict(
+ provider_configuration_info={'issuer': ISSUER,
+ 'end_session_endpoint': end_session_endpoint},
+ client_registration_info={'client_id': 'foo',
+ 'post_logout_redirect_uris': [post_logout_uri]}))
callback_mock = MagicMock()
callback_mock.__name__ = 'test_callback' # required for Python 2
id_token = IdToken(**{'sub': 'sub1', 'nonce': 'nonce'})
@@ -241,11 +247,11 @@ class TestOIDCAuthentication(object):
def test_oidc_logout_handles_redirects_from_provider(self):
end_session_endpoint = 'https://provider.example.com/end_session'
post_logout_uri = 'https://client.example.com/post_logout'
- authn = OIDCAuthentication(self.app,
- provider_configuration_info={'issuer': ISSUER,
- 'end_session_endpoint': end_session_endpoint},
- client_registration_info={'client_id': 'foo',
- 'post_logout_redirect_uris': [post_logout_uri]})
+ authn = self.get_instance(dict(
+ provider_configuration_info={'issuer': ISSUER,
+ 'end_session_endpoint': end_session_endpoint},
+ client_registration_info={'client_id': 'foo',
+ 'post_logout_redirect_uris': [post_logout_uri]}))
callback_mock = MagicMock()
callback_mock.__name__ = 'test_callback' # required for Python 2
state = 'end_session_123'
@@ -258,8 +264,8 @@ class TestOIDCAuthentication(object):
def test_authentication_error_reponse_calls_to_error_view_if_set(self):
state = 'test_tate'
error_response = {'error': 'invalid_request', 'error_description': 'test error'}
- authn = OIDCAuthentication(self.app, provider_configuration_info={'issuer': ISSUER},
- client_registration_info=dict(client_id='abc', client_secret='foo'))
+ authn = self.get_instance(dict(provider_configuration_info={'issuer': ISSUER},
+ client_registration_info=dict(client_id='abc', client_secret='foo')))
error_view_mock = MagicMock()
authn._error_view = error_view_mock
with self.app.test_request_context('/redirect_uri?{error}&state={state}'.format(
@@ -271,8 +277,8 @@ class TestOIDCAuthentication(object):
def test_authentication_error_reponse_returns_default_error_if_no_error_view_set(self):
state = 'test_tate'
error_response = {'error': 'invalid_request', 'error_description': 'test error'}
- authn = OIDCAuthentication(self.app, provider_configuration_info={'issuer': ISSUER},
- client_registration_info=dict(client_id='abc', client_secret='foo'))
+ authn = self.get_instance(dict(provider_configuration_info={'issuer': ISSUER},
+ client_registration_info=dict(client_id='abc', client_secret='foo')))
with self.app.test_request_context('/redirect_uri?{error}&state={state}'.format(
error=urlencode(error_response), state=state)):
flask.session['state'] = state
@@ -287,9 +293,9 @@ class TestOIDCAuthentication(object):
body=json.dumps(error_response),
content_type='application/json')
- authn = OIDCAuthentication(self.app,
- provider_configuration_info={'issuer': ISSUER, 'token_endpoint': token_endpoint},
- client_registration_info=dict(client_id='abc', client_secret='foo'))
+ authn = self.get_instance(dict(
+ provider_configuration_info={'issuer': ISSUER, 'token_endpoint': token_endpoint},
+ client_registration_info=dict(client_id='abc', client_secret='foo')))
error_view_mock = MagicMock()
authn._error_view = error_view_mock
state = 'test_tate'
@@ -306,9 +312,9 @@ class TestOIDCAuthentication(object):
body=json.dumps(error_response),
content_type='application/json')
- authn = OIDCAuthentication(self.app, provider_configuration_info={'issuer': ISSUER,
- 'token_endpoint': token_endpoint},
- client_registration_info=dict(client_id='abc', client_secret='foo'))
+ authn = self.get_instance(dict(provider_configuration_info={'issuer': ISSUER,
+ 'token_endpoint': token_endpoint},
+ client_registration_info=dict(client_id='abc', client_secret='foo')))
state = 'test_tate'
with self.app.test_request_context('/redirect_uri?code=foo&state=' + state):
flask.session['state'] = state
| Add init_app feature
It's customary for extensions to allow initialization of an app _after_ construction: For example, if an `app.config` contains the appropriate client information, this would be a desierable API:
```python3
from flask_pyoidc import OIDCAuthentication
auth = OIDCAuthentication()
def create_app():
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
auth.init_app(app)
# alternatively
# auth.init_app(app, client_info=app.config["CLIENT_INFO"])
return app
```
As it stands, this requires the `app` to be global -- a huge testability no-no. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_dont_reauthenticate_silent_if_authentication_not_expired",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_configurable_userinfo_endpoint_method_is_used[POST]",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_oidc_logout_redirects_to_provider",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_logout",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_authenticatate_with_extra_request_parameters",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_oidc_logout_handles_redirects_from_provider",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_reauthenticate_silent_if_refresh_expired",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_token_error_reponse_calls_to_error_view_if_set",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_session_expiration_set_to_id_token_exp",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_token_error_reponse_returns_default_error_if_no_error_view_set",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_no_userinfo_request_is_done_if_no_userinfo_endpoint_method_is_specified",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_logout_handles_provider_without_end_session_endpoint",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_authentication_error_reponse_returns_default_error_if_no_error_view_set",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_reauthenticate_if_no_session",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_store_internal_redirect_uri_on_static_client_reg",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_configurable_userinfo_endpoint_method_is_used[GET]",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_authentication_error_reponse_calls_to_error_view_if_set"
] | [
"tests/test_flask_pyoidc.py::Test_Session::test_unauthenticated_session",
"tests/test_flask_pyoidc.py::Test_Session::test_should_not_refresh_if_not_supported",
"tests/test_flask_pyoidc.py::Test_Session::test_should_not_refresh_if_authenticated_within_refresh_interval",
"tests/test_flask_pyoidc.py::Test_Session::test_authenticated_session",
"tests/test_flask_pyoidc.py::Test_Session::test_should_refresh_if_supported_and_necessary"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2018-08-21T18:07:58Z" | apache-2.0 |
|
zamzterz__Flask-pyoidc-57 | diff --git a/README.md b/README.md
index adb7848..39601ae 100644
--- a/README.md
+++ b/README.md
@@ -66,6 +66,8 @@ config = ProviderConfiguration([provider configuration], client_metadata=client_
**Note: The redirect URIs registered with the provider MUST include `<application_url>/redirect_uri`,
where `<application_url>` is the URL of the Flask application.**
+To configure this extension to use a different endpoint, set the
+[`OIDC_REDIRECT_ENDPOINT` configuration parameter](#flask-configuration).
#### Dynamic client registration
@@ -91,6 +93,8 @@ You may also configure the way the user sessions created by this extension are h
* `OIDC_SESSION_PERMANENT`: If set to `True` (which is the default) the user session will be kept until the configured
session lifetime (see below). If set to `False` the session will be deleted when the user closes the browser.
+* `OIDC_REDIRECT_ENDPOINT`: Set the endpoint used as redirect_uri to receive authentication responses. Defaults to
+ `redirect_uri`, meaning the URL `<application_url>/redirect_uri` needs to be registered with the provider(s).
* `PERMANENT_SESSION_LIFETIME`: Control how long a user session is valid, see
[Flask documentation](http://flask.pocoo.org/docs/1.0/config/#PERMANENT_SESSION_LIFETIME) for more information.
diff --git a/src/flask_pyoidc/flask_pyoidc.py b/src/flask_pyoidc/flask_pyoidc.py
index 79816d2..132ddc6 100644
--- a/src/flask_pyoidc/flask_pyoidc.py
+++ b/src/flask_pyoidc/flask_pyoidc.py
@@ -36,13 +36,12 @@ try:
except ImportError:
from urlparse import parse_qsl
+
class OIDCAuthentication(object):
"""
OIDCAuthentication object for Flask extension.
"""
- REDIRECT_URI_ENDPOINT = 'redirect_uri'
-
def __init__(self, provider_configurations, app=None):
"""
Args:
@@ -55,21 +54,24 @@ class OIDCAuthentication(object):
self.clients = None
self._logout_view = None
self._error_view = None
+ self._redirect_uri_endpoint = None
if app:
self.init_app(app)
def init_app(self, app):
+ self._redirect_uri_endpoint = app.config.get('OIDC_REDIRECT_ENDPOINT', 'redirect_uri').lstrip('/')
+
# setup redirect_uri as a flask route
- app.add_url_rule('/redirect_uri',
- self.REDIRECT_URI_ENDPOINT,
+ app.add_url_rule('/' + self._redirect_uri_endpoint,
+ self._redirect_uri_endpoint,
self._handle_authentication_response,
methods=['GET', 'POST'])
# dynamically add the Flask redirect uri to the client info
with app.app_context():
self.clients = {
- name: PyoidcFacade(configuration, url_for(self.REDIRECT_URI_ENDPOINT))
+ name: PyoidcFacade(configuration, url_for(self._redirect_uri_endpoint))
for (name, configuration) in self._provider_configurations.items()
}
@@ -161,7 +163,7 @@ class OIDCAuthentication(object):
# if the current request was from the JS page handling fragment encoded responses we need to return
# a URL for the error page to redirect to
flask.session['error'] = error_response
- return '/redirect_uri?error=1'
+ return '/' + self._redirect_uri_endpoint + '?error=1'
return self._show_error_response(error_response)
def _show_error_response(self, error_response):
| zamzterz/Flask-pyoidc | c1494d755af1d427bc214446699eb97f951eb09d | diff --git a/tests/test_flask_pyoidc.py b/tests/test_flask_pyoidc.py
index 78cde1a..a2eca3a 100644
--- a/tests/test_flask_pyoidc.py
+++ b/tests/test_flask_pyoidc.py
@@ -468,3 +468,9 @@ class TestOIDCAuthentication(object):
with pytest.raises(ValueError) as exc_info:
self.init_app().oidc_auth('unknown')
assert 'unknown' in str(exc_info.value)
+
+ def test_should_use_custom_redirect_endpoint(self):
+ self.app.config['OIDC_REDIRECT_ENDPOINT'] = '/openid_connect_login'
+ authn = self.init_app()
+ assert authn._redirect_uri_endpoint == 'openid_connect_login'
+ assert authn.clients['test_provider']._redirect_uri == 'http://client.example.com/openid_connect_login'
| Do not hardcode routes like `/redirect_uri`
Better provide a default which people can then override. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_should_use_custom_redirect_endpoint"
] | [
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_logout_handles_redirect_back_from_provider",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_using_unknown_provider_name_should_raise_exception",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_logout_redirects_to_provider_if_end_session_endpoint_is_configured",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_authentication_error_response_returns_default_error_if_no_error_view_set",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_handle_authentication_response_POST",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_token_error_response_returns_default_error_if_no_error_view_set",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_reauthenticate_silent_if_session_expired",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_token_error_response_calls_to_error_view_if_set",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_handle_authentication_response_fragment_encoded",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_handle_authentication_response_error_message",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_authentication_error_response_calls_to_error_view_if_set",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_logout_handles_redirect_back_from_provider_with_incorrect_state",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_logout_handles_provider_without_end_session_endpoint",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_should_not_authenticate_if_session_exists",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_dont_reauthenticate_silent_if_session_not_expired",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_handle_authentication_response_error_message_without_stored_error",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_expected_auth_response_mode_is_set[id_token",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_handle_implicit_authentication_response",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_should_register_client_if_not_registered_before",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_handle_authentication_response",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_should_authenticate_if_no_session",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_expected_auth_response_mode_is_set[code-False]"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2019-07-27T23:55:39Z" | apache-2.0 |
|
zamzterz__Flask-pyoidc-70 | diff --git a/src/flask_pyoidc/user_session.py b/src/flask_pyoidc/user_session.py
index 962f4db..4578db0 100644
--- a/src/flask_pyoidc/user_session.py
+++ b/src/flask_pyoidc/user_session.py
@@ -11,7 +11,15 @@ class UserSession:
Wraps comparison of times necessary for session handling.
"""
- KEYS = ['access_token', 'current_provider', 'id_token', 'id_token_jwt', 'last_authenticated', 'userinfo']
+ KEYS = [
+ 'access_token',
+ 'current_provider',
+ 'id_token',
+ 'id_token_jwt',
+ 'last_authenticated',
+ 'last_session_refresh',
+ 'userinfo'
+ ]
def __init__(self, session_storage, provider_name=None):
self._session_storage = session_storage
@@ -36,10 +44,11 @@ class UserSession:
def should_refresh(self, refresh_interval_seconds=None):
return refresh_interval_seconds is not None and \
+ self._session_storage.get('last_session_refresh') is not None and \
self._refresh_time(refresh_interval_seconds) < time.time()
def _refresh_time(self, refresh_interval_seconds):
- last = self._session_storage.get('last_authenticated', 0)
+ last = self._session_storage.get('last_session_refresh', 0)
return last + refresh_interval_seconds
def update(self, access_token=None, id_token=None, id_token_jwt=None, userinfo=None):
@@ -55,11 +64,13 @@ class UserSession:
if value:
self._session_storage[session_key] = value
- auth_time = int(time.time())
+ now = int(time.time())
+ auth_time = now
if id_token:
auth_time = id_token.get('auth_time', auth_time)
self._session_storage['last_authenticated'] = auth_time
+ self._session_storage['last_session_refresh'] = now
set_if_defined('access_token', access_token)
set_if_defined('id_token', id_token)
set_if_defined('id_token_jwt', id_token_jwt)
| zamzterz/Flask-pyoidc | cf3f5f8ed0507d310c70b40d13b49dd2a7b708b4 | diff --git a/tests/test_user_session.py b/tests/test_user_session.py
index 6507603..1689161 100644
--- a/tests/test_user_session.py
+++ b/tests/test_user_session.py
@@ -45,17 +45,17 @@ class TestUserSession(object):
def test_should_not_refresh_if_authenticated_within_refresh_interval(self):
refresh_interval = 10
- session = self.initialised_session({'last_authenticated': time.time() + (refresh_interval - 1)})
+ session = self.initialised_session({'last_session_refresh': time.time() + (refresh_interval - 1)})
assert session.should_refresh(refresh_interval) is False
def test_should_refresh_if_supported_and_necessary(self):
refresh_interval = 10
# authenticated too far in the past
- session_storage = {'last_authenticated': time.time() - (refresh_interval + 1)}
+ session_storage = {'last_session_refresh': time.time() - (refresh_interval + 1)}
assert self.initialised_session(session_storage).should_refresh(refresh_interval) is True
- def test_should_refresh_if_supported_and_not_previously_authenticated(self):
- assert self.initialised_session({}).should_refresh(10) is True
+ def test_should_not_refresh_if_not_previously_authenticated(self):
+ assert self.initialised_session({}).should_refresh(10) is False
@pytest.mark.parametrize('data', [
{'access_token': 'test_access_token'},
@@ -71,7 +71,11 @@ class TestUserSession(object):
self.initialised_session(storage).update(**data)
- expected_session_data = {'last_authenticated': auth_time, 'current_provider': self.PROVIDER_NAME}
+ expected_session_data = {
+ 'last_authenticated': auth_time,
+ 'last_session_refresh': auth_time,
+ 'current_provider': self.PROVIDER_NAME
+ }
expected_session_data.update(**data)
assert storage == expected_session_data
@@ -81,6 +85,15 @@ class TestUserSession(object):
session.update(id_token={'auth_time': auth_time})
assert session.last_authenticated == auth_time
+ @patch('time.time')
+ def test_update_should_update_last_session_refresh_timestamp(self, time_mock):
+ now_timestamp = 1234
+ time_mock.return_value = now_timestamp
+ data = {}
+ session = self.initialised_session(data)
+ session.update()
+ assert data['last_session_refresh'] == now_timestamp
+
def test_trying_to_update_uninitialised_session_should_throw_exception(self):
with pytest.raises(UninitialisedSession):
UserSession(session_storage={}).update()
| Issues refreshing tokens when 'session_refresh_interval_seconds' is set
With the current state of flask_pyoidc we're running into the issue of not silently refreshing the tokens when it's desired.
Our current setup is as follows: API endpoints are protected using flask_pyoidc, with the session_refresh_interval_seconds providing `prompt=none` refreshing after 5 minutes.
The first issue we encountered was running into the silent refreshing when the initial authentication has not been successfully established yet.
The second issue was the refreshing being triggered based on the previous auth_time, which didn't change with the request. Instead, what worked was taking the expiry time provided by the OIDC instance to trigger the silent refresh that way.
To illustrate a proposed way of fixing it we've created this change (this is not PR-quality code by any means):
https://github.com/fredldotme/Flask-pyoidc/commit/8a062a1d9d281a80421c1e3adadd84c50ae12c7a
This forces the refresh after 5 minutes. Note that we've added 20 seconds of headroom before the expiry time runs out.
I'd like to get your suggestions on this topic and maybe a way forward in the form of code being merged into upstream. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_user_session.py::TestUserSession::test_should_not_refresh_if_authenticated_within_refresh_interval",
"tests/test_user_session.py::TestUserSession::test_should_not_refresh_if_not_previously_authenticated",
"tests/test_user_session.py::TestUserSession::test_update[data0]",
"tests/test_user_session.py::TestUserSession::test_update[data1]",
"tests/test_user_session.py::TestUserSession::test_update[data2]",
"tests/test_user_session.py::TestUserSession::test_update[data3]",
"tests/test_user_session.py::TestUserSession::test_update_should_update_last_session_refresh_timestamp"
] | [
"tests/test_user_session.py::TestUserSession::test_initialising_session_with_existing_user_session_should_preserve_state",
"tests/test_user_session.py::TestUserSession::test_initialising_session_with_new_provider_name_should_reset_session",
"tests/test_user_session.py::TestUserSession::test_unauthenticated_session",
"tests/test_user_session.py::TestUserSession::test_authenticated_session",
"tests/test_user_session.py::TestUserSession::test_should_not_refresh_if_not_supported",
"tests/test_user_session.py::TestUserSession::test_should_refresh_if_supported_and_necessary",
"tests/test_user_session.py::TestUserSession::test_update_should_use_auth_time_from_id_token_if_it_exists",
"tests/test_user_session.py::TestUserSession::test_trying_to_update_uninitialised_session_should_throw_exception",
"tests/test_user_session.py::TestUserSession::test_clear"
] | {
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
} | "2019-12-12T19:16:30Z" | apache-2.0 |
|
zamzterz__Flask-pyoidc-79 | diff --git a/docs/configuration.md b/docs/configuration.md
index 966193f..432d1d9 100644
--- a/docs/configuration.md
+++ b/docs/configuration.md
@@ -68,8 +68,8 @@ config = ProviderConfiguration([provider configuration], client_metadata=client_
**Note: The redirect URIs registered with the provider MUST include `<application_url>/redirect_uri`,
where `<application_url>` is the URL of the Flask application.**
-To configure this extension to use a different endpoint, set the
-[`OIDC_REDIRECT_ENDPOINT` configuration parameter](#flask-configuration).
+To configure this extension to use a different location, set the
+[`OIDC_REDIRECT_DOMAIN` and/or `OIDC_REDIRECT_ENDPOINT` configuration parameter](#flask-configuration).
#### Dynamic client registration
@@ -87,15 +87,16 @@ config = ProviderConfiguration([provider configuration], client_registration_inf
The application using this extension **MUST** set the following
[builtin configuration values of Flask](http://flask.pocoo.org/docs/config/#builtin-configuration-values):
-* `SERVER_NAME`: **MUST** be the same as `<flask_url>` if using static client registration.
* `SECRET_KEY`: This extension relies on [Flask sessions](http://flask.pocoo.org/docs/quickstart/#sessions), which
requires `SECRET_KEY`.
-You may also configure the way the user sessions created by this extension are handled:
+This extension also defines the following configuration parameters:
+* `OIDC_REDIRECT_DOMAIN`: Set the domain (which may contain port number) used in the redirect_uri to receive
+ authentication responses. Defaults to the `SERVER_NAME` configured for Flask.
+* `OIDC_REDIRECT_ENDPOINT`: Set the endpoint used in the redirect_uri to receive authentication responses. Defaults to
+ `redirect_uri`, meaning the URL `<application_url>/redirect_uri` needs to be registered with the provider(s).
* `OIDC_SESSION_PERMANENT`: If set to `True` (which is the default) the user session will be kept until the configured
session lifetime (see below). If set to `False` the session will be deleted when the user closes the browser.
-* `OIDC_REDIRECT_ENDPOINT`: Set the endpoint used as redirect_uri to receive authentication responses. Defaults to
- `redirect_uri`, meaning the URL `<application_url>/redirect_uri` needs to be registered with the provider(s).
* `PERMANENT_SESSION_LIFETIME`: Control how long a user session is valid, see
[Flask documentation](http://flask.pocoo.org/docs/1.0/config/#PERMANENT_SESSION_LIFETIME) for more information.
diff --git a/src/flask_pyoidc/flask_pyoidc.py b/src/flask_pyoidc/flask_pyoidc.py
index 4eadb25..c5afcea 100644
--- a/src/flask_pyoidc/flask_pyoidc.py
+++ b/src/flask_pyoidc/flask_pyoidc.py
@@ -16,6 +16,7 @@
import functools
import json
import logging
+from urllib.parse import parse_qsl, urlunparse
import flask
import importlib_resources
@@ -23,7 +24,6 @@ from flask import current_app
from flask.helpers import url_for
from oic import rndstr
from oic.oic.message import EndSessionRequest
-from urllib.parse import parse_qsl
from werkzeug.utils import redirect
from .auth_response_handler import AuthResponseProcessError, AuthResponseHandler, AuthResponseErrorResponseError
@@ -65,11 +65,20 @@ class OIDCAuthentication:
methods=['GET', 'POST'])
# dynamically add the Flask redirect uri to the client info
- with app.app_context():
- self.clients = {
- name: PyoidcFacade(configuration, url_for(self._redirect_uri_endpoint))
- for (name, configuration) in self._provider_configurations.items()
- }
+ redirect_uri = self._get_redirect_uri(app)
+ self.clients = {
+ name: PyoidcFacade(configuration, redirect_uri)
+ for (name, configuration) in self._provider_configurations.items()
+ }
+
+ def _get_redirect_uri(self, app):
+ redirect_domain = app.config.get('OIDC_REDIRECT_DOMAIN', app.config.get('SERVER_NAME'))
+
+ if redirect_domain:
+ scheme = app.config.get('PREFERRED_URL_SCHEME', 'http')
+ return urlunparse((scheme, redirect_domain, self._redirect_uri_endpoint, '', '', ''))
+ else:
+ raise ValueError("'OIDC_REDIRECT_DOMAIN' must be configured.")
def _get_post_logout_redirect_uri(self, client):
if client.post_logout_redirect_uris:
| zamzterz/Flask-pyoidc | 45544dd9cdde6abff856d7d303451c3ee5f20649 | diff --git a/tests/test_flask_pyoidc.py b/tests/test_flask_pyoidc.py
index 67ed041..b0c4fac 100644
--- a/tests/test_flask_pyoidc.py
+++ b/tests/test_flask_pyoidc.py
@@ -501,3 +501,15 @@ class TestOIDCAuthentication(object):
authn = self.init_app()
assert authn._redirect_uri_endpoint == 'openid_connect_login'
assert authn.clients['test_provider']._redirect_uri == 'http://client.example.com/openid_connect_login'
+
+ def test_should_use_custom_redirect_domain(self):
+ self.app.config['PREFERRED_URL_SCHEME'] = 'https'
+ self.app.config['OIDC_REDIRECT_DOMAIN'] = 'custom.example.com'
+ authn = self.init_app()
+ assert authn.clients['test_provider']._redirect_uri == 'https://custom.example.com/redirect_uri'
+
+ def test_should_raise_if_domain_not_specified(self):
+ self.app.config['SERVER_NAME'] = None
+ with pytest.raises(ValueError) as exc_info:
+ self.init_app()
+ assert 'OIDC_REDIRECT_DOMAIN' in str(exc_info.value)
| SERVER_NAME requirement
Hi!
I've been playing around today with this great lib but I can't figure out one thing. According to the docs, `SERVER_NAME` must be set in order to the lib to work, but there are no further explanations.
In my case, using the latest version of flask from pip (1.1.2) and the version 3.2.0 of this iib, if I set `SERVER_NAME` to something then all the request that use a different hostname (for example kubernetes liveness and readiness probes, that uses the localhost / localip) get a 404 as an answer. If I don't set `SERVER_NAME` the app won't come up because of the hard requirement of the lib.
Is there some alternative than setting `SERVER_NAME`?
Thanks in advance! | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_should_raise_if_domain_not_specified",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_should_use_custom_redirect_domain"
] | [
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_handle_authentication_response_error_message_without_stored_error",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_should_register_client_if_not_registered_before[None]",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_handle_implicit_authentication_response",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_using_unknown_provider_name_should_raise_exception",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_handle_authentication_response_POST",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_token_error_response_calls_to_error_view_if_set",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_logout_handles_no_user_session",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_handle_authentication_response_error_message",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_expected_auth_response_mode_is_set[code-False]",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_logout_redirects_to_provider_if_end_session_endpoint_is_configured[None]",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_logout_handles_redirect_back_from_provider",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_expected_auth_response_mode_is_set[id_token",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_token_error_response_returns_default_error_if_no_error_view_set",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_should_register_client_if_not_registered_before[post_logout_redirect_uris1]",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_handle_authentication_response_fragment_encoded",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_handle_authentication_response",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_reauthenticate_silent_if_session_expired",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_logout_redirects_to_provider_if_end_session_endpoint_is_configured[https://example.com/post_logout]",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_logout_handles_provider_without_end_session_endpoint",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_logout_handles_redirect_back_from_provider_with_incorrect_state",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_should_not_authenticate_if_session_exists",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_authentication_error_response_returns_default_error_if_no_error_view_set",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_dont_reauthenticate_silent_if_session_not_expired",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_should_authenticate_if_no_session",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_authentication_error_response_calls_to_error_view_if_set",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_should_use_custom_redirect_endpoint"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2020-04-29T17:52:27Z" | apache-2.0 |
|
zamzterz__Flask-pyoidc-96 | diff --git a/src/flask_pyoidc/flask_pyoidc.py b/src/flask_pyoidc/flask_pyoidc.py
index 5ca699f..cd00461 100644
--- a/src/flask_pyoidc/flask_pyoidc.py
+++ b/src/flask_pyoidc/flask_pyoidc.py
@@ -183,7 +183,7 @@ class OIDCAuthentication:
# if the current request was from the JS page handling fragment encoded responses we need to return
# a URL for the error page to redirect to
flask.session['error'] = error_response
- return '/' + self._redirect_uri_endpoint + '?error=1'
+ return '/' + self._redirect_uri_config.endpoint + '?error=1'
return self._show_error_response(error_response)
def _show_error_response(self, error_response):
| zamzterz/Flask-pyoidc | 4aa29e46949e33994edef06eb855b01be7c4d5d4 | diff --git a/tests/test_flask_pyoidc.py b/tests/test_flask_pyoidc.py
index 427cdf9..e507adc 100644
--- a/tests/test_flask_pyoidc.py
+++ b/tests/test_flask_pyoidc.py
@@ -290,6 +290,24 @@ class TestOIDCAuthentication(object):
assert session.access_token == access_token
assert response == '/test'
+ def test_handle_error_response_POST(self):
+ state = 'test_state'
+
+ authn = self.init_app()
+ error_resp = {'state': state, 'error': 'invalid_request', 'error_description': 'test error'}
+
+ with self.app.test_request_context('/redirect_uri',
+ method='POST',
+ data=error_resp,
+ mimetype='application/x-www-form-urlencoded'):
+ UserSession(flask.session, self.PROVIDER_NAME)
+ flask.session['state'] = state
+ flask.session['nonce'] = 'test_nonce'
+ response = authn._handle_authentication_response()
+ assert flask.session['error'] == error_resp
+ assert response == '/redirect_uri?error=1'
+
+
def test_handle_authentication_response_without_initialised_session(self):
authn = self.init_app()
| Error responses using undefined _redirect_uri_endpoint attribute
In some cases (e.g. when the auth state goes stale after much time) we rightfully receive an error that should be passed on to the client
```python
Exception on /redirect_uri [POST]
Traceback (most recent call last):
File "../flask_pyoidc/flask_pyoidc.py", line 156, in _handle_authentication_response
flask.session.pop('nonce'))
File "../lib/python3.7/site-packages/flask_pyoidc/auth_response_handler.py", line 60, in process_auth_response
raise AuthResponseErrorResponseError(auth_response.to_dict())
flask_pyoidc.auth_response_handler.AuthResponseErrorResponseError: {'error': 'login_required', 'state': 'm92iSPHP7qMBXSkQ'}
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "../lib/python3.7/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "../lib/python3.7/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "../lib/python3.7/site-packages/flask_cors/extension.py", line 165, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "../lib/python3.7/site-packages/flask_cors/extension.py", line 165, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "../lib/python3.7/site-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "../lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "../lib/python3.7/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "../lib/python3.7/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "../lib/python3.7/site-packages/flask_pyoidc/flask_pyoidc.py", line 158, in _handle_authentication_response
return self._handle_error_response(e.error_response, is_processing_fragment_encoded_response)
File "../lib/python3.7/site-packages/flask_pyoidc/flask_pyoidc.py", line 186, in _handle_error_response
return '/' + self._redirect_uri_endpoint + '?error=1'
AttributeError: 'OIDCAuthentication' object has no attribute '_redirect_uri_endpoint'
```
Unfortunately it looks like the error handler tries to return a nonexistant attribute (holdover from old code?) for the redirect uri endpoint. I'm guessing this should be
`self._redirect_uri_config.endpoint` instead. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_handle_error_response_POST"
] | [
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_should_register_client_if_not_registered_before[None]",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_handle_authentication_response_fragment_encoded",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_logout_redirects_to_provider_if_end_session_endpoint_is_configured[https://example.com/post_logout]",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_handle_authentication_response_without_stored_nonce",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_logout_handles_no_user_session",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_reauthenticate_silent_if_session_expired",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_should_not_refresh_still_valid_access_token",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_logout_handles_redirect_back_from_provider_with_incorrect_state",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_handle_authentication_response_POST",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_handle_authentication_response_without_initialised_session",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_handle_authentication_response",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_expected_auth_response_mode_is_set[code-False]",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_should_not_refresh_access_token_without_expiry",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_should_not_refresh_without_refresh_token",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_handle_authentication_response_without_stored_state",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_should_not_refresh_if_no_user_session",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_token_error_response_returns_default_error_if_no_error_view_set",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_token_error_response_calls_to_error_view_if_set",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_should_register_client_if_not_registered_before[post_logout_redirect_uris1]",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_expected_auth_response_mode_is_set[id_token",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_logout_handles_provider_without_end_session_endpoint",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_logout_redirects_to_provider_if_end_session_endpoint_is_configured[None]",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_authentication_error_response_returns_default_error_if_no_error_view_set",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_using_unknown_provider_name_should_raise_exception",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_dont_reauthenticate_silent_if_session_not_expired",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_should_return_None_if_token_refresh_request_fails",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_handle_authentication_response_error_message",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_should_refresh_expired_access_token",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_should_authenticate_if_no_session",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_handle_implicit_authentication_response",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_should_not_authenticate_if_session_exists",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_handle_authentication_response_error_message_without_stored_error",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_should_refresh_still_valid_access_token_if_forced",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_logout_handles_redirect_back_from_provider",
"tests/test_flask_pyoidc.py::TestOIDCAuthentication::test_authentication_error_response_calls_to_error_view_if_set"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2020-10-14T20:05:44Z" | apache-2.0 |
|
zarr-developers__zarr-python-1397 | diff --git a/docs/release.rst b/docs/release.rst
index 7442e519..83588bb3 100644
--- a/docs/release.rst
+++ b/docs/release.rst
@@ -52,6 +52,9 @@ Bug fixes
* Fix ``ReadOnlyError`` when opening V3 store via fsspec reference file system.
By :user:`Joe Hamman <jhamman>` :issue:`1383`.
+* Fix ``normalize_fill_value`` for structured arrays.
+ By :user:`Alan Du <alanhdu>` :issue:`1397`.
+
.. _release_2.14.2:
2.14.2
diff --git a/zarr/util.py b/zarr/util.py
index b661f5f6..6ba20b96 100644
--- a/zarr/util.py
+++ b/zarr/util.py
@@ -295,7 +295,7 @@ def normalize_fill_value(fill_value, dtype: np.dtype):
if fill_value is None or dtype.hasobject:
# no fill value
pass
- elif fill_value == 0:
+ elif not isinstance(fill_value, np.void) and fill_value == 0:
# this should be compatible across numpy versions for any array type, including
# structured arrays
fill_value = np.zeros((), dtype=dtype)[()]
| zarr-developers/zarr-python | d54f25c460f8835a0ec9a7b4bc3482159a5608f9 | diff --git a/zarr/tests/test_util.py b/zarr/tests/test_util.py
index 0a717b8f..e01aa671 100644
--- a/zarr/tests/test_util.py
+++ b/zarr/tests/test_util.py
@@ -119,6 +119,7 @@ def test_normalize_fill_value():
structured_dtype = np.dtype([('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')])
expect = np.array((b'', 0, 0.), dtype=structured_dtype)[()]
assert expect == normalize_fill_value(0, dtype=structured_dtype)
+ assert expect == normalize_fill_value(expect, dtype=structured_dtype)
assert '' == normalize_fill_value(0, dtype=np.dtype('U1'))
| FutureWarning from zarr.open
The following code snippet will raise a FutureWarning:
```python
import numpy
import zarr
group = zarr.open()
group.create('foo', dtype=[('a', int), ('b', int)], fill_value=numpy.zeros((), dtype=[('a', int), ('b', int)])[()], shape=(10, 10))
```
#### Problem description
The current behavior raises a FutureWarning:
```python
zarr/util.py:238: FutureWarning: elementwise == comparison failed and returning scalar instead; this will raise an error or perform elementwise comparison in the future.
elif fill_value == 0:
```
This happens because of the comparison of the utterable dtype to 0 (in line 258) above. I'm not sure if this error is a false positive from numpy or something that will actually break in a future numpy version.
#### Version and installation information
Please provide the following:
* Value of ``zarr.__version__``: '2.3.2'
* Value of ``numcodecs.__version__``: '0.6.4'
* Version of Python interpreter: 3.7.6
* Operating system (Linux/Windows/Mac): Mac and Linux
* How Zarr was installed: using conda (also from source)
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"zarr/tests/test_util.py::test_normalize_fill_value"
] | [
"zarr/tests/test_util.py::test_normalize_dimension_separator",
"zarr/tests/test_util.py::test_normalize_shape",
"zarr/tests/test_util.py::test_normalize_chunks",
"zarr/tests/test_util.py::test_is_total_slice",
"zarr/tests/test_util.py::test_normalize_resize_args",
"zarr/tests/test_util.py::test_human_readable_size",
"zarr/tests/test_util.py::test_normalize_order",
"zarr/tests/test_util.py::test_guess_chunks",
"zarr/tests/test_util.py::test_info_text_report",
"zarr/tests/test_util.py::test_info_html_report",
"zarr/tests/test_util.py::test_tree_get_icon",
"zarr/tests/test_util.py::test_tree_widget_missing_ipytree",
"zarr/tests/test_util.py::test_retry_call",
"zarr/tests/test_util.py::test_flatten",
"zarr/tests/test_util.py::test_all_equal",
"zarr/tests/test_util.py::test_json_dumps_numpy_dtype",
"zarr/tests/test_util.py::test_constant_map"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2023-04-20T16:28:03Z" | mit |
|
zarr-developers__zarr-python-1499 | diff --git a/docs/release.rst b/docs/release.rst
index cf1400d3..188edd62 100644
--- a/docs/release.rst
+++ b/docs/release.rst
@@ -27,6 +27,9 @@ Maintenance
* Add ``docs`` requirements to ``pyproject.toml``
By :user:`John A. Kirkham <jakirkham>` :issue:`1494`.
+* Fixed caching issue in ``LRUStoreCache``.
+ By :user:`Mads R. B. Kristensen <madsbk>` :issue:`1499`.
+
.. _release_2.16.0:
2.16.0
diff --git a/zarr/_storage/v3.py b/zarr/_storage/v3.py
index 1a50265c..00dc085d 100644
--- a/zarr/_storage/v3.py
+++ b/zarr/_storage/v3.py
@@ -509,7 +509,7 @@ class LRUStoreCacheV3(RmdirV3, LRUStoreCache, StoreV3):
self._max_size = max_size
self._current_size = 0
self._keys_cache = None
- self._contains_cache = None
+ self._contains_cache = {}
self._listdir_cache: Dict[Path, Any] = dict()
self._values_cache: Dict[Path, Any] = OrderedDict()
self._mutex = Lock()
diff --git a/zarr/storage.py b/zarr/storage.py
index 4f7b9905..b36f804e 100644
--- a/zarr/storage.py
+++ b/zarr/storage.py
@@ -2393,7 +2393,7 @@ class LRUStoreCache(Store):
self._max_size = max_size
self._current_size = 0
self._keys_cache = None
- self._contains_cache = None
+ self._contains_cache: Dict[Any, Any] = {}
self._listdir_cache: Dict[Path, Any] = dict()
self._values_cache: Dict[Path, Any] = OrderedDict()
self._mutex = Lock()
@@ -2434,9 +2434,9 @@ class LRUStoreCache(Store):
def __contains__(self, key):
with self._mutex:
- if self._contains_cache is None:
- self._contains_cache = set(self._keys())
- return key in self._contains_cache
+ if key not in self._contains_cache:
+ self._contains_cache[key] = key in self._store
+ return self._contains_cache[key]
def clear(self):
self._store.clear()
@@ -2506,7 +2506,7 @@ class LRUStoreCache(Store):
def _invalidate_keys(self):
self._keys_cache = None
- self._contains_cache = None
+ self._contains_cache.clear()
self._listdir_cache.clear()
def _invalidate_value(self, key):
| zarr-developers/zarr-python | f542fca7d0d42ee050e9a49d57ad0f5346f62de3 | diff --git a/zarr/tests/test_storage.py b/zarr/tests/test_storage.py
index 95570004..ca6a6c1a 100644
--- a/zarr/tests/test_storage.py
+++ b/zarr/tests/test_storage.py
@@ -2196,7 +2196,10 @@ class TestLRUStoreCache(StoreTests):
assert keys == sorted(cache.keys())
assert 1 == store.counter["keys"]
assert foo_key in cache
- assert 0 == store.counter["__contains__", foo_key]
+ assert 1 == store.counter["__contains__", foo_key]
+ # the next check for `foo_key` is cached
+ assert foo_key in cache
+ assert 1 == store.counter["__contains__", foo_key]
assert keys == sorted(cache)
assert 0 == store.counter["__iter__"]
assert 1 == store.counter["keys"]
@@ -2215,23 +2218,23 @@ class TestLRUStoreCache(StoreTests):
keys = sorted(cache.keys())
assert keys == [bar_key, baz_key, foo_key]
assert 3 == store.counter["keys"]
- assert 0 == store.counter["__contains__", foo_key]
+ assert 1 == store.counter["__contains__", foo_key]
assert 0 == store.counter["__iter__"]
cache.invalidate_keys()
keys = sorted(cache)
assert keys == [bar_key, baz_key, foo_key]
assert 4 == store.counter["keys"]
- assert 0 == store.counter["__contains__", foo_key]
+ assert 1 == store.counter["__contains__", foo_key]
assert 0 == store.counter["__iter__"]
cache.invalidate_keys()
assert foo_key in cache
- assert 5 == store.counter["keys"]
- assert 0 == store.counter["__contains__", foo_key]
+ assert 4 == store.counter["keys"]
+ assert 2 == store.counter["__contains__", foo_key]
assert 0 == store.counter["__iter__"]
# check these would get counted if called directly
assert foo_key in store
- assert 1 == store.counter["__contains__", foo_key]
+ assert 3 == store.counter["__contains__", foo_key]
assert keys == sorted(store)
assert 1 == store.counter["__iter__"]
| tifffile.ZarrTiffStore wrapped in zarr.LRUStoreCache fails to read any chunks
### Zarr version
2.16.0
### Numcodecs version
0.11.0
### Python Version
3.11.4
### Operating System
Windows
### Installation
py -m pip install -U zarr
### Description
Since zarr v2.15.0, the `tifffile.ZarrTiffStore` fails to read any chunks when wrapping the store in `zarr.LRUStoreCache`. The chunks returned by `LRUStoreCache` are always zeroed.
I don't understand yet what change in v2.15 causes the failure. It may be related to `ZarrTiffStore` not returning all chunk keys from the `keys` method because there may be many million keys and it would take significant resources to parse the TIFF file(s) for all keys upfront. Instead, the store relies on the `__contains__` method.
The following patch fixes the issue for me:
```patch
diff --git a/zarr/storage.py b/zarr/storage.py
index 4f7b9905..c3260638 100644
--- a/zarr/storage.py
+++ b/zarr/storage.py
@@ -2436,7 +2436,7 @@ class LRUStoreCache(Store):
with self._mutex:
if self._contains_cache is None:
self._contains_cache = set(self._keys())
- return key in self._contains_cache
+ return key in self._contains_cache or key in self._store
def clear(self):
self._store.clear()
```
### Steps to reproduce
```Python
import numpy
import zarr
import tifffile
data = numpy.random.rand(8, 8)
tifffile.imwrite('test.tif', data)
store = tifffile.imread('test.tif', aszarr=True)
try:
# without cache
zarray = zarr.open(store, mode='r')
numpy.testing.assert_array_equal(zarray, data)
# with cache
cache = zarr.LRUStoreCache(store, max_size=2**10)
zarray = zarr.open(cache, mode='r')
numpy.testing.assert_array_equal(zarray, data)
finally:
store.close()
```
### Additional output
```Python traceback
Traceback (most recent call last):
File "D:\Dev\Python\tifffile\test_zarr_lrucache.py", line 16, in <module>
numpy.testing.assert_array_equal(zarray, data)
File "X:\Python311\Lib\site-packages\numpy\testing\_private\utils.py", line 920, in assert_array_equal
assert_array_compare(operator.__eq__, x, y, err_msg=err_msg,
File "X:\Python311\Lib\contextlib.py", line 81, in inner
return func(*args, **kwds)
^^^^^^^^^^^^^^^^^^^
File "X:\Python311\Lib\site-packages\numpy\testing\_private\utils.py", line 797, in assert_array_compare
raise AssertionError(msg)
AssertionError:
Arrays are not equal
Mismatched elements: 64 / 64 (100%)
Max absolute difference: 0.99263945
Max relative difference: 1.
x: array([[0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0.],...
y: array([[0.992639, 0.580277, 0.454157, 0.055261, 0.664422, 0.82762 ,
0.144393, 0.240842],
[0.241279, 0.190615, 0.37115 , 0.078737, 0.706201, 0.593853,...
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"zarr/tests/test_storage.py::TestLRUStoreCache::test_cache_keys"
] | [
"zarr/tests/test_storage.py::test_kvstore_repr",
"zarr/tests/test_storage.py::test_ensure_store",
"zarr/tests/test_storage.py::test_capabilities",
"zarr/tests/test_storage.py::test_getsize_non_implemented",
"zarr/tests/test_storage.py::test_kvstore_eq",
"zarr/tests/test_storage.py::test_coverage_rename",
"zarr/tests/test_storage.py::test_deprecated_listdir_nosotre",
"zarr/tests/test_storage.py::TestMappingStore::test_context_manager",
"zarr/tests/test_storage.py::TestMappingStore::test_get_set_del_contains",
"zarr/tests/test_storage.py::TestMappingStore::test_clear",
"zarr/tests/test_storage.py::TestMappingStore::test_pop",
"zarr/tests/test_storage.py::TestMappingStore::test_popitem",
"zarr/tests/test_storage.py::TestMappingStore::test_writeable_values",
"zarr/tests/test_storage.py::TestMappingStore::test_update",
"zarr/tests/test_storage.py::TestMappingStore::test_iterators",
"zarr/tests/test_storage.py::TestMappingStore::test_pickle",
"zarr/tests/test_storage.py::TestMappingStore::test_getsize",
"zarr/tests/test_storage.py::TestMappingStore::test_hierarchy",
"zarr/tests/test_storage.py::TestMappingStore::test_init_array[dimension_separator_fixture0]",
"zarr/tests/test_storage.py::TestMappingStore::test_init_array[dimension_separator_fixture1]",
"zarr/tests/test_storage.py::TestMappingStore::test_init_array_overwrite",
"zarr/tests/test_storage.py::TestMappingStore::test_init_array_overwrite_path",
"zarr/tests/test_storage.py::TestMappingStore::test_init_array_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestMappingStore::test_init_group_overwrite",
"zarr/tests/test_storage.py::TestMappingStore::test_init_group_overwrite_path",
"zarr/tests/test_storage.py::TestMappingStore::test_init_group_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestMappingStore::test_init_array_path",
"zarr/tests/test_storage.py::TestMappingStore::test_init_array_overwrite_group",
"zarr/tests/test_storage.py::TestMappingStore::test_init_array_compat",
"zarr/tests/test_storage.py::TestMappingStore::test_init_group",
"zarr/tests/test_storage.py::TestMappingStore::test_set_invalid_content",
"zarr/tests/test_storage.py::TestMemoryStore::test_context_manager",
"zarr/tests/test_storage.py::TestMemoryStore::test_get_set_del_contains",
"zarr/tests/test_storage.py::TestMemoryStore::test_set_invalid_content",
"zarr/tests/test_storage.py::TestMemoryStore::test_clear",
"zarr/tests/test_storage.py::TestMemoryStore::test_pop",
"zarr/tests/test_storage.py::TestMemoryStore::test_popitem",
"zarr/tests/test_storage.py::TestMemoryStore::test_writeable_values",
"zarr/tests/test_storage.py::TestMemoryStore::test_update",
"zarr/tests/test_storage.py::TestMemoryStore::test_iterators",
"zarr/tests/test_storage.py::TestMemoryStore::test_pickle",
"zarr/tests/test_storage.py::TestMemoryStore::test_getsize",
"zarr/tests/test_storage.py::TestMemoryStore::test_hierarchy",
"zarr/tests/test_storage.py::TestMemoryStore::test_init_array[dimension_separator_fixture0]",
"zarr/tests/test_storage.py::TestMemoryStore::test_init_array[dimension_separator_fixture1]",
"zarr/tests/test_storage.py::TestMemoryStore::test_init_array_overwrite",
"zarr/tests/test_storage.py::TestMemoryStore::test_init_array_overwrite_path",
"zarr/tests/test_storage.py::TestMemoryStore::test_init_array_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestMemoryStore::test_init_group_overwrite",
"zarr/tests/test_storage.py::TestMemoryStore::test_init_group_overwrite_path",
"zarr/tests/test_storage.py::TestMemoryStore::test_init_group_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestMemoryStore::test_init_array_path",
"zarr/tests/test_storage.py::TestMemoryStore::test_init_array_overwrite_group",
"zarr/tests/test_storage.py::TestMemoryStore::test_init_array_compat",
"zarr/tests/test_storage.py::TestMemoryStore::test_init_group",
"zarr/tests/test_storage.py::TestMemoryStore::test_store_contains_bytes",
"zarr/tests/test_storage.py::TestMemoryStore::test_setdel",
"zarr/tests/test_storage.py::TestDictStore::test_context_manager",
"zarr/tests/test_storage.py::TestDictStore::test_get_set_del_contains",
"zarr/tests/test_storage.py::TestDictStore::test_set_invalid_content",
"zarr/tests/test_storage.py::TestDictStore::test_clear",
"zarr/tests/test_storage.py::TestDictStore::test_pop",
"zarr/tests/test_storage.py::TestDictStore::test_popitem",
"zarr/tests/test_storage.py::TestDictStore::test_writeable_values",
"zarr/tests/test_storage.py::TestDictStore::test_update",
"zarr/tests/test_storage.py::TestDictStore::test_iterators",
"zarr/tests/test_storage.py::TestDictStore::test_getsize",
"zarr/tests/test_storage.py::TestDictStore::test_hierarchy",
"zarr/tests/test_storage.py::TestDictStore::test_init_array[dimension_separator_fixture0]",
"zarr/tests/test_storage.py::TestDictStore::test_init_array[dimension_separator_fixture1]",
"zarr/tests/test_storage.py::TestDictStore::test_init_array_overwrite",
"zarr/tests/test_storage.py::TestDictStore::test_init_array_overwrite_path",
"zarr/tests/test_storage.py::TestDictStore::test_init_array_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestDictStore::test_init_group_overwrite",
"zarr/tests/test_storage.py::TestDictStore::test_init_group_overwrite_path",
"zarr/tests/test_storage.py::TestDictStore::test_init_group_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestDictStore::test_init_array_path",
"zarr/tests/test_storage.py::TestDictStore::test_init_array_overwrite_group",
"zarr/tests/test_storage.py::TestDictStore::test_init_array_compat",
"zarr/tests/test_storage.py::TestDictStore::test_init_group",
"zarr/tests/test_storage.py::TestDictStore::test_deprecated",
"zarr/tests/test_storage.py::TestDictStore::test_pickle",
"zarr/tests/test_storage.py::TestDirectoryStore::test_context_manager",
"zarr/tests/test_storage.py::TestDirectoryStore::test_get_set_del_contains",
"zarr/tests/test_storage.py::TestDirectoryStore::test_set_invalid_content",
"zarr/tests/test_storage.py::TestDirectoryStore::test_clear",
"zarr/tests/test_storage.py::TestDirectoryStore::test_pop",
"zarr/tests/test_storage.py::TestDirectoryStore::test_popitem",
"zarr/tests/test_storage.py::TestDirectoryStore::test_writeable_values",
"zarr/tests/test_storage.py::TestDirectoryStore::test_update",
"zarr/tests/test_storage.py::TestDirectoryStore::test_iterators",
"zarr/tests/test_storage.py::TestDirectoryStore::test_pickle",
"zarr/tests/test_storage.py::TestDirectoryStore::test_getsize",
"zarr/tests/test_storage.py::TestDirectoryStore::test_hierarchy",
"zarr/tests/test_storage.py::TestDirectoryStore::test_init_array[dimension_separator_fixture0]",
"zarr/tests/test_storage.py::TestDirectoryStore::test_init_array[dimension_separator_fixture1]",
"zarr/tests/test_storage.py::TestDirectoryStore::test_init_array[dimension_separator_fixture2]",
"zarr/tests/test_storage.py::TestDirectoryStore::test_init_array_overwrite",
"zarr/tests/test_storage.py::TestDirectoryStore::test_init_array_overwrite_path",
"zarr/tests/test_storage.py::TestDirectoryStore::test_init_array_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestDirectoryStore::test_init_group_overwrite",
"zarr/tests/test_storage.py::TestDirectoryStore::test_init_group_overwrite_path",
"zarr/tests/test_storage.py::TestDirectoryStore::test_init_group_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestDirectoryStore::test_init_array_path",
"zarr/tests/test_storage.py::TestDirectoryStore::test_init_array_overwrite_group",
"zarr/tests/test_storage.py::TestDirectoryStore::test_init_array_compat",
"zarr/tests/test_storage.py::TestDirectoryStore::test_init_group",
"zarr/tests/test_storage.py::TestDirectoryStore::test_filesystem_path",
"zarr/tests/test_storage.py::TestDirectoryStore::test_init_pathlib",
"zarr/tests/test_storage.py::TestDirectoryStore::test_pickle_ext",
"zarr/tests/test_storage.py::TestDirectoryStore::test_setdel",
"zarr/tests/test_storage.py::TestDirectoryStore::test_normalize_keys",
"zarr/tests/test_storage.py::TestDirectoryStore::test_listing_keys_slash",
"zarr/tests/test_storage.py::TestDirectoryStore::test_listing_keys_no_slash",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_context_manager",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_get_set_del_contains",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_set_invalid_content",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_clear",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_pop",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_popitem",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_writeable_values",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_update",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_iterators",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_pickle",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_getsize",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_hierarchy",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_init_array_overwrite",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_init_array_overwrite_path",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_init_array_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_init_group_overwrite",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_init_group_overwrite_path",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_init_group_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_init_array_path",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_init_array_overwrite_group",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_init_array_compat",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_init_group",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_filesystem_path",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_init_pathlib",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_pickle_ext",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_setdel",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_normalize_keys",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_listing_keys_slash",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_listing_keys_no_slash",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_init_array",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_chunk_nesting",
"zarr/tests/test_storage.py::TestNestedDirectoryStore::test_listdir",
"zarr/tests/test_storage.py::TestNestedDirectoryStoreNone::test_value_error",
"zarr/tests/test_storage.py::TestNestedDirectoryStoreWithWrongValue::test_value_error",
"zarr/tests/test_storage.py::TestN5Store::test_context_manager",
"zarr/tests/test_storage.py::TestN5Store::test_get_set_del_contains",
"zarr/tests/test_storage.py::TestN5Store::test_set_invalid_content",
"zarr/tests/test_storage.py::TestN5Store::test_clear",
"zarr/tests/test_storage.py::TestN5Store::test_pop",
"zarr/tests/test_storage.py::TestN5Store::test_popitem",
"zarr/tests/test_storage.py::TestN5Store::test_writeable_values",
"zarr/tests/test_storage.py::TestN5Store::test_update",
"zarr/tests/test_storage.py::TestN5Store::test_iterators",
"zarr/tests/test_storage.py::TestN5Store::test_pickle",
"zarr/tests/test_storage.py::TestN5Store::test_getsize",
"zarr/tests/test_storage.py::TestN5Store::test_hierarchy",
"zarr/tests/test_storage.py::TestN5Store::test_init_array_overwrite_group",
"zarr/tests/test_storage.py::TestN5Store::test_filesystem_path",
"zarr/tests/test_storage.py::TestN5Store::test_init_pathlib",
"zarr/tests/test_storage.py::TestN5Store::test_pickle_ext",
"zarr/tests/test_storage.py::TestN5Store::test_setdel",
"zarr/tests/test_storage.py::TestN5Store::test_normalize_keys",
"zarr/tests/test_storage.py::TestN5Store::test_listing_keys_slash",
"zarr/tests/test_storage.py::TestN5Store::test_listing_keys_no_slash",
"zarr/tests/test_storage.py::TestN5Store::test_listdir",
"zarr/tests/test_storage.py::TestN5Store::test_equal",
"zarr/tests/test_storage.py::TestN5Store::test_del_zarr_meta_key[.zarray]",
"zarr/tests/test_storage.py::TestN5Store::test_del_zarr_meta_key[.zattrs]",
"zarr/tests/test_storage.py::TestN5Store::test_del_zarr_meta_key[.zgroup]",
"zarr/tests/test_storage.py::TestN5Store::test_chunk_nesting",
"zarr/tests/test_storage.py::TestN5Store::test_init_array",
"zarr/tests/test_storage.py::TestN5Store::test_init_array_path",
"zarr/tests/test_storage.py::TestN5Store::test_init_array_compat",
"zarr/tests/test_storage.py::TestN5Store::test_init_array_overwrite",
"zarr/tests/test_storage.py::TestN5Store::test_init_array_overwrite_path",
"zarr/tests/test_storage.py::TestN5Store::test_init_array_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestN5Store::test_init_group_overwrite",
"zarr/tests/test_storage.py::TestN5Store::test_init_group_overwrite_path",
"zarr/tests/test_storage.py::TestN5Store::test_init_group_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestN5Store::test_init_group",
"zarr/tests/test_storage.py::TestN5Store::test_filters",
"zarr/tests/test_storage.py::TestTempStore::test_context_manager",
"zarr/tests/test_storage.py::TestTempStore::test_get_set_del_contains",
"zarr/tests/test_storage.py::TestTempStore::test_set_invalid_content",
"zarr/tests/test_storage.py::TestTempStore::test_clear",
"zarr/tests/test_storage.py::TestTempStore::test_pop",
"zarr/tests/test_storage.py::TestTempStore::test_popitem",
"zarr/tests/test_storage.py::TestTempStore::test_writeable_values",
"zarr/tests/test_storage.py::TestTempStore::test_update",
"zarr/tests/test_storage.py::TestTempStore::test_iterators",
"zarr/tests/test_storage.py::TestTempStore::test_pickle",
"zarr/tests/test_storage.py::TestTempStore::test_getsize",
"zarr/tests/test_storage.py::TestTempStore::test_hierarchy",
"zarr/tests/test_storage.py::TestTempStore::test_init_array[dimension_separator_fixture0]",
"zarr/tests/test_storage.py::TestTempStore::test_init_array[dimension_separator_fixture1]",
"zarr/tests/test_storage.py::TestTempStore::test_init_array_overwrite",
"zarr/tests/test_storage.py::TestTempStore::test_init_array_overwrite_path",
"zarr/tests/test_storage.py::TestTempStore::test_init_array_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestTempStore::test_init_group_overwrite",
"zarr/tests/test_storage.py::TestTempStore::test_init_group_overwrite_path",
"zarr/tests/test_storage.py::TestTempStore::test_init_group_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestTempStore::test_init_array_path",
"zarr/tests/test_storage.py::TestTempStore::test_init_array_overwrite_group",
"zarr/tests/test_storage.py::TestTempStore::test_init_array_compat",
"zarr/tests/test_storage.py::TestTempStore::test_init_group",
"zarr/tests/test_storage.py::TestTempStore::test_setdel",
"zarr/tests/test_storage.py::TestZipStore::test_get_set_del_contains",
"zarr/tests/test_storage.py::TestZipStore::test_set_invalid_content",
"zarr/tests/test_storage.py::TestZipStore::test_clear",
"zarr/tests/test_storage.py::TestZipStore::test_writeable_values",
"zarr/tests/test_storage.py::TestZipStore::test_update",
"zarr/tests/test_storage.py::TestZipStore::test_iterators",
"zarr/tests/test_storage.py::TestZipStore::test_pickle",
"zarr/tests/test_storage.py::TestZipStore::test_getsize",
"zarr/tests/test_storage.py::TestZipStore::test_hierarchy",
"zarr/tests/test_storage.py::TestZipStore::test_init_array[dimension_separator_fixture0]",
"zarr/tests/test_storage.py::TestZipStore::test_init_array[dimension_separator_fixture1]",
"zarr/tests/test_storage.py::TestZipStore::test_init_array[dimension_separator_fixture2]",
"zarr/tests/test_storage.py::TestZipStore::test_init_array_overwrite",
"zarr/tests/test_storage.py::TestZipStore::test_init_array_overwrite_path",
"zarr/tests/test_storage.py::TestZipStore::test_init_array_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestZipStore::test_init_group_overwrite",
"zarr/tests/test_storage.py::TestZipStore::test_init_group_overwrite_path",
"zarr/tests/test_storage.py::TestZipStore::test_init_group_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestZipStore::test_init_array_path",
"zarr/tests/test_storage.py::TestZipStore::test_init_array_overwrite_group",
"zarr/tests/test_storage.py::TestZipStore::test_init_array_compat",
"zarr/tests/test_storage.py::TestZipStore::test_init_group",
"zarr/tests/test_storage.py::TestZipStore::test_mode",
"zarr/tests/test_storage.py::TestZipStore::test_flush",
"zarr/tests/test_storage.py::TestZipStore::test_context_manager",
"zarr/tests/test_storage.py::TestZipStore::test_pop",
"zarr/tests/test_storage.py::TestZipStore::test_popitem",
"zarr/tests/test_storage.py::TestZipStore::test_permissions",
"zarr/tests/test_storage.py::TestZipStore::test_store_and_retrieve_ndarray",
"zarr/tests/test_storage.py::TestDBMStore::test_get_set_del_contains",
"zarr/tests/test_storage.py::TestDBMStore::test_set_invalid_content",
"zarr/tests/test_storage.py::TestDBMStore::test_clear",
"zarr/tests/test_storage.py::TestDBMStore::test_pop",
"zarr/tests/test_storage.py::TestDBMStore::test_popitem",
"zarr/tests/test_storage.py::TestDBMStore::test_writeable_values",
"zarr/tests/test_storage.py::TestDBMStore::test_update",
"zarr/tests/test_storage.py::TestDBMStore::test_iterators",
"zarr/tests/test_storage.py::TestDBMStore::test_pickle",
"zarr/tests/test_storage.py::TestDBMStore::test_getsize",
"zarr/tests/test_storage.py::TestDBMStore::test_hierarchy",
"zarr/tests/test_storage.py::TestDBMStore::test_init_array[dimension_separator_fixture0]",
"zarr/tests/test_storage.py::TestDBMStore::test_init_array[dimension_separator_fixture1]",
"zarr/tests/test_storage.py::TestDBMStore::test_init_array[dimension_separator_fixture2]",
"zarr/tests/test_storage.py::TestDBMStore::test_init_array_overwrite",
"zarr/tests/test_storage.py::TestDBMStore::test_init_array_overwrite_path",
"zarr/tests/test_storage.py::TestDBMStore::test_init_array_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestDBMStore::test_init_group_overwrite",
"zarr/tests/test_storage.py::TestDBMStore::test_init_group_overwrite_path",
"zarr/tests/test_storage.py::TestDBMStore::test_init_group_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestDBMStore::test_init_array_path",
"zarr/tests/test_storage.py::TestDBMStore::test_init_array_overwrite_group",
"zarr/tests/test_storage.py::TestDBMStore::test_init_array_compat",
"zarr/tests/test_storage.py::TestDBMStore::test_init_group",
"zarr/tests/test_storage.py::TestDBMStore::test_context_manager",
"zarr/tests/test_storage.py::TestDBMStoreDumb::test_get_set_del_contains",
"zarr/tests/test_storage.py::TestDBMStoreDumb::test_set_invalid_content",
"zarr/tests/test_storage.py::TestDBMStoreDumb::test_clear",
"zarr/tests/test_storage.py::TestDBMStoreDumb::test_pop",
"zarr/tests/test_storage.py::TestDBMStoreDumb::test_popitem",
"zarr/tests/test_storage.py::TestDBMStoreDumb::test_writeable_values",
"zarr/tests/test_storage.py::TestDBMStoreDumb::test_update",
"zarr/tests/test_storage.py::TestDBMStoreDumb::test_iterators",
"zarr/tests/test_storage.py::TestDBMStoreDumb::test_pickle",
"zarr/tests/test_storage.py::TestDBMStoreDumb::test_getsize",
"zarr/tests/test_storage.py::TestDBMStoreDumb::test_hierarchy",
"zarr/tests/test_storage.py::TestDBMStoreDumb::test_init_array[dimension_separator_fixture0]",
"zarr/tests/test_storage.py::TestDBMStoreDumb::test_init_array[dimension_separator_fixture1]",
"zarr/tests/test_storage.py::TestDBMStoreDumb::test_init_array[dimension_separator_fixture2]",
"zarr/tests/test_storage.py::TestDBMStoreDumb::test_init_array_overwrite",
"zarr/tests/test_storage.py::TestDBMStoreDumb::test_init_array_overwrite_path",
"zarr/tests/test_storage.py::TestDBMStoreDumb::test_init_array_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestDBMStoreDumb::test_init_group_overwrite",
"zarr/tests/test_storage.py::TestDBMStoreDumb::test_init_group_overwrite_path",
"zarr/tests/test_storage.py::TestDBMStoreDumb::test_init_group_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestDBMStoreDumb::test_init_array_path",
"zarr/tests/test_storage.py::TestDBMStoreDumb::test_init_array_overwrite_group",
"zarr/tests/test_storage.py::TestDBMStoreDumb::test_init_array_compat",
"zarr/tests/test_storage.py::TestDBMStoreDumb::test_init_group",
"zarr/tests/test_storage.py::TestDBMStoreDumb::test_context_manager",
"zarr/tests/test_storage.py::TestSQLiteStore::test_context_manager",
"zarr/tests/test_storage.py::TestSQLiteStore::test_get_set_del_contains",
"zarr/tests/test_storage.py::TestSQLiteStore::test_set_invalid_content",
"zarr/tests/test_storage.py::TestSQLiteStore::test_clear",
"zarr/tests/test_storage.py::TestSQLiteStore::test_pop",
"zarr/tests/test_storage.py::TestSQLiteStore::test_popitem",
"zarr/tests/test_storage.py::TestSQLiteStore::test_writeable_values",
"zarr/tests/test_storage.py::TestSQLiteStore::test_update",
"zarr/tests/test_storage.py::TestSQLiteStore::test_iterators",
"zarr/tests/test_storage.py::TestSQLiteStore::test_pickle",
"zarr/tests/test_storage.py::TestSQLiteStore::test_getsize",
"zarr/tests/test_storage.py::TestSQLiteStore::test_hierarchy",
"zarr/tests/test_storage.py::TestSQLiteStore::test_init_array[dimension_separator_fixture0]",
"zarr/tests/test_storage.py::TestSQLiteStore::test_init_array[dimension_separator_fixture1]",
"zarr/tests/test_storage.py::TestSQLiteStore::test_init_array[dimension_separator_fixture2]",
"zarr/tests/test_storage.py::TestSQLiteStore::test_init_array_overwrite",
"zarr/tests/test_storage.py::TestSQLiteStore::test_init_array_overwrite_path",
"zarr/tests/test_storage.py::TestSQLiteStore::test_init_array_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestSQLiteStore::test_init_group_overwrite",
"zarr/tests/test_storage.py::TestSQLiteStore::test_init_group_overwrite_path",
"zarr/tests/test_storage.py::TestSQLiteStore::test_init_group_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestSQLiteStore::test_init_array_path",
"zarr/tests/test_storage.py::TestSQLiteStore::test_init_array_overwrite_group",
"zarr/tests/test_storage.py::TestSQLiteStore::test_init_array_compat",
"zarr/tests/test_storage.py::TestSQLiteStore::test_init_group",
"zarr/tests/test_storage.py::TestSQLiteStore::test_underscore_in_name",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_context_manager",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_get_set_del_contains",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_set_invalid_content",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_clear",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_pop",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_popitem",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_writeable_values",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_update",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_iterators",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_getsize",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_hierarchy",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_init_array[dimension_separator_fixture0]",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_init_array[dimension_separator_fixture1]",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_init_array[dimension_separator_fixture2]",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_init_array_overwrite",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_init_array_overwrite_path",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_init_array_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_init_group_overwrite",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_init_group_overwrite_path",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_init_group_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_init_array_path",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_init_array_overwrite_group",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_init_array_compat",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_init_group",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_underscore_in_name",
"zarr/tests/test_storage.py::TestSQLiteStoreInMemory::test_pickle",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_context_manager",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_get_set_del_contains",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_set_invalid_content",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_clear",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_pop",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_popitem",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_writeable_values",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_update",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_iterators",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_pickle",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_getsize",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_hierarchy",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_init_array[dimension_separator_fixture0]",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_init_array[dimension_separator_fixture1]",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_init_array_overwrite",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_init_array_overwrite_path",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_init_array_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_init_group_overwrite",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_init_group_overwrite_path",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_init_group_overwrite_chunk_store",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_init_array_path",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_init_array_overwrite_group",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_init_array_compat",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_init_group",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_cache_values_no_max_size",
"zarr/tests/test_storage.py::TestLRUStoreCache::test_cache_values_with_max_size",
"zarr/tests/test_storage.py::test_getsize",
"zarr/tests/test_storage.py::test_migrate_1to2[False]",
"zarr/tests/test_storage.py::test_migrate_1to2[True]",
"zarr/tests/test_storage.py::test_format_compatibility",
"zarr/tests/test_storage.py::TestConsolidatedMetadataStore::test_bad_format",
"zarr/tests/test_storage.py::TestConsolidatedMetadataStore::test_bad_store_version",
"zarr/tests/test_storage.py::TestConsolidatedMetadataStore::test_read_write",
"zarr/tests/test_storage.py::test_fill_value_change",
"zarr/tests/test_storage.py::test_get_hierarchy_metadata_v2",
"zarr/tests/test_storage.py::test_normalize_store_arg",
"zarr/tests/test_storage.py::test_meta_prefix_6853",
"zarr/tests/test_storage.py::test_getitems_contexts"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-08-14T10:08:51Z" | mit |
|
zarr-developers__zarr-python-1724 | diff --git a/docs/release.rst b/docs/release.rst
index 116393d4..fd48a53b 100644
--- a/docs/release.rst
+++ b/docs/release.rst
@@ -18,6 +18,12 @@ Release notes
Unreleased
----------
+Enhancements
+~~~~~~~~~~~~
+
+* Override IPython ``_repr_*_`` methods to avoid expensive lookups against object stores.
+ By :user:`Deepak Cherian <dcherian>` :issue:`1716`.
+
Maintenance
~~~~~~~~~~~
diff --git a/zarr/hierarchy.py b/zarr/hierarchy.py
index 44af1d63..c88892c9 100644
--- a/zarr/hierarchy.py
+++ b/zarr/hierarchy.py
@@ -515,6 +515,13 @@ class Group(MutableMapping):
raise KeyError(item)
def __getattr__(self, item):
+ # https://github.com/jupyter/notebook/issues/2014
+ # Save a possibly expensive lookup (for e.g. against cloud stores)
+ # Note: The _ipython_display_ method is required to display the right info as a side-effect.
+ # It is simpler to pretend it doesn't exist.
+ if item in ["_ipython_canary_method_should_not_exist_", "_ipython_display_"]:
+ raise AttributeError
+
# allow access to group members via dot notation
try:
return self.__getitem__(item)
@@ -1331,6 +1338,40 @@ class Group(MutableMapping):
self._write_op(self._move_nosync, source, dest)
+ # Override ipython repr methods, GH1716
+ # https://ipython.readthedocs.io/en/stable/config/integrating.html#custom-methods
+ # " If the methods don’t exist, the standard repr() is used. If a method exists and
+ # returns None, it is treated the same as if it does not exist."
+ def _repr_html_(self):
+ return None
+
+ def _repr_latex_(self):
+ return None
+
+ def _repr_mimebundle_(self, **kwargs):
+ return None
+
+ def _repr_svg_(self):
+ return None
+
+ def _repr_png_(self):
+ return None
+
+ def _repr_jpeg_(self):
+ return None
+
+ def _repr_markdown_(self):
+ return None
+
+ def _repr_javascript_(self):
+ return None
+
+ def _repr_pdf_(self):
+ return None
+
+ def _repr_json_(self):
+ return None
+
def _normalize_store_arg(store, *, storage_options=None, mode="r", zarr_version=None):
if zarr_version is None:
| zarr-developers/zarr-python | 2534413e2f8b56d9c64744419628a464d639f1dc | diff --git a/zarr/tests/test_hierarchy.py b/zarr/tests/test_hierarchy.py
index 6c08d7b8..161e1eb8 100644
--- a/zarr/tests/test_hierarchy.py
+++ b/zarr/tests/test_hierarchy.py
@@ -1,4 +1,5 @@
import atexit
+import operator
import os
import sys
import pickle
@@ -87,6 +88,26 @@ class TestGroup(unittest.TestCase):
)
return g
+ def test_ipython_repr_methods(self):
+ g = self.create_group()
+ for method in [
+ "html",
+ "json",
+ "javascript",
+ "markdown",
+ "svg",
+ "png",
+ "jpeg",
+ "latex",
+ "pdf",
+ "mimebundle",
+ ]:
+ assert operator.methodcaller(f"_repr_{method}_")(g) is None
+ with pytest.raises(AttributeError):
+ g._ipython_display_()
+ with pytest.raises(AttributeError):
+ g._ipython_canary_method_should_not_exist_()
+
def test_group_init_1(self):
store, chunk_store = self.create_store()
g = self.create_group(store, chunk_store=chunk_store)
| Implement ipython repr methods on Group to prevent expensive lookups
### Zarr version
2.16.1
### Numcodecs version
...
### Python Version
...
### Operating System
...
### Installation
conda
### Description
`ipython` will look for 11 custom repr methods (https://ipython.readthedocs.io/en/stable/config/integrating.html#custom-methods) in a zarr group.
Zarr chooses to map any `hasattr` query to a `__getitem__` call so sach of these queries becomes a `__getitem__` call for (e.g.) `_repr_mimebundle_.array.json` and `_repr_mimebundle_.array.json` and is interleaved with a request for `_ipython_canary_method_should_not_exist_.[array|group].json`.
I count **44** useless requests for a simple `zarr.open_group`.
I think a good solution would be to implement `_ipython_display_` or `_repr_mimebundle_`.
It would also be nice to raise `AttributeError` for `_ipython_canary_method_should_not_exist_`.
xref https://github.com/jupyter/notebook/issues/2014
### Steps to reproduce
1. Create a zarr group
2. Open it with some way of recording __getitem__ requests.
### Additional output
_No response_ | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"zarr/tests/test_hierarchy.py::TestGroup::test_ipython_repr_methods",
"zarr/tests/test_hierarchy.py::TestGroupWithMemoryStore::test_ipython_repr_methods",
"zarr/tests/test_hierarchy.py::TestGroupWithDirectoryStore::test_ipython_repr_methods",
"zarr/tests/test_hierarchy.py::TestGroupWithNestedDirectoryStore::test_ipython_repr_methods",
"zarr/tests/test_hierarchy.py::TestGroupWithZipStore::test_ipython_repr_methods",
"zarr/tests/test_hierarchy.py::TestGroupWithDBMStore::test_ipython_repr_methods",
"zarr/tests/test_hierarchy.py::TestGroupWithSQLiteStore::test_ipython_repr_methods",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_ipython_repr_methods",
"zarr/tests/test_hierarchy.py::TestGroupWithStoreCache::test_ipython_repr_methods"
] | [
"zarr/tests/test_hierarchy.py::TestGroup::test_array_creation",
"zarr/tests/test_hierarchy.py::TestGroup::test_context_manager",
"zarr/tests/test_hierarchy.py::TestGroup::test_create_dataset",
"zarr/tests/test_hierarchy.py::TestGroup::test_create_errors",
"zarr/tests/test_hierarchy.py::TestGroup::test_create_group",
"zarr/tests/test_hierarchy.py::TestGroup::test_create_overwrite",
"zarr/tests/test_hierarchy.py::TestGroup::test_delitem",
"zarr/tests/test_hierarchy.py::TestGroup::test_double_counting_group_v3",
"zarr/tests/test_hierarchy.py::TestGroup::test_empty_getitem_contains_iterators",
"zarr/tests/test_hierarchy.py::TestGroup::test_getattr",
"zarr/tests/test_hierarchy.py::TestGroup::test_getitem_contains_iterators",
"zarr/tests/test_hierarchy.py::TestGroup::test_group_init_1",
"zarr/tests/test_hierarchy.py::TestGroup::test_group_init_2",
"zarr/tests/test_hierarchy.py::TestGroup::test_group_init_errors_1",
"zarr/tests/test_hierarchy.py::TestGroup::test_group_init_errors_2",
"zarr/tests/test_hierarchy.py::TestGroup::test_group_repr",
"zarr/tests/test_hierarchy.py::TestGroup::test_iterators_recurse",
"zarr/tests/test_hierarchy.py::TestGroup::test_move",
"zarr/tests/test_hierarchy.py::TestGroup::test_paths",
"zarr/tests/test_hierarchy.py::TestGroup::test_pickle",
"zarr/tests/test_hierarchy.py::TestGroup::test_require_dataset",
"zarr/tests/test_hierarchy.py::TestGroup::test_require_group",
"zarr/tests/test_hierarchy.py::TestGroup::test_rmdir_group_and_array_metadata_files",
"zarr/tests/test_hierarchy.py::TestGroup::test_setitem",
"zarr/tests/test_hierarchy.py::test_group_init_from_dict[False]",
"zarr/tests/test_hierarchy.py::test_group_init_from_dict[True]",
"zarr/tests/test_hierarchy.py::TestGroupWithMemoryStore::test_array_creation",
"zarr/tests/test_hierarchy.py::TestGroupWithMemoryStore::test_context_manager",
"zarr/tests/test_hierarchy.py::TestGroupWithMemoryStore::test_create_dataset",
"zarr/tests/test_hierarchy.py::TestGroupWithMemoryStore::test_create_errors",
"zarr/tests/test_hierarchy.py::TestGroupWithMemoryStore::test_create_group",
"zarr/tests/test_hierarchy.py::TestGroupWithMemoryStore::test_create_overwrite",
"zarr/tests/test_hierarchy.py::TestGroupWithMemoryStore::test_delitem",
"zarr/tests/test_hierarchy.py::TestGroupWithMemoryStore::test_double_counting_group_v3",
"zarr/tests/test_hierarchy.py::TestGroupWithMemoryStore::test_empty_getitem_contains_iterators",
"zarr/tests/test_hierarchy.py::TestGroupWithMemoryStore::test_getattr",
"zarr/tests/test_hierarchy.py::TestGroupWithMemoryStore::test_getitem_contains_iterators",
"zarr/tests/test_hierarchy.py::TestGroupWithMemoryStore::test_group_init_1",
"zarr/tests/test_hierarchy.py::TestGroupWithMemoryStore::test_group_init_2",
"zarr/tests/test_hierarchy.py::TestGroupWithMemoryStore::test_group_init_errors_1",
"zarr/tests/test_hierarchy.py::TestGroupWithMemoryStore::test_group_init_errors_2",
"zarr/tests/test_hierarchy.py::TestGroupWithMemoryStore::test_group_repr",
"zarr/tests/test_hierarchy.py::TestGroupWithMemoryStore::test_iterators_recurse",
"zarr/tests/test_hierarchy.py::TestGroupWithMemoryStore::test_move",
"zarr/tests/test_hierarchy.py::TestGroupWithMemoryStore::test_paths",
"zarr/tests/test_hierarchy.py::TestGroupWithMemoryStore::test_pickle",
"zarr/tests/test_hierarchy.py::TestGroupWithMemoryStore::test_require_dataset",
"zarr/tests/test_hierarchy.py::TestGroupWithMemoryStore::test_require_group",
"zarr/tests/test_hierarchy.py::TestGroupWithMemoryStore::test_rmdir_group_and_array_metadata_files",
"zarr/tests/test_hierarchy.py::TestGroupWithMemoryStore::test_setitem",
"zarr/tests/test_hierarchy.py::TestGroupWithDirectoryStore::test_array_creation",
"zarr/tests/test_hierarchy.py::TestGroupWithDirectoryStore::test_context_manager",
"zarr/tests/test_hierarchy.py::TestGroupWithDirectoryStore::test_create_dataset",
"zarr/tests/test_hierarchy.py::TestGroupWithDirectoryStore::test_create_errors",
"zarr/tests/test_hierarchy.py::TestGroupWithDirectoryStore::test_create_group",
"zarr/tests/test_hierarchy.py::TestGroupWithDirectoryStore::test_create_overwrite",
"zarr/tests/test_hierarchy.py::TestGroupWithDirectoryStore::test_delitem",
"zarr/tests/test_hierarchy.py::TestGroupWithDirectoryStore::test_double_counting_group_v3",
"zarr/tests/test_hierarchy.py::TestGroupWithDirectoryStore::test_empty_getitem_contains_iterators",
"zarr/tests/test_hierarchy.py::TestGroupWithDirectoryStore::test_getattr",
"zarr/tests/test_hierarchy.py::TestGroupWithDirectoryStore::test_getitem_contains_iterators",
"zarr/tests/test_hierarchy.py::TestGroupWithDirectoryStore::test_group_init_1",
"zarr/tests/test_hierarchy.py::TestGroupWithDirectoryStore::test_group_init_2",
"zarr/tests/test_hierarchy.py::TestGroupWithDirectoryStore::test_group_init_errors_1",
"zarr/tests/test_hierarchy.py::TestGroupWithDirectoryStore::test_group_init_errors_2",
"zarr/tests/test_hierarchy.py::TestGroupWithDirectoryStore::test_group_repr",
"zarr/tests/test_hierarchy.py::TestGroupWithDirectoryStore::test_iterators_recurse",
"zarr/tests/test_hierarchy.py::TestGroupWithDirectoryStore::test_move",
"zarr/tests/test_hierarchy.py::TestGroupWithDirectoryStore::test_paths",
"zarr/tests/test_hierarchy.py::TestGroupWithDirectoryStore::test_pickle",
"zarr/tests/test_hierarchy.py::TestGroupWithDirectoryStore::test_require_dataset",
"zarr/tests/test_hierarchy.py::TestGroupWithDirectoryStore::test_require_group",
"zarr/tests/test_hierarchy.py::TestGroupWithDirectoryStore::test_rmdir_group_and_array_metadata_files",
"zarr/tests/test_hierarchy.py::TestGroupWithDirectoryStore::test_setitem",
"zarr/tests/test_hierarchy.py::TestGroupWithNestedDirectoryStore::test_array_creation",
"zarr/tests/test_hierarchy.py::TestGroupWithNestedDirectoryStore::test_context_manager",
"zarr/tests/test_hierarchy.py::TestGroupWithNestedDirectoryStore::test_create_dataset",
"zarr/tests/test_hierarchy.py::TestGroupWithNestedDirectoryStore::test_create_errors",
"zarr/tests/test_hierarchy.py::TestGroupWithNestedDirectoryStore::test_create_group",
"zarr/tests/test_hierarchy.py::TestGroupWithNestedDirectoryStore::test_create_overwrite",
"zarr/tests/test_hierarchy.py::TestGroupWithNestedDirectoryStore::test_delitem",
"zarr/tests/test_hierarchy.py::TestGroupWithNestedDirectoryStore::test_double_counting_group_v3",
"zarr/tests/test_hierarchy.py::TestGroupWithNestedDirectoryStore::test_empty_getitem_contains_iterators",
"zarr/tests/test_hierarchy.py::TestGroupWithNestedDirectoryStore::test_getattr",
"zarr/tests/test_hierarchy.py::TestGroupWithNestedDirectoryStore::test_getitem_contains_iterators",
"zarr/tests/test_hierarchy.py::TestGroupWithNestedDirectoryStore::test_group_init_1",
"zarr/tests/test_hierarchy.py::TestGroupWithNestedDirectoryStore::test_group_init_2",
"zarr/tests/test_hierarchy.py::TestGroupWithNestedDirectoryStore::test_group_init_errors_1",
"zarr/tests/test_hierarchy.py::TestGroupWithNestedDirectoryStore::test_group_init_errors_2",
"zarr/tests/test_hierarchy.py::TestGroupWithNestedDirectoryStore::test_group_repr",
"zarr/tests/test_hierarchy.py::TestGroupWithNestedDirectoryStore::test_iterators_recurse",
"zarr/tests/test_hierarchy.py::TestGroupWithNestedDirectoryStore::test_move",
"zarr/tests/test_hierarchy.py::TestGroupWithNestedDirectoryStore::test_paths",
"zarr/tests/test_hierarchy.py::TestGroupWithNestedDirectoryStore::test_pickle",
"zarr/tests/test_hierarchy.py::TestGroupWithNestedDirectoryStore::test_require_dataset",
"zarr/tests/test_hierarchy.py::TestGroupWithNestedDirectoryStore::test_require_group",
"zarr/tests/test_hierarchy.py::TestGroupWithNestedDirectoryStore::test_rmdir_group_and_array_metadata_files",
"zarr/tests/test_hierarchy.py::TestGroupWithNestedDirectoryStore::test_setitem",
"zarr/tests/test_hierarchy.py::TestGroupWithZipStore::test_array_creation",
"zarr/tests/test_hierarchy.py::TestGroupWithZipStore::test_context_manager",
"zarr/tests/test_hierarchy.py::TestGroupWithZipStore::test_create_dataset",
"zarr/tests/test_hierarchy.py::TestGroupWithZipStore::test_create_errors",
"zarr/tests/test_hierarchy.py::TestGroupWithZipStore::test_create_group",
"zarr/tests/test_hierarchy.py::TestGroupWithZipStore::test_create_overwrite",
"zarr/tests/test_hierarchy.py::TestGroupWithZipStore::test_delitem",
"zarr/tests/test_hierarchy.py::TestGroupWithZipStore::test_double_counting_group_v3",
"zarr/tests/test_hierarchy.py::TestGroupWithZipStore::test_empty_getitem_contains_iterators",
"zarr/tests/test_hierarchy.py::TestGroupWithZipStore::test_getattr",
"zarr/tests/test_hierarchy.py::TestGroupWithZipStore::test_getitem_contains_iterators",
"zarr/tests/test_hierarchy.py::TestGroupWithZipStore::test_group_init_1",
"zarr/tests/test_hierarchy.py::TestGroupWithZipStore::test_group_init_2",
"zarr/tests/test_hierarchy.py::TestGroupWithZipStore::test_group_init_errors_1",
"zarr/tests/test_hierarchy.py::TestGroupWithZipStore::test_group_init_errors_2",
"zarr/tests/test_hierarchy.py::TestGroupWithZipStore::test_group_repr",
"zarr/tests/test_hierarchy.py::TestGroupWithZipStore::test_iterators_recurse",
"zarr/tests/test_hierarchy.py::TestGroupWithZipStore::test_move",
"zarr/tests/test_hierarchy.py::TestGroupWithZipStore::test_paths",
"zarr/tests/test_hierarchy.py::TestGroupWithZipStore::test_pickle",
"zarr/tests/test_hierarchy.py::TestGroupWithZipStore::test_require_dataset",
"zarr/tests/test_hierarchy.py::TestGroupWithZipStore::test_require_group",
"zarr/tests/test_hierarchy.py::TestGroupWithZipStore::test_rmdir_group_and_array_metadata_files",
"zarr/tests/test_hierarchy.py::TestGroupWithZipStore::test_setitem",
"zarr/tests/test_hierarchy.py::TestGroupWithDBMStore::test_array_creation",
"zarr/tests/test_hierarchy.py::TestGroupWithDBMStore::test_context_manager",
"zarr/tests/test_hierarchy.py::TestGroupWithDBMStore::test_create_dataset",
"zarr/tests/test_hierarchy.py::TestGroupWithDBMStore::test_create_errors",
"zarr/tests/test_hierarchy.py::TestGroupWithDBMStore::test_create_group",
"zarr/tests/test_hierarchy.py::TestGroupWithDBMStore::test_create_overwrite",
"zarr/tests/test_hierarchy.py::TestGroupWithDBMStore::test_delitem",
"zarr/tests/test_hierarchy.py::TestGroupWithDBMStore::test_double_counting_group_v3",
"zarr/tests/test_hierarchy.py::TestGroupWithDBMStore::test_empty_getitem_contains_iterators",
"zarr/tests/test_hierarchy.py::TestGroupWithDBMStore::test_getattr",
"zarr/tests/test_hierarchy.py::TestGroupWithDBMStore::test_getitem_contains_iterators",
"zarr/tests/test_hierarchy.py::TestGroupWithDBMStore::test_group_init_1",
"zarr/tests/test_hierarchy.py::TestGroupWithDBMStore::test_group_init_2",
"zarr/tests/test_hierarchy.py::TestGroupWithDBMStore::test_group_init_errors_1",
"zarr/tests/test_hierarchy.py::TestGroupWithDBMStore::test_group_init_errors_2",
"zarr/tests/test_hierarchy.py::TestGroupWithDBMStore::test_group_repr",
"zarr/tests/test_hierarchy.py::TestGroupWithDBMStore::test_iterators_recurse",
"zarr/tests/test_hierarchy.py::TestGroupWithDBMStore::test_move",
"zarr/tests/test_hierarchy.py::TestGroupWithDBMStore::test_paths",
"zarr/tests/test_hierarchy.py::TestGroupWithDBMStore::test_pickle",
"zarr/tests/test_hierarchy.py::TestGroupWithDBMStore::test_require_dataset",
"zarr/tests/test_hierarchy.py::TestGroupWithDBMStore::test_require_group",
"zarr/tests/test_hierarchy.py::TestGroupWithDBMStore::test_rmdir_group_and_array_metadata_files",
"zarr/tests/test_hierarchy.py::TestGroupWithDBMStore::test_setitem",
"zarr/tests/test_hierarchy.py::TestGroupWithSQLiteStore::test_array_creation",
"zarr/tests/test_hierarchy.py::TestGroupWithSQLiteStore::test_context_manager",
"zarr/tests/test_hierarchy.py::TestGroupWithSQLiteStore::test_create_dataset",
"zarr/tests/test_hierarchy.py::TestGroupWithSQLiteStore::test_create_errors",
"zarr/tests/test_hierarchy.py::TestGroupWithSQLiteStore::test_create_group",
"zarr/tests/test_hierarchy.py::TestGroupWithSQLiteStore::test_create_overwrite",
"zarr/tests/test_hierarchy.py::TestGroupWithSQLiteStore::test_delitem",
"zarr/tests/test_hierarchy.py::TestGroupWithSQLiteStore::test_double_counting_group_v3",
"zarr/tests/test_hierarchy.py::TestGroupWithSQLiteStore::test_empty_getitem_contains_iterators",
"zarr/tests/test_hierarchy.py::TestGroupWithSQLiteStore::test_getattr",
"zarr/tests/test_hierarchy.py::TestGroupWithSQLiteStore::test_getitem_contains_iterators",
"zarr/tests/test_hierarchy.py::TestGroupWithSQLiteStore::test_group_init_1",
"zarr/tests/test_hierarchy.py::TestGroupWithSQLiteStore::test_group_init_2",
"zarr/tests/test_hierarchy.py::TestGroupWithSQLiteStore::test_group_init_errors_1",
"zarr/tests/test_hierarchy.py::TestGroupWithSQLiteStore::test_group_init_errors_2",
"zarr/tests/test_hierarchy.py::TestGroupWithSQLiteStore::test_group_repr",
"zarr/tests/test_hierarchy.py::TestGroupWithSQLiteStore::test_iterators_recurse",
"zarr/tests/test_hierarchy.py::TestGroupWithSQLiteStore::test_move",
"zarr/tests/test_hierarchy.py::TestGroupWithSQLiteStore::test_paths",
"zarr/tests/test_hierarchy.py::TestGroupWithSQLiteStore::test_pickle",
"zarr/tests/test_hierarchy.py::TestGroupWithSQLiteStore::test_require_dataset",
"zarr/tests/test_hierarchy.py::TestGroupWithSQLiteStore::test_require_group",
"zarr/tests/test_hierarchy.py::TestGroupWithSQLiteStore::test_rmdir_group_and_array_metadata_files",
"zarr/tests/test_hierarchy.py::TestGroupWithSQLiteStore::test_setitem",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_array_creation",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_chunk_store",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_context_manager",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_create_dataset",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_create_errors",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_create_group",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_create_overwrite",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_delitem",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_double_counting_group_v3",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_empty_getitem_contains_iterators",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_getattr",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_getitem_contains_iterators",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_group_init_1",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_group_init_2",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_group_init_errors_1",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_group_init_errors_2",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_group_repr",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_iterators_recurse",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_move",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_paths",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_pickle",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_require_dataset",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_require_group",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_rmdir_group_and_array_metadata_files",
"zarr/tests/test_hierarchy.py::TestGroupWithChunkStore::test_setitem",
"zarr/tests/test_hierarchy.py::TestGroupWithStoreCache::test_array_creation",
"zarr/tests/test_hierarchy.py::TestGroupWithStoreCache::test_context_manager",
"zarr/tests/test_hierarchy.py::TestGroupWithStoreCache::test_create_dataset",
"zarr/tests/test_hierarchy.py::TestGroupWithStoreCache::test_create_errors",
"zarr/tests/test_hierarchy.py::TestGroupWithStoreCache::test_create_group",
"zarr/tests/test_hierarchy.py::TestGroupWithStoreCache::test_create_overwrite",
"zarr/tests/test_hierarchy.py::TestGroupWithStoreCache::test_delitem",
"zarr/tests/test_hierarchy.py::TestGroupWithStoreCache::test_double_counting_group_v3",
"zarr/tests/test_hierarchy.py::TestGroupWithStoreCache::test_empty_getitem_contains_iterators",
"zarr/tests/test_hierarchy.py::TestGroupWithStoreCache::test_getattr",
"zarr/tests/test_hierarchy.py::TestGroupWithStoreCache::test_getitem_contains_iterators",
"zarr/tests/test_hierarchy.py::TestGroupWithStoreCache::test_group_init_1",
"zarr/tests/test_hierarchy.py::TestGroupWithStoreCache::test_group_init_2",
"zarr/tests/test_hierarchy.py::TestGroupWithStoreCache::test_group_init_errors_1",
"zarr/tests/test_hierarchy.py::TestGroupWithStoreCache::test_group_init_errors_2",
"zarr/tests/test_hierarchy.py::TestGroupWithStoreCache::test_group_repr",
"zarr/tests/test_hierarchy.py::TestGroupWithStoreCache::test_iterators_recurse",
"zarr/tests/test_hierarchy.py::TestGroupWithStoreCache::test_move",
"zarr/tests/test_hierarchy.py::TestGroupWithStoreCache::test_paths",
"zarr/tests/test_hierarchy.py::TestGroupWithStoreCache::test_pickle",
"zarr/tests/test_hierarchy.py::TestGroupWithStoreCache::test_require_dataset",
"zarr/tests/test_hierarchy.py::TestGroupWithStoreCache::test_require_group",
"zarr/tests/test_hierarchy.py::TestGroupWithStoreCache::test_rmdir_group_and_array_metadata_files",
"zarr/tests/test_hierarchy.py::TestGroupWithStoreCache::test_setitem",
"zarr/tests/test_hierarchy.py::test_group[2]",
"zarr/tests/test_hierarchy.py::test_open_group[2]",
"zarr/tests/test_hierarchy.py::test_group_completions[2]",
"zarr/tests/test_hierarchy.py::test_group_key_completions[2]",
"zarr/tests/test_hierarchy.py::test_tree[False-2]",
"zarr/tests/test_hierarchy.py::test_tree[True-2]",
"zarr/tests/test_hierarchy.py::test_open_group_from_paths[2]"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2024-03-26T16:02:58Z" | mit |
|
zheller__flake8-quotes-46 | diff --git a/.travis.yml b/.travis.yml
index 11c9ca2..d22e40b 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -13,7 +13,7 @@ install:
- pip install -r requirements-dev.txt
# If we are testing Flake8 3.x, then install it
- - if test "$FLAKE8_VERSION" = "3"; then pip install flake8==3.0.0b2; fi
+ - if test "$FLAKE8_VERSION" = "3"; then pip install flake8==3; fi
# Install `flake8-quotes`
- python setup.py develop
diff --git a/flake8_quotes/__init__.py b/flake8_quotes/__init__.py
index a3806c3..3631c21 100644
--- a/flake8_quotes/__init__.py
+++ b/flake8_quotes/__init__.py
@@ -2,7 +2,17 @@ import optparse
import tokenize
import warnings
-from flake8.engine import pep8
+# Polyfill stdin loading/reading lines
+# https://gitlab.com/pycqa/flake8-polyfill/blob/1.0.1/src/flake8_polyfill/stdin.py#L52-57
+try:
+ from flake8.engine import pep8
+ stdin_get_value = pep8.stdin_get_value
+ readlines = pep8.readlines
+except ImportError:
+ from flake8 import utils
+ import pycodestyle
+ stdin_get_value = utils.stdin_get_value
+ readlines = pycodestyle.readlines
from flake8_quotes.__about__ import __version__
@@ -74,9 +84,9 @@ class QuoteChecker(object):
def get_file_contents(self):
if self.filename in ('stdin', '-', None):
- return pep8.stdin_get_value().splitlines(True)
+ return stdin_get_value().splitlines(True)
else:
- return pep8.readlines(self.filename)
+ return readlines(self.filename)
def run(self):
file_contents = self.get_file_contents()
| zheller/flake8-quotes | 2cde3ba5170edcd35c3de5ac0d4d8827f568e3db | diff --git a/test/test_checks.py b/test/test_checks.py
index f242f16..0cb1574 100644
--- a/test/test_checks.py
+++ b/test/test_checks.py
@@ -1,18 +1,7 @@
from flake8_quotes import QuoteChecker
import os
import subprocess
-from unittest import expectedFailure, TestCase
-
-
-FLAKE8_VERSION = os.environ.get('FLAKE8_VERSION', '2')
-
-
-def expectedFailureIf(condition):
- """Only expect failure if condition applies."""
- if condition:
- return expectedFailure
- else:
- return lambda func: func
+from unittest import TestCase
class TestChecks(TestCase):
@@ -22,7 +11,6 @@ class TestChecks(TestCase):
class TestFlake8Stdin(TestCase):
- @expectedFailureIf(FLAKE8_VERSION == '3')
def test_stdin(self):
"""Test using stdin."""
filepath = get_absolute_path('data/doubles.py')
@@ -33,11 +21,10 @@ class TestFlake8Stdin(TestCase):
stdout_lines = stdout.splitlines()
self.assertEqual(stderr, b'')
- self.assertEqual(stdout_lines, [
- b'stdin:1:25: Q000 Remove bad quotes.',
- b'stdin:2:25: Q000 Remove bad quotes.',
- b'stdin:3:25: Q000 Remove bad quotes.',
- ])
+ self.assertEqual(len(stdout_lines), 3)
+ self.assertRegexpMatches(stdout_lines[0], b'stdin:1:(24|25): Q000 Remove bad quotes.')
+ self.assertRegexpMatches(stdout_lines[1], b'stdin:2:(24|25): Q000 Remove bad quotes.')
+ self.assertRegexpMatches(stdout_lines[2], b'stdin:3:(24|25): Q000 Remove bad quotes.')
class DoublesTestChecks(TestCase):
| Incompatible with flake8 version 3
There is a beta version of flake8 version 3, which doesn't use `config_options` anymore so I get the following error:
```
Traceback (most recent call last):
File "/home/xzise/.pyenv/versions/3.5.1/bin/flake8", line 11, in <module>
sys.exit(main())
File "/home/xzise/.pyenv/versions/3.5.1/lib/python3.5/site-packages/flake8/main/cli.py", line 16, in main
app.run(argv)
File "/home/xzise/.pyenv/versions/3.5.1/lib/python3.5/site-packages/flake8/main/application.py", line 293, in run
self._run(argv)
File "/home/xzise/.pyenv/versions/3.5.1/lib/python3.5/site-packages/flake8/main/application.py", line 279, in _run
self.initialize(argv)
File "/home/xzise/.pyenv/versions/3.5.1/lib/python3.5/site-packages/flake8/main/application.py", line 270, in initialize
self.register_plugin_options()
File "/home/xzise/.pyenv/versions/3.5.1/lib/python3.5/site-packages/flake8/main/application.py", line 150, in register_plugin_options
self.check_plugins.register_options(self.option_manager)
File "/home/xzise/.pyenv/versions/3.5.1/lib/python3.5/site-packages/flake8/plugins/manager.py", line 451, in register_options
list(self.manager.map(register_and_enable))
File "/home/xzise/.pyenv/versions/3.5.1/lib/python3.5/site-packages/flake8/plugins/manager.py", line 261, in map
yield func(self.plugins[name], *args, **kwargs)
File "/home/xzise/.pyenv/versions/3.5.1/lib/python3.5/site-packages/flake8/plugins/manager.py", line 447, in register_and_enable
call_register_options(plugin)
File "/home/xzise/.pyenv/versions/3.5.1/lib/python3.5/site-packages/flake8/plugins/manager.py", line 357, in generated_function
return method(optmanager, *args, **kwargs)
File "/home/xzise/.pyenv/versions/3.5.1/lib/python3.5/site-packages/flake8/plugins/manager.py", line 207, in register_options
add_options(optmanager)
File "/home/xzise/.pyenv/versions/3.5.1/lib/python3.5/site-packages/flake8_quotes/__init__.py", line 38, in add_options
parser.config_options.extend(['quotes', 'inline-quotes'])
```
More information:
* [List of plugins broken by 3.0.0](https://gitlab.com/pycqa/flake8/issues/149)
* [Guide to handle both versions](http://flake8.pycqa.org/en/latest/plugin-development/cross-compatibility.html#option-handling-on-flake8-2-and-3) | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"test/test_checks.py::TestChecks::test_get_noqa_lines",
"test/test_checks.py::DoublesTestChecks::test_doubles",
"test/test_checks.py::DoublesTestChecks::test_multiline_string",
"test/test_checks.py::DoublesTestChecks::test_noqa_doubles",
"test/test_checks.py::DoublesTestChecks::test_wrapped",
"test/test_checks.py::SinglesTestChecks::test_multiline_string",
"test/test_checks.py::SinglesTestChecks::test_noqa_singles",
"test/test_checks.py::SinglesTestChecks::test_singles",
"test/test_checks.py::SinglesTestChecks::test_wrapped"
] | [] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2016-07-26T16:19:35Z" | mit |
|
zhmcclient__python-zhmcclient-142 | diff --git a/zhmcclient/_manager.py b/zhmcclient/_manager.py
index e3d95aa..06e0c28 100644
--- a/zhmcclient/_manager.py
+++ b/zhmcclient/_manager.py
@@ -198,8 +198,11 @@ class BaseManager(object):
"""
found = list()
if list(kwargs.keys()) == ['name']:
- obj = self.find_by_name(kwargs['name'])
- found.append(obj)
+ try:
+ obj = self.find_by_name(kwargs['name'])
+ found.append(obj)
+ except NotFound:
+ pass
else:
searches = kwargs.items()
listing = self.list()
| zhmcclient/python-zhmcclient | ca4b1e678e3568e3c95143ba8544d2982e6ac40b | diff --git a/tests/unit/test_manager.py b/tests/unit/test_manager.py
new file mode 100644
index 0000000..85f77d9
--- /dev/null
+++ b/tests/unit/test_manager.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python
+# Copyright 2016 IBM Corp. All Rights Reserved.
+#
+# 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 tests for _manager module.
+"""
+
+from __future__ import absolute_import, print_function
+
+import unittest
+
+from zhmcclient._manager import BaseManager
+from zhmcclient._resource import BaseResource
+
+
+class MyResource(BaseResource):
+ def __init__(self, manager, uri, name=None, properties=None):
+ super(MyResource, self).__init__(manager, uri, name, properties,
+ uri_prop='object-uri',
+ name_prop='name')
+
+
+class MyManager(BaseManager):
+ def __init__(self):
+ super(MyManager, self).__init__(MyResource)
+ self._items = []
+
+ def list(self):
+ return self._items
+
+
+class ManagerTests(unittest.TestCase):
+ def setUp(self):
+ self.manager = MyManager()
+
+ self.resource = MyResource(self.manager, "foo-uri",
+ properties={"name": "foo-name",
+ "other": "foo-other"})
+ self.manager._items = [self.resource]
+
+ def test_findall_attribute(self):
+ items = self.manager.findall(other="foo-other")
+ self.assertIn(self.resource, items)
+
+ def test_findall_attribute_no_result(self):
+ items = self.manager.findall(other="not-exists")
+ self.assertEqual([], items)
+
+ def test_findall_name(self):
+ items = self.manager.findall(name="foo-name")
+ self.assertEqual(1, len(items))
+ item = items[0]
+ self.assertEqual("foo-name", item.properties['name'])
+ self.assertEqual("foo-uri", item.properties['object-uri'])
+
+ def test_findall_name_no_result(self):
+ items = self.manager.findall(name="not-exists")
+ self.assertEqual([], items)
| Regression: findall() raises NotFound Error when searching by name and nothing was found
### Actual behavior
_manager.findall(name=foo) raises NotFound exception when nothing was found
### Expected behavior
Empty list returned
### Execution environment
* zhmcclient version: 0.8.0 + master
* Operating system (type+version): ubuntu14
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/unit/test_manager.py::ManagerTests::test_findall_name_no_result"
] | [
"tests/unit/test_manager.py::ManagerTests::test_findall_attribute",
"tests/unit/test_manager.py::ManagerTests::test_findall_attribute_no_result",
"tests/unit/test_manager.py::ManagerTests::test_findall_name"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2017-01-10T15:47:38Z" | apache-2.0 |
|
zimeon__ocfl-py-54 | diff --git a/ocfl/data/validation-errors.json b/ocfl/data/validation-errors.json
index 1f53481..b3b07ff 100644
--- a/ocfl/data/validation-errors.json
+++ b/ocfl/data/validation-errors.json
@@ -86,9 +86,16 @@
"en": "OCFL Object version directory %s includes an illegal file (%s)"
}
},
+ "E017": {
+ "params": ["where"],
+ "description": {
+ "en": "OCFL Object %s inventory contentDirectory must be a string and must not contain a forward slash (/)"
+ }
+ },
"E018": {
+ "params": ["where"],
"description": {
- "en": "Content directory must not contain a forward slash (/) or be . or .."
+ "en": "OCFL Object %s inventory contentDirectory must not be either . or .."
}
},
"E023": {
diff --git a/ocfl/inventory_validator.py b/ocfl/inventory_validator.py
index 44a15b4..021798b 100644
--- a/ocfl/inventory_validator.py
+++ b/ocfl/inventory_validator.py
@@ -79,7 +79,9 @@ class InventoryValidator():
if 'contentDirectory' in inventory:
# Careful only to set self.content_directory if value is safe
cd = inventory['contentDirectory']
- if not isinstance(cd, str) or '/' in cd or cd in ['.', '..']:
+ if not isinstance(cd, str) or '/' in cd:
+ self.error("E017")
+ elif cd in ('.', '..'):
self.error("E018")
else:
self.content_directory = cd
| zimeon/ocfl-py | 2c11ca2c8df09bd33eb18f4fc3de1b879826526b | diff --git a/tests/test_inventory_validator.py b/tests/test_inventory_validator.py
index bc87693..1551ca1 100644
--- a/tests/test_inventory_validator.py
+++ b/tests/test_inventory_validator.py
@@ -66,7 +66,10 @@ class TestAll(unittest.TestCase):
iv = InventoryValidator(log=log)
log.clear()
iv.validate({"id": "like:uri", "contentDirectory": "not/allowed"})
- self.assertIn('E018', log.errors)
+ self.assertIn('E017', log.errors)
+ log.clear()
+ iv.validate({"id": "like:uri", "contentDirectory": ["s"]})
+ self.assertIn('E017', log.errors)
log.clear()
iv.validate({"id": "like:uri", "contentDirectory": ".."})
self.assertIn('E018', log.errors)
| Fix validation error for forward slash in `contentDirectory`
From https://github.com/OCFL/fixtures/pull/82 the error for this should be `E017` instead of `E018` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_inventory_validator.py::TestAll::test_validate"
] | [
"tests/test_inventory_validator.py::TestAll::test_check_content_path",
"tests/test_inventory_validator.py::TestAll::test_check_digests_present_and_used",
"tests/test_inventory_validator.py::TestAll::test_check_logical_path",
"tests/test_inventory_validator.py::TestAll::test_digest_regex",
"tests/test_inventory_validator.py::TestAll::test_init",
"tests/test_inventory_validator.py::TestAll::test_validate_as_prior_version",
"tests/test_inventory_validator.py::TestAll::test_validate_fixity",
"tests/test_inventory_validator.py::TestAll::test_validate_manifest",
"tests/test_inventory_validator.py::TestAll::test_validate_state_block",
"tests/test_inventory_validator.py::TestAll::test_validate_version_sequence",
"tests/test_inventory_validator.py::TestAll::test_validate_versions"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2021-04-20T14:39:28Z" | mit |
|
zimeon__ocfl-py-60 | diff --git a/ocfl/data/validation-errors.json b/ocfl/data/validation-errors.json
index 56eed29..64f9dbf 100644
--- a/ocfl/data/validation-errors.json
+++ b/ocfl/data/validation-errors.json
@@ -513,7 +513,13 @@
"en": "OCFL Object %s inventory manifest content path %s must not begin or end with /."
}
},
- "E101": {
+ "E101a": {
+ "params": ["where", "path"],
+ "description": {
+ "en": "OCFL Object %s inventory manifest content path %s is repeated."
+ }
+ },
+ "E101b": {
"params": ["where", "path"],
"description": {
"en": "OCFL Object %s inventory manifest content path %s used as both a directory and a file path."
diff --git a/ocfl/inventory_validator.py b/ocfl/inventory_validator.py
index 4a918b5..83a0f6e 100644
--- a/ocfl/inventory_validator.py
+++ b/ocfl/inventory_validator.py
@@ -157,7 +157,7 @@ class InventoryValidator():
# Check for conflicting content paths
for path in content_directories:
if path in content_paths:
- self.error("E101", path=path)
+ self.error("E101b", path=path)
return manifest_files, manifest_files_correct_format, unnormalized_digests
def validate_fixity(self, fixity, manifest_files):
@@ -417,7 +417,10 @@ class InventoryValidator():
if element in ('', '.', '..'):
self.error("E099", path=path)
return False
- # Accumulate paths and directories
+ # Accumulate paths and directories if not seen before
+ if path in content_paths:
+ self.error("E101a", path=path)
+ return False
content_paths.add(path)
content_directories.add('/'.join([m.group(1)] + elements[0:-1]))
return True
| zimeon/ocfl-py | b7ae64de3cc9388bb8b7b606e50aae05cde3c412 | diff --git a/tests/test_inventory_validator.py b/tests/test_inventory_validator.py
index 5db1512..af61b9d 100644
--- a/tests/test_inventory_validator.py
+++ b/tests/test_inventory_validator.py
@@ -101,7 +101,7 @@ class TestAll(unittest.TestCase):
log.clear()
# Conflicting content paths
iv.validate_manifest({"067eca3f5b024afa00aeac03a3c42dc0042bf43cba56104037abea8b365c0cf672f0e0c14c91b82bbce6b1464e231ac285d630a82cd4d4a7b194bea04d4b2eb7": ['v1/content/a', 'v1/content/a/b']})
- self.assertEqual(log.errors, ['E101'])
+ self.assertEqual(log.errors, ['E101b'])
def test_validate_fixity(self):
"""Test validate_fixity method."""
@@ -373,6 +373,9 @@ class TestAll(unittest.TestCase):
log.clear()
self.assertFalse(iv.check_content_path('v1/xyz/.', cp, cd))
self.assertEqual(log.errors, ['E099'])
+ log.clear()
+ self.assertFalse(iv.check_content_path('v1/xyz/anything', cp, cd))
+ self.assertEqual(log.errors, ['E101a'])
# Good cases
log.clear()
self.assertTrue(iv.check_content_path('v1/xyz/.secret/d', cp, cd))
| Correctly handle validation with multiple entries for a given digest in `manifest`
See error case https://github.com/OCFL/fixtures/pull/78 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_inventory_validator.py::TestAll::test_check_content_path",
"tests/test_inventory_validator.py::TestAll::test_validate_manifest"
] | [
"tests/test_inventory_validator.py::TestAll::test_bad_inventory_files",
"tests/test_inventory_validator.py::TestAll::test_check_digests_present_and_used",
"tests/test_inventory_validator.py::TestAll::test_check_logical_path",
"tests/test_inventory_validator.py::TestAll::test_digest_regex",
"tests/test_inventory_validator.py::TestAll::test_init",
"tests/test_inventory_validator.py::TestAll::test_validate",
"tests/test_inventory_validator.py::TestAll::test_validate_as_prior_version",
"tests/test_inventory_validator.py::TestAll::test_validate_fixity",
"tests/test_inventory_validator.py::TestAll::test_validate_state_block",
"tests/test_inventory_validator.py::TestAll::test_validate_version_sequence",
"tests/test_inventory_validator.py::TestAll::test_validate_versions"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2021-04-21T22:24:12Z" | mit |
|
zimeon__ocfl-py-66 | diff --git a/fixtures b/fixtures
index db7d333..9a9d868 160000
--- a/fixtures
+++ b/fixtures
@@ -1,1 +1,1 @@
-Subproject commit db7d3338fef71be3328510d32d768a2746eb0e1f
+Subproject commit 9a9d86802f853de56a4b7925adcceccabee390ee
diff --git a/ocfl/data/validation-errors.json b/ocfl/data/validation-errors.json
index 210f963..05c85ac 100644
--- a/ocfl/data/validation-errors.json
+++ b/ocfl/data/validation-errors.json
@@ -158,12 +158,18 @@
"en": "OCFL Object %s inventory missing `head` attribute"
}
},
- "E037": {
+ "E037a": {
"params": ["where"],
"description": {
"en": "OCFL Object %s inventory `id` attribute is empty or badly formed"
}
},
+ "E037b": {
+ "params": ["where", "version_id", "root_id"],
+ "description": {
+ "en": "OCFL Object %s inventory id `%s` does not match the value in the root inventory `%s`"
+ }
+ },
"E038": {
"params": ["where"],
"description": {
diff --git a/ocfl/inventory_validator.py b/ocfl/inventory_validator.py
index 4453b22..0eb08ab 100644
--- a/ocfl/inventory_validator.py
+++ b/ocfl/inventory_validator.py
@@ -32,6 +32,7 @@ class InventoryValidator():
self.where = where
# Object state
self.inventory = None
+ self.id = None
self.digest_algorithm = 'sha512'
self.content_directory = 'content'
self.all_versions = []
@@ -56,9 +57,11 @@ class InventoryValidator():
if 'id' in inventory:
iid = inventory['id']
if not isinstance(iid, str) or iid == '':
- self.error("E037")
- elif not re.match(r'''(\w+):.+''', iid):
- self.warning("W005", id=iid)
+ self.error("E037a")
+ else:
+ if not re.match(r'''(\w+):.+''', iid):
+ self.warning("W005", id=iid)
+ self.id = iid
else:
self.error("E036a")
if 'type' not in inventory:
diff --git a/ocfl/validator.py b/ocfl/validator.py
index 211fcfe..5360e93 100644
--- a/ocfl/validator.py
+++ b/ocfl/validator.py
@@ -40,6 +40,7 @@ class Validator():
'0005-mutable-head'
]
# The following actually initialized in initialize() method
+ self.id = None
self.digest_algorithm = None
self.content_directory = None
self.inventory_digest_files = None
@@ -52,6 +53,7 @@ class Validator():
Must be called between attempts to validate objects.
"""
+ self.id = None
self.digest_algorithm = 'sha512'
self.content_directory = 'content'
self.inventory_digest_files = {} # index by version_dir, algorithms may differ
@@ -95,6 +97,7 @@ class Validator():
inventory_is_valid = self.log.num_errors == 0
self.root_inv_validator = inv_validator
all_versions = inv_validator.all_versions
+ self.id = inv_validator.id
self.content_directory = inv_validator.content_directory
self.digest_algorithm = inv_validator.digest_algorithm
self.validate_inventory_digest(inv_file, self.digest_algorithm)
@@ -225,6 +228,9 @@ class Validator():
digest_algorithm = inv_validator.digest_algorithm
self.validate_inventory_digest(inv_file, digest_algorithm, where=version_dir)
self.inventory_digest_files[version_dir] = 'inventory.json.' + digest_algorithm
+ if self.id and 'id' in version_inventory:
+ if version_inventory['id'] != self.id:
+ self.log.error('E037b', where=version_dir, root_id=self.id, version_id=version_inventory['id'])
if 'manifest' in version_inventory:
# Check that all files listed in prior inventories are in manifest
not_seen = set(prior_manifest_digests.keys())
| zimeon/ocfl-py | e5db6c0099d125bc46f1aa01366b94b5d244afe9 | diff --git a/tests/test_inventory_validator.py b/tests/test_inventory_validator.py
index af61b9d..1d2a387 100644
--- a/tests/test_inventory_validator.py
+++ b/tests/test_inventory_validator.py
@@ -50,7 +50,7 @@ class TestAll(unittest.TestCase):
self.assertIn('E041b', log.errors)
log.clear()
iv.validate({"id": []})
- self.assertIn('E037', log.errors)
+ self.assertIn('E037a', log.errors)
log.clear()
iv.validate({"id": "not_a_uri", "digestAlgorithm": "sha256"})
self.assertIn('W005', log.warns)
diff --git a/tests/test_validator.py b/tests/test_validator.py
index 14ac8d4..3ab6ffb 100644
--- a/tests/test_validator.py
+++ b/tests/test_validator.py
@@ -40,6 +40,7 @@ class TestAll(unittest.TestCase):
'E033_inventory_bad_json': ['E033'],
'E036_no_id': ['E036a'],
'E036_no_head': ['E036d'],
+ 'E037_inconsistent_id': ['E037b'],
'E040_head_not_most_recent': ['E040'],
'E040_wrong_head_doesnt_exist': ['E040'],
'E040_wrong_head_format': ['E040'],
| Catch inconsistent id error
See https://github.com/OCFL/fixtures/pull/87 in which the `id` in `v1` does not match the `id` in the root/`v2` inventory.
My validator fails to report this error:
```
(py38) simeon@RottenApple fixtures> ../ocfl-validate.py 1.0/bad-objects/E037_inconsistent_id
INFO:ocfl.object:OCFL object at 1.0/bad-objects/E037_inconsistent_id is VALID
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_inventory_validator.py::TestAll::test_validate"
] | [
"tests/test_inventory_validator.py::TestAll::test_bad_inventory_files",
"tests/test_inventory_validator.py::TestAll::test_check_content_path",
"tests/test_inventory_validator.py::TestAll::test_check_digests_present_and_used",
"tests/test_inventory_validator.py::TestAll::test_check_logical_path",
"tests/test_inventory_validator.py::TestAll::test_digest_regex",
"tests/test_inventory_validator.py::TestAll::test_init",
"tests/test_inventory_validator.py::TestAll::test_validate_as_prior_version",
"tests/test_inventory_validator.py::TestAll::test_validate_fixity",
"tests/test_inventory_validator.py::TestAll::test_validate_manifest",
"tests/test_inventory_validator.py::TestAll::test_validate_state_block",
"tests/test_inventory_validator.py::TestAll::test_validate_version_sequence",
"tests/test_inventory_validator.py::TestAll::test_validate_versions"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-04-26T12:08:42Z" | mit |
|
zimeon__ocfl-py-72 | diff --git a/ocfl/data/validation-errors.json b/ocfl/data/validation-errors.json
index 2c6f570..28f5fea 100644
--- a/ocfl/data/validation-errors.json
+++ b/ocfl/data/validation-errors.json
@@ -415,17 +415,29 @@
}
},
"E066b": {
- "params": ["version_dir" , "prior_head", "where"],
+ "params": ["version" , "prior_head", "where"],
"description": {
"en": "OCFL Object inventory manifest for %s in %s doesn't have a subset of manifest entries of inventory for %s"
}
},
"E066c": {
- "params": ["prior_head", "version_dir", "file", "prior_content", "where", "current_content"],
+ "params": ["prior_head", "version", "file", "prior_content", "where", "current_content"],
"description": {
"en": "OCFL Object %s inventory %s version state has file %s that maps to different content files (%s) than in the %s inventory (%s)"
}
},
+ "E066d": {
+ "params": ["where", "version", "digest", "logical_files", "prior_head"],
+ "description": {
+ "en": "OCFL Object %s inventory %s version state has digest %s (mapping to logical files %s) that does not appear in the %s inventory"
+ }
+ },
+ "E066e": {
+ "params": ["prior_head", "version", "digest", "logical_files", "where"],
+ "description": {
+ "en": "OCFL Object %s inventory %s version state has digest %s (mapping to logical files %s) that does not appear in the %s inventory"
+ }
+ },
"E067": {
"params": ["entry"],
"description": {
@@ -614,7 +626,7 @@
"spec": "In addition to the inventory in the OCFL Object Root, every version directory SHOULD include an inventory file that is an Inventory of all content for versions up to and including that particular version"
},
"W011": {
- "params": ["key", "version_dir" , "prior_head", "where"],
+ "params": ["key", "version" , "prior_head", "where"],
"description": {
"en": "OCFL Object version metadata '%s' for %s in %s inventory does not match that in %s inventory"
},
diff --git a/ocfl/inventory_validator.py b/ocfl/inventory_validator.py
index 0eb08ab..2dbe328 100644
--- a/ocfl/inventory_validator.py
+++ b/ocfl/inventory_validator.py
@@ -10,9 +10,15 @@ from .validation_logger import ValidationLogger
from .w3c_datetime import str_to_datetime
-def get_file_map(inventory, version_dir):
- """Get a map of files in state to files on disk for version_dir in inventory."""
- state = inventory['versions'][version_dir]['state']
+def get_file_map(inventory, version):
+ """Get a map of files in state to files on disk for version in inventory.
+
+ Returns a dictionary: file_in_state -> set(content_files)
+
+ The set of content_files may includes references to duplicate files in
+ later versions than the version being described.
+ """
+ state = inventory['versions'][version]['state']
manifest = inventory['manifest']
file_map = {}
for digest in state:
@@ -432,9 +438,11 @@ class InventoryValidator():
return True
def validate_as_prior_version(self, prior):
- """Check that prior is a valid InventoryValidator for a prior version of the current inventory object.
+ """Check that prior is a valid prior version of the current inventory object.
- Both inventories are assumed to have been checked for internal consistency.
+ The input prior is also expected to be an InventoryValidator object and
+ both self and prior inventories are assumed to have been checked for
+ internal consistency.
"""
# Must have a subset of versions which also check zero padding format etc.
if not set(prior.all_versions) < set(self.all_versions):
@@ -442,22 +450,53 @@ class InventoryValidator():
else:
# Check references to files but realize that there might be different
# digest algorithms between versions
- version_dir = 'no-version'
- for version_dir in prior.all_versions:
- prior_map = get_file_map(prior.inventory, version_dir)
- self_map = get_file_map(self.inventory, version_dir)
+ version = 'no-version'
+ for version in prior.all_versions:
+ # If the digest algorithm is the same then we can make a
+ # direct check on whether the state blocks match
+ if prior.digest_algorithm == self.digest_algorithm:
+ self.compare_states_for_version(prior, version)
+ # Now check the mappings from state to content files which must
+ # be consistent even if the digestAlgorithm is different between
+ # versions
+ prior_map = get_file_map(prior.inventory, version)
+ self_map = get_file_map(self.inventory, version)
if prior_map.keys() != self_map.keys():
- self.error('E066b', version_dir=version_dir, prior_head=prior.head)
+ self.error('E066b', version=version, prior_head=prior.head)
else:
# Check them all...
for file in prior_map:
if not prior_map[file].issubset(self_map[file]):
- self.error('E066c', version_dir=version_dir, prior_head=prior.head,
+ self.error('E066c', version=version, prior_head=prior.head,
file=file, prior_content=','.join(prior_map[file]),
current_content=','.join(self_map[file]))
- # Check metadata
- prior_version = prior.inventory['versions'][version_dir]
- self_version = self.inventory['versions'][version_dir]
- for key in ('created', 'message', 'user'):
- if prior_version.get(key) != self_version.get(key):
- self.warning('W011', version_dir=version_dir, prior_head=prior.head, key=key)
+ # Check metadata
+ prior_version = prior.inventory['versions'][version]
+ self_version = self.inventory['versions'][version]
+ for key in ('created', 'message', 'user'):
+ if prior_version.get(key) != self_version.get(key):
+ self.warning('W011', version=version, prior_head=prior.head, key=key)
+
+ def compare_states_for_version(self, prior, version):
+ """Compare state blocks for version between self and prior.
+
+ The digest algorithm must be the same in both, do not call otherwise!
+ Looks only for digests that appear in one but not in the other, the code
+ in validate_as_prior_version(..) does a check for whether the same sets
+ of logical files appear and we don't want to duplicate an error message
+ about that.
+
+ While the mapping checks in validate_as_prior_version(..) do all that is
+ necessary to detect an error, the additional errors that may be generated
+ here provide more detailed diagnostics in the case that the digest
+ algorithm is the same across versions being compared.
+ """
+ self_state = self.inventory['versions'][version]['state']
+ prior_state = prior.inventory['versions'][version]['state']
+ for digest in set(self_state.keys()).union(prior_state.keys()):
+ if digest not in prior_state:
+ self.error('E066d', version=version, prior_head=prior.head,
+ digest=digest, logical_files=', '.join(self_state[digest]))
+ elif digest not in self_state:
+ self.error('E066e', version=version, prior_head=prior.head,
+ digest=digest, logical_files=', '.join(prior_state[digest]))
| zimeon/ocfl-py | 008828b7a089aea1b43b87ffeb42d3254faee1ed | diff --git a/tests/test_inventory_validator.py b/tests/test_inventory_validator.py
index 1d2a387..6070546 100644
--- a/tests/test_inventory_validator.py
+++ b/tests/test_inventory_validator.py
@@ -300,11 +300,13 @@ class TestAll(unittest.TestCase):
log.clear()
# Good inventory in spite of diferent digests
iv.all_versions = ['v1', 'v2']
+ iv.digest_algorithm = 'a1'
iv.inventory = {"manifest": {"a1d1": ["v1/content/f1"],
"a1d2": ["v1/content/f2"],
"a1d3": ["v2/content/f3"]},
"versions": {"v1": {"state": {"a1d1": ["f1"], "a1d2": ["f2"]}},
"v2": {"state": {"a1d1": ["f1"], "a1d3": ["f3"]}}}}
+ prior.digest_algorithm = 'a2'
prior.inventory = {"manifest": {"a2d1": ["v1/content/f1"],
"a2d2": ["v1/content/f2"]},
"versions": {"v1": {"state": {"a2d1": ["f1"], "a2d2": ["f2"]}}}}
@@ -322,6 +324,31 @@ class TestAll(unittest.TestCase):
iv.validate_as_prior_version(prior)
self.assertEqual(log.errors, ["E066c"])
+ def test_compare_states_for_version(self):
+ """Test compare_states_for_version method."""
+ log = TLogger()
+ iv = InventoryValidator(log=log)
+ prior = InventoryValidator(log=TLogger())
+ # Same digests
+ iv.inventory = {
+ "versions": {"v99": {"state": {"a1d1": ["f1"], "a1d2": ["f2", "f3"]}}}}
+ prior.inventory = {
+ "versions": {"v99": {"state": {"a1d1": ["f1"], "a1d2": ["f2", "f3"]}}}}
+ iv.compare_states_for_version(prior, 'v99')
+ self.assertEqual(log.errors, [])
+ log.clear()
+ # Extra in iv
+ iv.inventory = {
+ "versions": {"v99": {"state": {"a1d1": ["f1"], "a1d2": ["f2", "f3"], "a1d3": ["f4"]}}}}
+ iv.compare_states_for_version(prior, 'v99')
+ self.assertEqual(log.errors, ['E066d'])
+ log.clear()
+ # Extra in prior
+ iv.inventory = {
+ "versions": {"v99": {"state": {"a1d2": ["f2", "f3"]}}}}
+ iv.compare_states_for_version(prior, 'v99')
+ self.assertEqual(log.errors, ['E066e'])
+
def test_check_content_path(self):
"""Test check_content_path method."""
log = TLogger()
diff --git a/tests/test_validator.py b/tests/test_validator.py
index d77fde3..1d27e02 100644
--- a/tests/test_validator.py
+++ b/tests/test_validator.py
@@ -60,7 +60,7 @@ class TestAll(unittest.TestCase):
'E061_invalid_sidecar': ['E061'],
'E063_no_inv': ['E063'],
'E064_different_root_and_latest_inventories': ['E064'],
- 'E066_E092_old_manifest_digest_incorrect': ['E092a'],
+ 'E066_E092_old_manifest_digest_incorrect': ['E066d', 'E066e', 'E092a'],
'E066_algorithm_change_state_mismatch': ['E066b'],
'E066_inconsistent_version_state': ['E066b'],
'E067_file_in_extensions_dir': ['E067'],
| Detect E066 for fixture E066_E092_old_manifest_digest_incorrect
See https://github.com/OCFL/fixtures/pull/71 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_inventory_validator.py::TestAll::test_compare_states_for_version"
] | [
"tests/test_inventory_validator.py::TestAll::test_bad_inventory_files",
"tests/test_inventory_validator.py::TestAll::test_check_content_path",
"tests/test_inventory_validator.py::TestAll::test_check_digests_present_and_used",
"tests/test_inventory_validator.py::TestAll::test_check_logical_path",
"tests/test_inventory_validator.py::TestAll::test_digest_regex",
"tests/test_inventory_validator.py::TestAll::test_init",
"tests/test_inventory_validator.py::TestAll::test_validate",
"tests/test_inventory_validator.py::TestAll::test_validate_as_prior_version",
"tests/test_inventory_validator.py::TestAll::test_validate_fixity",
"tests/test_inventory_validator.py::TestAll::test_validate_manifest",
"tests/test_inventory_validator.py::TestAll::test_validate_state_block",
"tests/test_inventory_validator.py::TestAll::test_validate_version_sequence",
"tests/test_inventory_validator.py::TestAll::test_validate_versions"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-04-27T13:02:30Z" | mit |
|
zimeon__ocfl-py-77 | diff --git a/CHANGES.md b/CHANGES.md
index 7be9540..b6f1827 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -5,6 +5,7 @@
* Additional validation improvements:
* Checks between version state in different version inventories
* Check to see is extra directories look like version directories
+ * Fix URI scheme syntax check
* Use additional fixtures in https://github.com/OCFL/fixtures for tests
## 2021-04-26 v1.2.2
diff --git a/ocfl/inventory_validator.py b/ocfl/inventory_validator.py
index 2dbe328..27eb807 100644
--- a/ocfl/inventory_validator.py
+++ b/ocfl/inventory_validator.py
@@ -65,7 +65,9 @@ class InventoryValidator():
if not isinstance(iid, str) or iid == '':
self.error("E037a")
else:
- if not re.match(r'''(\w+):.+''', iid):
+ # URI syntax https://www.rfc-editor.org/rfc/rfc3986.html#section-3.1 :
+ # scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
+ if not re.match(r'''[a-z][a-z\d\+\-\.]*:.+''', iid, re.IGNORECASE):
self.warning("W005", id=iid)
self.id = iid
else:
| zimeon/ocfl-py | 7a5ef5e75cb86fec6dd8e87b57949fd755931470 | diff --git a/tests/test_inventory_validator.py b/tests/test_inventory_validator.py
index 6070546..37519a6 100644
--- a/tests/test_inventory_validator.py
+++ b/tests/test_inventory_validator.py
@@ -52,6 +52,17 @@ class TestAll(unittest.TestCase):
iv.validate({"id": []})
self.assertIn('E037a', log.errors)
log.clear()
+ # Valid and invalid URIs
+ iv.validate({"id": "scheme:rest", "digestAlgorithm": "sha512"})
+ self.assertNotIn('W005', log.warns)
+ log.clear()
+ iv.validate({"id": "URN-3:rest", "digestAlgorithm": "sha512"})
+ self.assertNotIn('W005', log.warns)
+ log.clear()
+ iv.validate({"id": "a1+2-3z.:rest", "digestAlgorithm": "sha512"})
+ self.assertNotIn('W005', log.warns)
+ self.assertNotIn('W004', log.warns)
+ log.clear()
iv.validate({"id": "not_a_uri", "digestAlgorithm": "sha256"})
self.assertIn('W005', log.warns)
self.assertIn('W004', log.warns)
| URN Object IDs flagged as validation warning
OCFL objects with an `id` such as: "URN-3:HUL.DRS.OBJECT:100775205", are flagged as validation warnings. I believe these should be valid.. as URNs are valid URIs and the above URN-3 scheme is a valid URN.
See: https://www.iana.org/assignments/urn-informal/urn-3 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_inventory_validator.py::TestAll::test_validate"
] | [
"tests/test_inventory_validator.py::TestAll::test_bad_inventory_files",
"tests/test_inventory_validator.py::TestAll::test_check_content_path",
"tests/test_inventory_validator.py::TestAll::test_check_digests_present_and_used",
"tests/test_inventory_validator.py::TestAll::test_check_logical_path",
"tests/test_inventory_validator.py::TestAll::test_compare_states_for_version",
"tests/test_inventory_validator.py::TestAll::test_digest_regex",
"tests/test_inventory_validator.py::TestAll::test_init",
"tests/test_inventory_validator.py::TestAll::test_validate_as_prior_version",
"tests/test_inventory_validator.py::TestAll::test_validate_fixity",
"tests/test_inventory_validator.py::TestAll::test_validate_manifest",
"tests/test_inventory_validator.py::TestAll::test_validate_state_block",
"tests/test_inventory_validator.py::TestAll::test_validate_version_sequence",
"tests/test_inventory_validator.py::TestAll::test_validate_versions"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2021-07-02T17:09:14Z" | mit |
|
zimeon__ocfl-py-94 | diff --git a/ocfl-validate.py b/ocfl-validate.py
index 30e1d9c..f5653ec 100755
--- a/ocfl-validate.py
+++ b/ocfl-validate.py
@@ -61,7 +61,8 @@ for path in args.path:
obj = ocfl.Object(lax_digests=args.lax_digests)
if obj.validate_inventory(path,
show_warnings=show_warnings,
- show_errors=not args.very_quiet):
+ show_errors=not args.very_quiet,
+ extract_spec_version=True):
num_good += 1
else:
log.error("Bad path %s (%s)", path, path_type)
diff --git a/ocfl/data/validation-errors.json b/ocfl/data/validation-errors.json
index 7d1002b..fe8f676 100644
--- a/ocfl/data/validation-errors.json
+++ b/ocfl/data/validation-errors.json
@@ -184,12 +184,24 @@
"en": "OCFL Object %s inventory id `%s` does not match the value in the root inventory `%s`"
}
},
- "E038": {
+ "E038a": {
"params": ["where", "expected", "got"],
"description": {
"en": "OCFL Object %s inventory `type` attribute has wrong value (expected %s, got %s)"
}
},
+ "E038b": {
+ "params": ["where", "got", "assumed_spec_version"],
+ "description": {
+ "en": "OCFL Object %s inventory `type` attribute does not look like a valid specification URI (got %s), will proceed as if using version %s"
+ }
+ },
+ "E038c": {
+ "params": ["where", "got", "assumed_spec_version"],
+ "description": {
+ "en": "OCFL Object %s inventory `type` attribute has an unsupported specification version number (%s), will proceed as if using version %s"
+ }
+ },
"E039": {
"params": ["where", "digest_algorithm"],
"description": {
diff --git a/ocfl/inventory_validator.py b/ocfl/inventory_validator.py
index cb702db..6684155 100644
--- a/ocfl/inventory_validator.py
+++ b/ocfl/inventory_validator.py
@@ -48,6 +48,8 @@ class InventoryValidator():
self.head = 'UNKNOWN'
# Validation control
self.lax_digests = lax_digests
+ # Configuration
+ self.spec_versions_supported = ('1.0', '1.1')
def error(self, code, **args):
"""Error with added context."""
@@ -57,8 +59,13 @@ class InventoryValidator():
"""Warning with added context."""
self.log.warning(code, where=self.where, **args)
- def validate(self, inventory):
- """Validate a given inventory."""
+ def validate(self, inventory, extract_spec_version=False):
+ """Validate a given inventory.
+
+ If extract_spec_version is True then will look at the type value to determine
+ the specification version. In the case that there is no type value or it isn't
+ valid, then other tests will be based on the version given in self.spec_version.
+ """
# Basic structure
self.inventory = inventory
if 'id' in inventory:
@@ -75,8 +82,18 @@ class InventoryValidator():
self.error("E036a")
if 'type' not in inventory:
self.error("E036b")
+ elif not isinstance(inventory['type'], str):
+ self.error("E999")
+ elif extract_spec_version:
+ m = re.match(r'''https://ocfl.io/(\d+.\d)/spec/#inventory''', inventory['type'])
+ if not m:
+ self.error('E038b', got=inventory['type'], assumed_spec_version=self.spec_version)
+ elif m.group(1) in self.spec_versions_supported:
+ self.spec_version = m.group(1)
+ else:
+ self.error("E038c", got=m.group(1), assumed_spec_version=self.spec_version)
elif inventory['type'] != 'https://ocfl.io/' + self.spec_version + '/spec/#inventory':
- self.error("E038", expected='https://ocfl.io/' + self.spec_version + '/spec/#inventory', got=inventory['type'])
+ self.error("E038a", expected='https://ocfl.io/' + self.spec_version + '/spec/#inventory', got=inventory['type'])
if 'digestAlgorithm' not in inventory:
self.error("E036c")
elif inventory['digestAlgorithm'] == 'sha512':
diff --git a/ocfl/object.py b/ocfl/object.py
index 83b3e74..e8fb726 100755
--- a/ocfl/object.py
+++ b/ocfl/object.py
@@ -532,14 +532,14 @@ class Object():
self.log.info("OCFL object at %s is INVALID", objdir)
return passed
- def validate_inventory(self, path, show_warnings=True, show_errors=True):
+ def validate_inventory(self, path, show_warnings=True, show_errors=True, extract_spec_version=False):
"""Validate just an OCFL Object inventory at path."""
validator = Validator(show_warnings=show_warnings,
show_errors=show_errors)
try:
(inv_dir, inv_file) = fs.path.split(path)
validator.obj_fs = open_fs(inv_dir, create=False)
- validator.validate_inventory(inv_file, where='standalone')
+ validator.validate_inventory(inv_file, where='standalone', extract_spec_version=extract_spec_version)
except fs.errors.ResourceNotFound:
validator.log.error('E033', where='standalone', explanation='failed to open directory')
except ValidatorAbortException:
diff --git a/ocfl/validator.py b/ocfl/validator.py
index 060c1dc..6fc3dc1 100644
--- a/ocfl/validator.py
+++ b/ocfl/validator.py
@@ -132,12 +132,17 @@ class Validator():
pass
return self.log.num_errors == 0
- def validate_inventory(self, inv_file, where='root'):
+ def validate_inventory(self, inv_file, where='root', extract_spec_version=False):
"""Validate a given inventory file, record errors with self.log.error().
Returns inventory object for use in later validation
of object content. Does not look at anything else in the
object itself.
+
+ where - used for reporting messages of where inventory is in object
+
+ extract_spec_version - if set True will attempt to take spec_version from the
+ inventory itself instead of using the spec_version provided
"""
try:
with self.obj_fs.openbin(inv_file, 'r') as fh:
@@ -148,7 +153,7 @@ class Validator():
inv_validator = InventoryValidator(log=self.log, where=where,
lax_digests=self.lax_digests,
spec_version=self.spec_version)
- inv_validator.validate(inventory)
+ inv_validator.validate(inventory, extract_spec_version=extract_spec_version)
return inventory, inv_validator
def validate_inventory_digest(self, inv_file, digest_algorithm, where="root"):
| zimeon/ocfl-py | aa078262eff7f19ee33e287342e9875fba049b69 | diff --git a/tests/test_inventory_validator.py b/tests/test_inventory_validator.py
index f8f53e3..56081c6 100644
--- a/tests/test_inventory_validator.py
+++ b/tests/test_inventory_validator.py
@@ -68,8 +68,14 @@ class TestAll(unittest.TestCase):
self.assertIn('W004', log.warns)
log.clear()
iv.validate({"id": "like:uri", "type": "wrong type", "digestAlgorithm": "my_digest"})
- self.assertIn('E038', log.errors)
+ self.assertIn('E038a', log.errors)
self.assertIn('E039', log.errors)
+ log.clear()
+ iv.validate({"id": "like:uri", "type": "wrong type", "digestAlgorithm": "my_digest"}, extract_spec_version=True)
+ self.assertIn('E038b', log.errors)
+ log.clear()
+ iv.validate({"id": "like:uri", "type": "https://ocfl.io/100.9/spec/#inventory", "digestAlgorithm": "my_digest"}, extract_spec_version=True)
+ self.assertIn('E038c', log.errors)
iv = InventoryValidator(log=log, lax_digests=True)
log.clear()
iv.validate({"id": "like:uri", "type": "wrong type", "digestAlgorithm": "my_digest"})
| Fix handling of spec version in standalone inventory check
To replicate example:
```
(py38) simeon@RottenApple ocfl-py> ./ocfl-validate.py extra_fixtures/1.1/good-objects/empty_fixity
INFO:ocfl.object:OCFL object at extra_fixtures/1.1/good-objects/empty_fixity is VALID
(py38) simeon@RottenApple ocfl-py> ./ocfl-validate.py extra_fixtures/1.1/good-objects/empty_fixity/inventory.json
[E038] OCFL Object standalone inventory `type` attribute has wrong value (see https://ocfl.io/1.0/spec/#E038)
INFO:ocfl.object:Standalone OCFL inventory at extra_fixtures/1.1/good-objects/empty_fixity/inventory.json is INVALID
```
Inventory is good, it is just v1.1 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_inventory_validator.py::TestAll::test_validate"
] | [
"tests/test_inventory_validator.py::TestAll::test_bad_inventory_files",
"tests/test_inventory_validator.py::TestAll::test_check_content_path",
"tests/test_inventory_validator.py::TestAll::test_check_digests_present_and_used",
"tests/test_inventory_validator.py::TestAll::test_check_logical_path",
"tests/test_inventory_validator.py::TestAll::test_compare_states_for_version",
"tests/test_inventory_validator.py::TestAll::test_digest_regex",
"tests/test_inventory_validator.py::TestAll::test_init",
"tests/test_inventory_validator.py::TestAll::test_validate_as_prior_version",
"tests/test_inventory_validator.py::TestAll::test_validate_fixity",
"tests/test_inventory_validator.py::TestAll::test_validate_manifest",
"tests/test_inventory_validator.py::TestAll::test_validate_state_block",
"tests/test_inventory_validator.py::TestAll::test_validate_version_sequence",
"tests/test_inventory_validator.py::TestAll::test_validate_versions"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-04-16T18:07:32Z" | mit |
|
zmoog__refurbished-98 | diff --git a/README.md b/README.md
index d747423..9fa9355 100644
--- a/README.md
+++ b/README.md
@@ -21,7 +21,14 @@ $ rfrb it macs --min-saving=300
#### Output formats
-Refurbished supports several output formats.
+Refurbished supports several output formats:
+
+- `text`
+- `json`
+- `ndjson`
+- `csv`
+
+Here are a few examples.
##### text
@@ -67,6 +74,15 @@ $ rfrb it ipads --max-price 539 --format ndjson
{"name": "iPad Air Wi-Fi 64GB ricondizionato - Celeste (quarta generazione)", "family": "ipad", "url": "https://www.apple.com/it/shop/product/FYFQ2TY/A/iPad-Air-Wi-Fi-64GB-ricondizionato-Celeste-quarta-generazione", "price": 539.0, "previous_price": 639.0, "savings_price": 100.0, "saving_percentage": 0.1564945226917058, "model": "FYFQ2TY"}
```
+##### CSV
+
+```shell
+$ rfrb it ipads --name 'iPad Air Wi-Fi 64GB' --format csv
+name,family,store,url,price,previous_price,savings_price,saving_percentage,model
+iPad Air Wi-Fi 64GB ricondizionato - Oro (terza generazione),ipad,it,https://www.apple.com/it/shop/product/FUUL2TY/A/iPad-Air-Wi-Fi-64GB-ricondizionato-Oro-terza-generazione,479.00,559.00,80.00,0.14,FUUL2TY
+iPad Air Wi-Fi 64GB ricondizionato - Celeste (quarta generazione),ipad,it,https://www.apple.com/it/shop/product/FYFQ2TY/A/iPad-Air-Wi-Fi-64GB-ricondizionato-Celeste-quarta-generazione,539.00,639.00,100.00,0.16,FYFQ2TY
+iPad Air Wi-Fi 64GB ricondizionato - Grigio siderale (quarta generazione),ipad,it,https://www.apple.com/it/shop/product/FYFM2TY/A/iPad-Air-Wi-Fi-64GB-ricondizionato-Grigio-siderale-quarta-generazione,539.00,639.00,100.00,0.16,FYFM2TY
+```
### Library
@@ -88,10 +104,10 @@ MacBook Pro 13,3" ricondizionato con Intel Core i5 quad-core a 2,0GHz e display
## Built With
-* [beautifulsoup4](https://www.crummy.com/software/BeautifulSoup/)
-* [price-parser](https://github.com/scrapinghub/price-parser)
-* [pydantic](https://pydantic-docs.helpmanual.io/)
-* [requests](https://requests.readthedocs.io/en/master/)
+- [beautifulsoup4](https://www.crummy.com/software/BeautifulSoup/)
+- [price-parser](https://github.com/scrapinghub/price-parser)
+- [pydantic](https://pydantic-docs.helpmanual.io/)
+- [requests](https://requests.readthedocs.io/en/master/)
## Development
@@ -107,9 +123,9 @@ We use [SemVer](http://semver.org/) for versioning. For the versions available,
## Authors
-* **Maurizio Branca** - *Initial work* - [zmoog](https://github.com/zmoog)
-* **Yizhou "Andi" Cui** - *Improved parser* - [AndiCui](https://github.com/AndiCui)
-* **Grant** - *Dockerfile* - [Firefishy](https://github.com/Firefishy)
+- **Maurizio Branca** - *Initial work* - [zmoog](https://github.com/zmoog)
+- **Yizhou "Andi" Cui** - *Improved parser* - [AndiCui](https://github.com/AndiCui)
+- **Grant** - *Dockerfile* - [Firefishy](https://github.com/Firefishy)
## License
diff --git a/cli/rfrb b/cli/rfrb
index 419697d..9f2adf5 100755
--- a/cli/rfrb
+++ b/cli/rfrb
@@ -3,7 +3,7 @@ import decimal
import click
-from refurbished import ProductNotFoundError, Store, feedback
+from refurbished import ProductNotFoundError, Store, cli, feedback
@click.command()
@@ -63,7 +63,7 @@ def get_products(
name=name,
)
- feedback.result(feedback.ProductsResult(products))
+ feedback.result(cli.ProductsResult(products))
except ProductNotFoundError:
# the selected procuct is not available on this store
diff --git a/refurbished/cli.py b/refurbished/cli.py
new file mode 100644
index 0000000..95efd2b
--- /dev/null
+++ b/refurbished/cli.py
@@ -0,0 +1,31 @@
+from typing import List
+
+from .model import Product
+
+
+class ProductsResult:
+ def __init__(self, values: List[Product]):
+ self.values = values
+
+ def str(self) -> str:
+ if len(self.values) == 0:
+ return "No products found"
+ out = ""
+ for p in self.values:
+ out += (
+ f"{p.previous_price} "
+ f"{p.price} "
+ f"{p.savings_price} "
+ f"({p.saving_percentage * 100}%) {p.name}\n"
+ )
+ return out
+
+ def data(self) -> List[Product]:
+ return self.values
+
+ def fieldnames(self) -> List[str]:
+ if self.values:
+ return (
+ self.values[0].__pydantic_model__.schema()["properties"].keys()
+ )
+ return []
diff --git a/refurbished/feedback.py b/refurbished/feedback.py
index 99fa117..9647c9b 100644
--- a/refurbished/feedback.py
+++ b/refurbished/feedback.py
@@ -1,11 +1,11 @@
+import csv
+import io
import json
-from typing import List
+from dataclasses import asdict
import click
from pydantic.json import pydantic_encoder
-from .model import Product
-
class Feedback:
def __init__(self, format):
@@ -14,27 +14,45 @@ class Feedback:
def echo(self, text, nl=True, err=False):
click.echo(text, nl=nl, err=err)
- def result(self, result):
+ def result(self, result) -> None:
if self.format == "text":
click.echo(
result.str(),
- # delefate newlines to the result class
+ # delegate newlines to the result class
nl=False,
)
elif self.format == "json":
+ # assumption: entries are all pydantic dataclasses
click.echo(
json.dumps(result.data(), indent=2, default=pydantic_encoder),
# delegate newline to json.dumps
nl=False,
)
elif self.format == "ndjson":
- for product in result.data():
+ # assumption: entries are all pydantic dataclasses
+ for entry in result.data():
click.echo(
- json.dumps(product, default=pydantic_encoder),
+ json.dumps(entry, default=pydantic_encoder),
# The newline is required by the format to separate the
# JSON objects
nl=True,
)
+ elif self.format == "csv":
+ entries = result.data()
+
+ # we need at least one entry to get the fieldnames from
+ # the pydantic dataclass and write the csv header
+ if not entries:
+ return
+
+ out = io.StringIO()
+ writer = csv.DictWriter(out, fieldnames=result.fieldnames())
+ writer.writeheader()
+ for entry in entries:
+ writer.writerow(asdict(entry))
+
+ # delegate newline to the csv writer
+ click.echo(out.getvalue(), nl=False)
_current_feedback = Feedback("text")
@@ -50,24 +68,3 @@ def echo(value, nl=True, err=False):
def result(values):
_current_feedback.result(values)
-
-
-class ProductsResult:
- def __init__(self, values: List[Product]):
- self.values = values
-
- def str(self) -> str:
- if len(self.values) == 0:
- return "No products found"
- out = ""
- for p in self.values:
- out += (
- f"{p.previous_price} "
- f"{p.price} "
- f"{p.savings_price} "
- f"({p.saving_percentage * 100}%) {p.name}\n"
- )
- return out
-
- def data(self):
- return self.values
diff --git a/refurbished/model.py b/refurbished/model.py
index 7f9ea33..ebd9eff 100644
--- a/refurbished/model.py
+++ b/refurbished/model.py
@@ -1,7 +1,6 @@
import decimal
import re
-# from dataclasses import dataclass
from pydantic.dataclasses import dataclass
diff --git a/requirements-dev.txt b/requirements-dev.txt
index e071685..49780e0 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -1,1 +1,1 @@
-pytest==7.1.3
+pytest==7.2.0
| zmoog/refurbished | ef4f517653c45c24a567dfa747196622bf2c2895 | diff --git a/tests/test_feedback.py b/tests/test_feedback.py
index 8c0c158..21695cf 100644
--- a/tests/test_feedback.py
+++ b/tests/test_feedback.py
@@ -83,3 +83,21 @@ class TestFeedback(object):
result.output
== '{"name": "iPad Wi-Fi 128GB ricondizionato - Argento (sesta generazione)", "family": "ipad", "store": "it", "url": "https://www.apple.com/it/shop/product/FR7K2TY/A/Refurbished-iPad-Wi-Fi-128GB-Silver-6th-Generation", "price": 389.0, "previous_price": 449.0, "savings_price": 60.0, "saving_percentage": 0.133630289532294, "model": "FR7K2TY"}\n' # noqa: E501
)
+
+ @patch(
+ "requests.Session.get",
+ side_effect=ResponseBuilder("it_ipad.html"),
+ )
+ def test_csv_format(self, _, cli_runner: CliRunner):
+ result = cli_runner.invoke(
+ rfrb.get_products,
+ ["it", "ipads", "--max-price", "389", "--format", "csv"],
+ )
+
+ assert result.exit_code == 0
+ assert (
+ result.output
+ == """name,family,store,url,price,previous_price,savings_price,saving_percentage,model
+iPad Wi-Fi 128GB ricondizionato - Argento (sesta generazione),ipad,it,https://www.apple.com/it/shop/product/FR7K2TY/A/Refurbished-iPad-Wi-Fi-128GB-Silver-6th-Generation,389.00,449.00,60.00,0.133630289532294,FR7K2TY
+""" # noqa: E501
+ )
| CSV output option
We should add a new CSV output option for uses cases where users want the raw data to use with other tools.
here's an example:
```shell
$ rfrb it ipads --name 'iPad Air Wi-Fi 64GB ricondizionato - Celeste (quarta generazione)' --format csv
name,family,store,url,price,previous_price,savings_price,saving_percentage,model
"iPad Air Wi-Fi 64GB ricondizionato - Celeste (quarta generazione)","ipad","it","https://www.apple.com/it/shop/product/FYFQ2TY/A/iPad-Air-Wi-Fi-64GB-ricondizionato-Celeste-quarta-generazione",539.0,639.0, 100.0,0.15,"FYFQ2TY"
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_feedback.py::TestFeedback::test_csv_format"
] | [
"tests/test_feedback.py::TestFeedback::test_default_format",
"tests/test_feedback.py::TestFeedback::test_text_format",
"tests/test_feedback.py::TestFeedback::test_json_format",
"tests/test_feedback.py::TestFeedback::test_ndjson_format"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_added_files",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-10-24T21:58:33Z" | mit |
|
znicholls__CMIP6-json-data-citation-generator-10 | diff --git a/CMIP6_json_data_citation_generator/__init__.py b/CMIP6_json_data_citation_generator/__init__.py
index bb6ab69..dceaa2a 100644
--- a/CMIP6_json_data_citation_generator/__init__.py
+++ b/CMIP6_json_data_citation_generator/__init__.py
@@ -1,5 +1,7 @@
from os import listdir, makedirs, walk
from os.path import split, splitext, basename, join, isdir, isfile
+import io
+import sys
import yaml
import json
@@ -149,8 +151,15 @@ class jsonGenerator():
return updated_yml
def write_json_to_file(self, json_dict=None, file_name=None):
- with open(file_name, 'w') as file_name:
- json.dump(json_dict, file_name, indent=4)
+ with io.open(file_name, 'w', encoding='utf8') as json_file:
+ text = json.dumps(
+ json_dict,
+ ensure_ascii=False,
+ indent=4
+ )
+ if sys.version.startswith('2'):
+ text=unicode(text)
+ json_file.write(text)
def write_json_for_filename_to_file_with_template(self, file_name=None, yaml_template=None, output_file=None):
yaml_template = self.return_template_yaml_from(in_file=yaml_template)
| znicholls/CMIP6-json-data-citation-generator | 53d8fe237e012f156e9d11d082d6474674717dc9 | diff --git a/tests/data/yaml-test-files/test-special-char.yml b/tests/data/yaml-test-files/test-special-char.yml
new file mode 100644
index 0000000..eee4ea7
--- /dev/null
+++ b/tests/data/yaml-test-files/test-special-char.yml
@@ -0,0 +1,6 @@
+creators:
+ - creatorName: "Müller, Björn"
+ givenName: "Björn"
+ familyName: "Müller"
+ email: "björnmüller@äéèîç.com"
+ affiliation: "kæčœ universität von Lände"
diff --git a/tests/test_generate_CMIP6_json_files.py b/tests/test_generate_CMIP6_json_files.py
index 4d30184..aa27d7f 100644
--- a/tests/test_generate_CMIP6_json_files.py
+++ b/tests/test_generate_CMIP6_json_files.py
@@ -22,7 +22,7 @@ test_file_unique_jsons = [
'UoM_UoM-ssp534os-1-1-0_input4MIPs_ScenarioMIP',
'UoM_UoM-ssp585-1-1-0_input4MIPs_ScenarioMIP',
]
-test_output_path = './test-json-output-path'
+test_output_path = './tests/test-json-output-path'
@pytest.fixture
def tear_down_test_path():
diff --git a/tests/test_jsonGenerator.py b/tests/test_jsonGenerator.py
index 5bf97e9..f23d091 100644
--- a/tests/test_jsonGenerator.py
+++ b/tests/test_jsonGenerator.py
@@ -1,3 +1,5 @@
+# -*- coding: utf-8 -*-
+
from os import listdir, remove
from os.path import join, isfile, dirname
from shutil import rmtree
@@ -5,6 +7,7 @@ import re
import datetime
import sys
from tempfile import mkstemp
+import codecs
import pytest
from pytest import raises
@@ -15,7 +18,8 @@ from utils import captured_output
from CMIP6_json_data_citation_generator import CMIPPathHandler
from CMIP6_json_data_citation_generator import jsonGenerator
-test_file_path_empty_files = join('.', 'tests', 'data', 'empty-test-files')
+test_data_path = join('.', 'tests', 'data')
+test_file_path_empty_files = join(test_data_path, 'empty-test-files')
test_file_unique_source_ids = [
'UoM-ssp119-1-1-0',
'UoM-ssp245-1-1-0',
@@ -26,11 +30,16 @@ test_file_unique_source_ids = [
]
test_output_path = join('.', 'test-json-output-path')
-test_file_path_yaml = join('.', 'tests', 'data', 'yaml-test-files')
+test_file_path_yaml = join(test_data_path, 'yaml-test-files')
test_data_citation_template_yaml = join(
test_file_path_yaml,
'test-data-citation-template.yml'
)
+test_file_path_yaml_special_char = join(test_data_path, 'yaml-test-files', 'test-special-char.yml')
+test_file_path_yaml_special_char_written = test_file_path_yaml_special_char.replace(
+ '.yml',
+ '-written.yml'
+)
def get_test_file():
for test_file in listdir(test_file_path_empty_files):
@@ -264,13 +273,13 @@ def test_check_yaml_replace_values():
assert subbed_yml['fundingReferences'][0]['funderName'] == [value]
def test_write_json_to_file():
- with patch('CMIP6_json_data_citation_generator.open') as mock_open:
- with patch('CMIP6_json_data_citation_generator.json.dump') as mock_json_dump:
+ with patch('CMIP6_json_data_citation_generator.io.open') as mock_open:
+ with patch('CMIP6_json_data_citation_generator.json.dumps') as mock_json_dump:
Generator = jsonGenerator()
test_fn = 'UoM-ssp119-1-1-0'
test_dict = {'hi': 'test', 'bye': 'another test'}
Generator.write_json_to_file(json_dict=test_dict, file_name=test_fn)
- mock_open.assert_called_with(test_fn, 'w')
+ mock_open.assert_called_with(test_fn, 'w', encoding='utf8')
mock_json_dump.assert_called_once()
@patch.object(jsonGenerator, 'return_template_yaml_from')
@@ -462,3 +471,49 @@ def test_invalid_name_in_dir(mock_walk, mock_isdir):
assert 'Unable to split filename: {}'.format(junk_name) == out.getvalue().strip()
+
+def test_special_yaml_read():
+ Generator = jsonGenerator()
+ actual_result = Generator.return_template_yaml_from(
+ in_file=test_file_path_yaml_special_char
+ )
+ expected_result = {
+ 'creators': [
+ {
+ 'creatorName': u"Müller, Björn",
+ 'givenName': u"Björn",
+ 'familyName': u"Müller",
+ 'email': u"björnmüller@äéèîç.com",
+ 'affiliation': u'kæčœ universität von Lände',
+ },
+ ],
+ }
+ assert actual_result == expected_result
+
[email protected]
+def remove_written_special_yaml():
+ yield None
+ if isfile(test_file_path_yaml_special_char_written):
+ remove(test_file_path_yaml_special_char_written)
+
+def test_special_yaml_write(remove_written_special_yaml):
+ Generator = jsonGenerator()
+ dict_to_write = Generator.return_template_yaml_from(
+ in_file=test_file_path_yaml_special_char
+ )
+ Generator.write_json_to_file(
+ json_dict=dict_to_write,
+ file_name=test_file_path_yaml_special_char_written
+ )
+ expected_strings = [
+ u"Müller, Björn",
+ u"Björn",
+ u"Müller",
+ u"björnmüller@äéèîç.com",
+ u"kæčœ universität von Lände",
+ ]
+ with codecs.open(test_file_path_yaml_special_char_written, "r", "utf-8") as written_file:
+ written_text = written_file.read()
+
+ for expected_string in expected_strings:
+ assert expected_string in written_text
| Check special character support
check the support for 'utf-8' in the json template and
the json result?
The authors or even their affiliations might be 'utf-8' (non-English).
To give you a German example: One of our most common last names is:
'Müller'. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_jsonGenerator.py::test_write_json_to_file"
] | [
"tests/test_jsonGenerator.py::test_get_unique_source_ids_in_dir",
"tests/test_jsonGenerator.py::test_get_unique_source_ids_in_dir_only_acts_on_nc_files",
"tests/test_jsonGenerator.py::test_generate_json_for_all_unique_scenario_ids",
"tests/test_jsonGenerator.py::test_write_json_to_file_only_runs_on_nc_file",
"tests/test_jsonGenerator.py::test_invalid_name_in_dir"
] | {
"failed_lite_validators": [],
"has_test_patch": true,
"is_lite": true
} | "2018-06-29T11:39:06Z" | mit |
|
zooba__deck-13 | diff --git a/deck.py b/deck.py
index dc7b3a5..ab7193c 100644
--- a/deck.py
+++ b/deck.py
@@ -9,7 +9,6 @@ import itertools
import random
import sys
-
__all__ = [
"Card",
"Deck",
@@ -22,7 +21,6 @@ __all__ = [
"Value",
]
-
_SUIT_SORT_ORDER = {
# Handle suit-less comparisons gracefully (as highest)
"": 10,
@@ -260,6 +258,7 @@ def get_poker_hand(cards):
The best hand sorts last (is greater than other hands).
"""
cards = sorted(cards, key=aces_high, reverse=True)
+ cards_low_ace = sorted(cards, key=lambda card: card.value, reverse=True)
# Any jokers will have sorted to the front
if cards and cards[0].joker:
@@ -280,9 +279,14 @@ def get_poker_hand(cards):
is_straight = len(cards) == 5 and all(
i[0].value == i[1] for i in zip(cards, range(cards[0].value, -5, -1))
)
+ is_ace_low_straight = len(cards) == 5 and all(
+ i[0].value == i[1] for i in zip(cards_low_ace, range(cards_low_ace[0].value, -5, -1))
+ )
if len(suits) == 1 and is_straight:
return PokerHand.StraightFlush, aces_high(high_card)
+ if len(suits) == 1 and is_ace_low_straight:
+ return PokerHand.StraightFlush, cards_low_ace[0].value
if of_a_kind == 4:
return PokerHand.FourOfAKind, aces_high(of_a_kind_card)
if of_a_kind == 3 and second_pair == 2:
@@ -291,6 +295,8 @@ def get_poker_hand(cards):
return PokerHand.Flush, aces_high(high_card)
if is_straight:
return PokerHand.Straight, aces_high(high_card)
+ if is_ace_low_straight:
+ return PokerHand.Straight, cards_low_ace[0].value
if of_a_kind == 3:
return (PokerHand.ThreeOfAKind, aces_high(of_a_kind_card)) + (
(aces_high(second_pair_card),) if second_pair_card else ()
@@ -520,7 +526,6 @@ class Hand(list):
self[:] = self.sorted(order=order, reverse=reverse)
def __format__(self, spec):
- import re
if not spec:
spec = "4.3"
diff --git a/readme.md b/readme.md
index fe76ca6..f059b60 100644
--- a/readme.md
+++ b/readme.md
@@ -210,7 +210,7 @@ The result of the function is a tuple containing first a `PokerHand` value, foll
Suits are not taken into account for breaking ties.
```python
->>> from deck import Deck, get_poker_hand
+>>> from deck import Deck, get_poker_hand, Hand, HandSort
>>> deck = Deck(include_jokers=False)
>>> deck.shuffle()
>>> p1, p2 = deck.deal_hands(hands=2, cards=5)
| zooba/deck | c8ace02770146b674eaeb184a5ebebed36cd2edd | diff --git a/deck-tests.py b/deck-tests.py
index 1e43659..dc33044 100644
--- a/deck-tests.py
+++ b/deck-tests.py
@@ -135,6 +135,17 @@ class PokerHandTests(unittest.TestCase):
hand = deck.get_poker_hand(cards)
assert hand == (deck.PokerHand.Straight, 6)
+ def test_straight_with_low_ace(self):
+ cards = [
+ Card("Spades", 1),
+ Card("Spades", 2),
+ Card("Clubs", 3),
+ Card("Hearts", 4),
+ Card("Diamonds", 5),
+ ]
+ hand = deck.get_poker_hand(cards)
+ assert hand == (deck.PokerHand.Straight, 5)
+
def test_flush(self):
cards = [
Card("Clubs", 2),
@@ -179,6 +190,17 @@ class PokerHandTests(unittest.TestCase):
hand = deck.get_poker_hand(cards)
assert hand == (deck.PokerHand.StraightFlush, 9)
+ def test_straight_flush_with_low_ace(self):
+ cards = [
+ Card("Clubs", 1),
+ Card("Clubs", 2),
+ Card("Clubs", 3),
+ Card("Clubs", 4),
+ Card("Clubs", 5),
+ ]
+ hand = deck.get_poker_hand(cards)
+ assert hand == (deck.PokerHand.StraightFlush, 5)
+
def test_compare_1(self):
cards = [
Card("Spades", 2),
| Ace to Five straight/straight flush are not handled in get_poker_hand
Low-ace straight/straight flush aren't found as the sort assumes aces-high.
PR on way to add tests & support. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"deck-tests.py::PokerHandTests::test_straight_flush_with_low_ace",
"deck-tests.py::PokerHandTests::test_straight_with_low_ace"
] | [
"deck-tests.py::DeckTests::test_count",
"deck-tests.py::DeckTests::test_count_multiple",
"deck-tests.py::DeckTests::test_count_no_jokers",
"deck-tests.py::DeckTests::test_count_no_jokers_multiple",
"deck-tests.py::DeckTests::test_patch",
"deck-tests.py::CardTests::test_eq",
"deck-tests.py::CardTests::test_format",
"deck-tests.py::CardTests::test_init",
"deck-tests.py::PokerHandTests::test_compare_1",
"deck-tests.py::PokerHandTests::test_compare_2",
"deck-tests.py::PokerHandTests::test_compare_3",
"deck-tests.py::PokerHandTests::test_flush",
"deck-tests.py::PokerHandTests::test_fours",
"deck-tests.py::PokerHandTests::test_full_house",
"deck-tests.py::PokerHandTests::test_high_card",
"deck-tests.py::PokerHandTests::test_high_card_ace",
"deck-tests.py::PokerHandTests::test_pair",
"deck-tests.py::PokerHandTests::test_straight",
"deck-tests.py::PokerHandTests::test_straight_flush",
"deck-tests.py::PokerHandTests::test_triples",
"deck-tests.py::PokerHandTests::test_two_pair",
"deck-tests.py::HandTests::test_contains",
"deck-tests.py::HandTests::test_count",
"deck-tests.py::HandTests::test_deal",
"deck-tests.py::HandTests::test_default_sort",
"deck-tests.py::HandTests::test_intersect_exact",
"deck-tests.py::HandTests::test_intersect_suit",
"deck-tests.py::HandTests::test_intersect_value",
"deck-tests.py::HandTests::test_poker_sort",
"deck-tests.py::HandTests::test_sort_suit",
"deck-tests.py::HandTests::test_type_checks",
"deck-tests.py::HandTests::test_union_exact",
"deck-tests.py::HandTests::test_union_suit",
"deck-tests.py::HandTests::test_union_value"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2022-04-03T20:44:57Z" | mit |
|
zooniverse__panoptes-python-client-207 | diff --git a/panoptes_client/panoptes.py b/panoptes_client/panoptes.py
index 3f59a9b..463751c 100644
--- a/panoptes_client/panoptes.py
+++ b/panoptes_client/panoptes.py
@@ -935,7 +935,7 @@ class LinkResolver(object):
def __setattr__(self, name, value):
reserved_names = ('raw', 'parent')
- if name not in reserved_names and name in self.parent.raw['links']:
+ if name not in reserved_names and name not in dir(self):
if not self.parent._loaded:
self.parent.reload()
if isinstance(value, PanoptesObject):
| zooniverse/panoptes-python-client | a6f91519326e3be7e974b88ce4f8805c5db9a0e4 | diff --git a/panoptes_client/tests/test_linkresolver.py b/panoptes_client/tests/test_linkresolver.py
new file mode 100644
index 0000000..72555c6
--- /dev/null
+++ b/panoptes_client/tests/test_linkresolver.py
@@ -0,0 +1,23 @@
+from __future__ import absolute_import, division, print_function
+
+import unittest
+import sys
+
+if sys.version_info <= (3, 0):
+ from mock import Mock
+else:
+ from unittest.mock import Mock
+
+from panoptes_client.panoptes import LinkResolver
+
+
+class TestLinkResolver(unittest.TestCase):
+ def test_set_new_link(self):
+ parent = Mock()
+ parent.raw = {'links': {}}
+
+ target = Mock()
+
+ resolver = LinkResolver(parent)
+ resolver.newlink = target
+ self.assertEqual(parent.raw['links'].get('newlink', None), target)
diff --git a/panoptes_client/tests/test_subject_set.py b/panoptes_client/tests/test_subject_set.py
new file mode 100644
index 0000000..97d33cd
--- /dev/null
+++ b/panoptes_client/tests/test_subject_set.py
@@ -0,0 +1,42 @@
+from __future__ import absolute_import, division, print_function
+
+import unittest
+import sys
+
+if sys.version_info <= (3, 0):
+ from mock import patch, Mock
+else:
+ from unittest.mock import patch, Mock
+
+from panoptes_client.subject_set import SubjectSet
+
+
+class TestSubjectSet(unittest.TestCase):
+ def test_create(self):
+ with patch('panoptes_client.panoptes.Panoptes') as pc:
+ pc.client().post = Mock(return_value=(
+ {
+ 'subject_sets': [{
+ 'id': 0,
+ 'display_name': '',
+ }],
+ },
+ '',
+ ))
+ subject_set = SubjectSet()
+ subject_set.links.project = 1234
+ subject_set.display_name = 'Name'
+ subject_set.save()
+
+ pc.client().post.assert_called_with(
+ '/subject_sets',
+ json={
+ 'subject_sets': {
+ 'display_name': 'Name',
+ 'links': {
+ 'project': 1234,
+ }
+ }
+ },
+ etag=None,
+ )
| Cannot create and save new subject set since 1.1
This [script](https://github.com/miclaraia/muon_analysis/blob/master/muon/scripts/test_panoptes_connection.py) illustrates the problem. The script fails on `subject_set.save()`. Mimics the instructions in the tutorial detailed in the [docs](https://panoptes-python-client.readthedocs.io/en/v1.1/user_guide.html#tutorial-creating-a-new-project).
Tries to get a project, create a subject set, link the subject set to the project, then save the subject set. The following trace is shown on `subject_set.save()`:
```
File "test_panoptes_connection.py", line 23, in main
subject_set.save()
File ".../venv/lib/python3.6/site-packages/panoptes_client/panoptes.py", line 815, in save
etag=self.etag
File ".../venv/lib/python3.6/site-packages/panoptes_client/panoptes.py", line 404, in post
retry=retry,
File ".../venv/lib/python3.6/site-packages/panoptes_client/panoptes.py", line 281, in json_request
json_response['errors']
panoptes_client.panoptes.PanoptesAPIException: {"schema"=>"did not contain a required property of 'links'"}
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"panoptes_client/tests/test_linkresolver.py::TestLinkResolver::test_set_new_link",
"panoptes_client/tests/test_subject_set.py::TestSubjectSet::test_create"
] | [] | {
"failed_lite_validators": [
"has_hyperlinks"
],
"has_test_patch": true,
"is_lite": false
} | "2019-02-22T16:58:26Z" | apache-2.0 |
|
zooniverse__panoptes-python-client-55 | diff --git a/panoptes_client/project.py b/panoptes_client/project.py
index fa67fd1..807d3b7 100644
--- a/panoptes_client/project.py
+++ b/panoptes_client/project.py
@@ -30,7 +30,12 @@ class Project(PanoptesObject):
def find(cls, id='', slug=None):
if not id and not slug:
return None
- return cls.where(id=id, slug=slug).next()
+ try:
+ return cls.where(id=id, slug=slug).next()
+ except StopIteration:
+ raise PanoptesAPIException(
+ "Could not find project with slug='{}'".format(slug)
+ )
def get_export(
self,
| zooniverse/panoptes-python-client | 6be958cc842488e5410814910febd6e71b14d7b0 | diff --git a/panoptes_client/tests/test_project.py b/panoptes_client/tests/test_project.py
index d900b75..14effae 100644
--- a/panoptes_client/tests/test_project.py
+++ b/panoptes_client/tests/test_project.py
@@ -1,6 +1,7 @@
import unittest
from panoptes_client import Project
+from panoptes_client.panoptes import PanoptesAPIException
class TestProject(unittest.TestCase):
@@ -17,5 +18,5 @@ class TestProject(unittest.TestCase):
self.assertEqual(p, None)
def test_find_unknown_slug(self):
- with self.assertRaises(StopIteration):
+ with self.assertRaises(PanoptesAPIException):
Project.find(slug='invalid_slug')
| Raise something better than StopIteration in .find() when nothing is found
https://github.com/zooniverse/panoptes-python-client/blob/67e11e16cd91689e62939a6ba54ff7769259a525/panoptes_client/panoptes.py#L428 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"panoptes_client/tests/test_project.py::TestProject::test_find_unknown_slug"
] | [
"panoptes_client/tests/test_project.py::TestProject::test_find_slug",
"panoptes_client/tests/test_project.py::TestProject::test_find_unknown_id"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2016-10-27T10:58:20Z" | apache-2.0 |
|
zopefoundation__AccessControl-70 | diff --git a/CHANGES.rst b/CHANGES.rst
index 1a303e9..bc80423 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -6,7 +6,8 @@ For changes before version 3.0, see ``HISTORY.rst``.
4.0b6 (unreleased)
------------------
-- Nothing changed yet.
+- Fix deprecation warnings for Python 3 and
+ change visibility of `buildfacade` to public. (#68, #69, #70)
4.0b5 (2018-10-05)
diff --git a/src/AccessControl/requestmethod.py b/src/AccessControl/requestmethod.py
index 18d063a..f9e537e 100644
--- a/src/AccessControl/requestmethod.py
+++ b/src/AccessControl/requestmethod.py
@@ -25,7 +25,7 @@ else: # Python 2
_default = []
-def _buildFacade(name, method, docstring):
+def buildfacade(name, method, docstring):
"""Build a facade function, matching the decorated method in signature.
Note that defaults are replaced by _default, and _curried will reconstruct
@@ -34,13 +34,14 @@ def _buildFacade(name, method, docstring):
"""
sig = signature(method)
args = []
+ callargs = []
for v in sig.parameters.values():
- argstr = str(v)
+ parts = str(v).split('=')
args.append(
- argstr if '=' not in argstr else '{}=_default'.format(v.name))
- callargs = ', '.join(sig.parameters.keys())
+ parts[0] if len(parts) == 1 else '{}=_default'.format(parts[0]))
+ callargs.append(parts[0])
return 'def %s(%s):\n """%s"""\n return _curried(%s)' % (
- name, ', '.join(args), docstring, callargs)
+ name, ', '.join(args), docstring, ', '.join(callargs))
def requestmethod(*methods):
@@ -86,7 +87,7 @@ def requestmethod(*methods):
# Build a facade, with a reference to our locally-scoped _curried
name = callable.__name__
facade_globs = dict(_curried=_curried, _default=_default)
- exec(_buildFacade(name, callable, callable.__doc__), facade_globs)
+ exec(buildfacade(name, callable, callable.__doc__), facade_globs)
return facade_globs[name]
return _methodtest
| zopefoundation/AccessControl | 605ec75772f6579e52380106ba0d333d9b97d866 | diff --git a/src/AccessControl/tests/test_requestmethod.py b/src/AccessControl/tests/test_requestmethod.py
index 910b22b..9971065 100644
--- a/src/AccessControl/tests/test_requestmethod.py
+++ b/src/AccessControl/tests/test_requestmethod.py
@@ -13,6 +13,7 @@
from AccessControl.requestmethod import requestmethod
from AccessControl.requestmethod import getfullargspec
+from AccessControl.requestmethod import buildfacade
from zope.interface import implementer
from zope.publisher.interfaces.browser import IBrowserRequest
import unittest
@@ -84,7 +85,6 @@ class RequestMethodDecoratorsTests(unittest.TestCase):
# variables against callable signatures, the result of the decorator
# must match the original closely, and keyword parameter defaults must
# be preserved:
- import inspect
mutabledefault = dict()
@requestmethod('POST')
@@ -121,3 +121,16 @@ class RequestMethodDecoratorsTests(unittest.TestCase):
foo('spam', POST)
self.assertEqual('Request must be GET, HEAD or PROPFIND',
str(err.exception))
+
+ def test_facade_render_correct_args_kwargs(self):
+ """ s. https://github.com/zopefoundation/AccessControl/issues/69
+ """
+ def foo(bar, baz, *args, **kwargs):
+ """foo doc"""
+ return baz
+ got = buildfacade('foo', foo, foo.__doc__)
+ expected = '\n'.join([
+ 'def foo(bar, baz, *args, **kwargs):',
+ ' """foo doc"""',
+ ' return _curried(bar, baz, *args, **kwargs)'])
+ self.assertEqual(expected, got)
| postonly drops kwargs
https://github.com/zopefoundation/AccessControl/pull/68 broke the behavior of the postonly-decorator.
E.g. `plone.api.group.create()` fails because the `kwargs` are dropped in `Products.PlonePAS.tools.groups.GroupsTool.addGroup` that is decorated. For failing tests sdee https://jenkins.plone.org/view/PLIPs/job/plip-py3/882/consoleText | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/AccessControl/tests/test_requestmethod.py::RequestMethodDecoratorsTests::test_REQUEST_parameter_is_a_requirement",
"src/AccessControl/tests/test_requestmethod.py::RequestMethodDecoratorsTests::test_allows_multiple_request_methods",
"src/AccessControl/tests/test_requestmethod.py::RequestMethodDecoratorsTests::test_can_be_used_for_any_request_method",
"src/AccessControl/tests/test_requestmethod.py::RequestMethodDecoratorsTests::test_facade_render_correct_args_kwargs",
"src/AccessControl/tests/test_requestmethod.py::RequestMethodDecoratorsTests::test_it_does_not_matter_if_REQUEST_is_positional_or_keyword_arg",
"src/AccessControl/tests/test_requestmethod.py::RequestMethodDecoratorsTests::test_preserves_keyword_parameter_defaults",
"src/AccessControl/tests/test_requestmethod.py::RequestMethodDecoratorsTests::test_requires_the_defined_HTTP_mehtod"
] | [] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2018-10-07T10:06:01Z" | zpl-2.1 |
|
zopefoundation__AccessControl-90 | diff --git a/CHANGES.rst b/CHANGES.rst
index 8dcf866..874cf62 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -6,7 +6,8 @@ For changes before version 3.0, see ``HISTORY.rst``.
4.1 (unreleased)
----------------
-- Nothing changed yet.
+- PY3: allow iteration over the result of ``dict.{keys,values,items}``
+ (`#89 <https://github.com/zopefoundation/AccessControl/issues/89>`_).
4.0 (2019-05-08)
diff --git a/src/AccessControl/ZopeGuards.py b/src/AccessControl/ZopeGuards.py
index 5cf0e4c..34643af 100644
--- a/src/AccessControl/ZopeGuards.py
+++ b/src/AccessControl/ZopeGuards.py
@@ -34,6 +34,7 @@ from AccessControl.SecurityInfo import secureModule
from AccessControl.SecurityManagement import getSecurityManager
from AccessControl.SimpleObjectPolicies import ContainerAssertions
from AccessControl.SimpleObjectPolicies import Containers
+from AccessControl.SimpleObjectPolicies import allow_type
_marker = [] # Create a new marker object.
@@ -196,6 +197,13 @@ def _check_dict_access(name, value):
ContainerAssertions[type({})] = _check_dict_access
+if six.PY3:
+ # Allow iteration over the result of `dict.{keys, values, items}`
+ d = {}
+ for attr in ("keys", "values", "items"):
+ allow_type(type(getattr(d, attr)()))
+
+
_list_white_list = {
'append': 1,
'count': 1,
| zopefoundation/AccessControl | 099c03fb5bcb7e3cf8e9f3f959a1a30508cd5422 | diff --git a/src/AccessControl/tests/testZopeGuards.py b/src/AccessControl/tests/testZopeGuards.py
index 20bd41f..24c933c 100644
--- a/src/AccessControl/tests/testZopeGuards.py
+++ b/src/AccessControl/tests/testZopeGuards.py
@@ -355,6 +355,14 @@ class TestDictGuards(GuardTestCase):
self.setSecurityManager(old)
self.assertTrue(sm.calls)
+ def test_kvi_iteration(self):
+ from AccessControl.ZopeGuards import SafeIter
+ d = dict(a=1, b=2)
+ for attr in ("keys", "values", "items"):
+ v = getattr(d, attr)()
+ si = SafeIter(v)
+ self.assertEqual(next(si), next(iter(v)))
+
class TestListGuards(GuardTestCase):
| PY3: "ZopeGuards" forgets to allow iteration over the result of "dict.{keys,values,items}"
Under Python 3, the `next`s in the following code all result in an `AccessControl.unauthorized.Unauthorized: You are not allowed to access 'a particular tuple' in this context`:
```
from AccessControl.ZopeGuards import SafeIter, Containers
d={1:1, 2:2}
i=SafeIter(d.items())
next(i)
ik=SafeIter(d.keys())
next(ik)
iv=SafeIter(d.values())
next(iv)
```
This is the cause of https://github.com/zopefoundation/Products.PythonScripts/issues/35. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/AccessControl/tests/testZopeGuards.py::TestDictGuards::test_kvi_iteration"
] | [
"src/AccessControl/tests/testZopeGuards.py::TestGuardedGetattr::test_attr_handler_table",
"src/AccessControl/tests/testZopeGuards.py::TestGuardedGetattr::test_calls_validate_for_unknown_type",
"src/AccessControl/tests/testZopeGuards.py::TestGuardedGetattr::test_miss",
"src/AccessControl/tests/testZopeGuards.py::TestGuardedGetattr::test_simple_object_policies",
"src/AccessControl/tests/testZopeGuards.py::TestGuardedGetattr::test_unauthorized",
"src/AccessControl/tests/testZopeGuards.py::TestGuardedGetattr::test_unhashable_key",
"src/AccessControl/tests/testZopeGuards.py::TestGuardedHasattr::test_hit",
"src/AccessControl/tests/testZopeGuards.py::TestGuardedHasattr::test_miss",
"src/AccessControl/tests/testZopeGuards.py::TestGuardedHasattr::test_unauthorized",
"src/AccessControl/tests/testZopeGuards.py::TestGuardedHasattr::test_unhashable_key",
"src/AccessControl/tests/testZopeGuards.py::TestDictGuards::test_get_default",
"src/AccessControl/tests/testZopeGuards.py::TestDictGuards::test_get_simple",
"src/AccessControl/tests/testZopeGuards.py::TestDictGuards::test_get_validates",
"src/AccessControl/tests/testZopeGuards.py::TestDictGuards::test_keys_empty",
"src/AccessControl/tests/testZopeGuards.py::TestDictGuards::test_keys_validates",
"src/AccessControl/tests/testZopeGuards.py::TestDictGuards::test_pop_default",
"src/AccessControl/tests/testZopeGuards.py::TestDictGuards::test_pop_raises",
"src/AccessControl/tests/testZopeGuards.py::TestDictGuards::test_pop_simple",
"src/AccessControl/tests/testZopeGuards.py::TestDictGuards::test_pop_validates",
"src/AccessControl/tests/testZopeGuards.py::TestDictGuards::test_values_empty",
"src/AccessControl/tests/testZopeGuards.py::TestDictGuards::test_values_validates",
"src/AccessControl/tests/testZopeGuards.py::TestListGuards::test_pop_raises",
"src/AccessControl/tests/testZopeGuards.py::TestListGuards::test_pop_simple",
"src/AccessControl/tests/testZopeGuards.py::TestListGuards::test_pop_validates",
"src/AccessControl/tests/testZopeGuards.py::TestBuiltinFunctionGuards::test_all_fails",
"src/AccessControl/tests/testZopeGuards.py::TestBuiltinFunctionGuards::test_all_succeeds",
"src/AccessControl/tests/testZopeGuards.py::TestBuiltinFunctionGuards::test_any_fails",
"src/AccessControl/tests/testZopeGuards.py::TestBuiltinFunctionGuards::test_any_succeeds",
"src/AccessControl/tests/testZopeGuards.py::TestBuiltinFunctionGuards::test_apply",
"src/AccessControl/tests/testZopeGuards.py::TestBuiltinFunctionGuards::test_enumerate_fails",
"src/AccessControl/tests/testZopeGuards.py::TestBuiltinFunctionGuards::test_enumerate_succeeds",
"src/AccessControl/tests/testZopeGuards.py::TestBuiltinFunctionGuards::test_map_fails",
"src/AccessControl/tests/testZopeGuards.py::TestBuiltinFunctionGuards::test_map_succeeds",
"src/AccessControl/tests/testZopeGuards.py::TestBuiltinFunctionGuards::test_max_fails",
"src/AccessControl/tests/testZopeGuards.py::TestBuiltinFunctionGuards::test_max_succeeds",
"src/AccessControl/tests/testZopeGuards.py::TestBuiltinFunctionGuards::test_min_fails",
"src/AccessControl/tests/testZopeGuards.py::TestBuiltinFunctionGuards::test_min_succeeds",
"src/AccessControl/tests/testZopeGuards.py::TestBuiltinFunctionGuards::test_sum_fails",
"src/AccessControl/tests/testZopeGuards.py::TestBuiltinFunctionGuards::test_sum_succeeds",
"src/AccessControl/tests/testZopeGuards.py::TestBuiltinFunctionGuards::test_zip_fails",
"src/AccessControl/tests/testZopeGuards.py::TestBuiltinFunctionGuards::test_zip_succeeds",
"src/AccessControl/tests/testZopeGuards.py::TestGuardedDictListTypes::testDictCreation",
"src/AccessControl/tests/testZopeGuards.py::TestGuardedDictListTypes::testListCreation",
"src/AccessControl/tests/testZopeGuards.py::TestRestrictedPythonApply::test_apply",
"src/AccessControl/tests/testZopeGuards.py::TestActualPython::testPython",
"src/AccessControl/tests/testZopeGuards.py::TestActualPython::testPythonRealAC",
"src/AccessControl/tests/testZopeGuards.py::TestActualPython::test_derived_class_normal",
"src/AccessControl/tests/testZopeGuards.py::TestActualPython::test_derived_class_sneaky_en_suite",
"src/AccessControl/tests/testZopeGuards.py::TestActualPython::test_derived_sneaky_instance",
"src/AccessControl/tests/testZopeGuards.py::TestActualPython::test_derived_sneaky_post_facto",
"src/AccessControl/tests/testZopeGuards.py::TestActualPython::test_dict_access",
"src/AccessControl/tests/testZopeGuards.py::TestActualPython::test_guarded_next__1",
"src/AccessControl/tests/testZopeGuards.py::TestActualPython::test_guarded_next__2",
"src/AccessControl/tests/testZopeGuards.py::TestActualPython::test_guarded_next__3",
"src/AccessControl/tests/testZopeGuards.py::test_inplacevar",
"src/AccessControl/tests/testZopeGuards.py::test_inplacevar_for_py24",
"src/AccessControl/tests/testZopeGuards.py::test_suite"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2019-07-11T06:59:46Z" | zpl-2.1 |
|
zopefoundation__Acquisition-54 | diff --git a/CHANGES.rst b/CHANGES.rst
index c0226e2..d7ed057 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -4,7 +4,9 @@ Changelog
4.9 (unreleased)
----------------
-- Nothing changed yet.
+- On CPython no longer omit compiling the C code when ``PURE_PYTHON`` is
+ required. Just evaluate it at runtime.
+ (`#53 <https://github.com/zopefoundation/Acquisition/issues/53>`_)
4.8 (2021-07-20)
diff --git a/setup.py b/setup.py
index 4ab4ed7..0de7c4f 100644
--- a/setup.py
+++ b/setup.py
@@ -26,8 +26,7 @@ with open('CHANGES.rst') as f:
# PyPy won't build the extension.
py_impl = getattr(platform, 'python_implementation', lambda: None)
is_pypy = py_impl() == 'PyPy'
-is_pure = 'PURE_PYTHON' in os.environ
-if is_pypy or is_pure:
+if is_pypy:
ext_modules = []
else:
ext_modules = [
@@ -53,7 +52,9 @@ setup(
classifiers=[
"Development Status :: 6 - Mature",
"Environment :: Web Environment",
- "Framework :: Zope2",
+ "Framework :: Zope :: 2",
+ "Framework :: Zope :: 4",
+ "Framework :: Zope :: 5",
"License :: OSI Approved :: Zope Public License",
"Operating System :: OS Independent",
"Programming Language :: Python",
diff --git a/src/Acquisition/__init__.py b/src/Acquisition/__init__.py
index d82f6b7..6a23ffa 100644
--- a/src/Acquisition/__init__.py
+++ b/src/Acquisition/__init__.py
@@ -4,7 +4,6 @@ from __future__ import absolute_import, print_function
import os
-import operator
import platform
import sys
import types
@@ -18,12 +17,9 @@ from .interfaces import IAcquirer
from .interfaces import IAcquisitionWrapper
IS_PYPY = getattr(platform, 'python_implementation', lambda: None)() == 'PyPy'
-IS_PURE = 'PURE_PYTHON' in os.environ
-
-
+IS_PURE = int(os.environ.get('PURE_PYTHON', '0'))
+CAPI = not (IS_PYPY or IS_PURE)
Acquired = "<Special Object Used to Force Acquisition>"
-
-
_NOT_FOUND = object() # marker
###
@@ -917,7 +913,7 @@ def aq_inContextOf(self, o, inner=True):
return False
-if not (IS_PYPY or IS_PURE): # pragma: no cover
+if CAPI: # pragma: no cover
# Make sure we can import the C extension of our dependency.
from ExtensionClass import _ExtensionClass # NOQA
from ._Acquisition import * # NOQA
| zopefoundation/Acquisition | 448a2c72009069de54c6102e85c00d946b7a45a9 | diff --git a/src/Acquisition/tests.py b/src/Acquisition/tests.py
index af70b8d..aa96acc 100644
--- a/src/Acquisition/tests.py
+++ b/src/Acquisition/tests.py
@@ -35,6 +35,7 @@ from Acquisition import ( # NOQA
aq_self,
Explicit,
Implicit,
+ CAPI,
IS_PYPY,
IS_PURE,
_Wrapper,
@@ -3282,18 +3283,15 @@ class TestProxying(unittest.TestCase):
self.assertEqual(base.derived(1, k=2), (42, 1, 2))
- if not IS_PYPY:
- # XXX: This test causes certain versions
- # of PyPy to segfault (at least 2.6.0-alpha1)
- class NotCallable(base_class):
- pass
+ class NotCallable(base_class):
+ pass
- base.derived = NotCallable()
- try:
- base.derived()
- self.fail("Not callable")
- except (TypeError, AttributeError):
- pass
+ base.derived = NotCallable()
+ try:
+ base.derived()
+ self.fail("Not callable")
+ except (TypeError, AttributeError):
+ pass
def test_implicit_proxy_call(self):
self._check_call()
@@ -3416,19 +3414,18 @@ class TestProxying(unittest.TestCase):
class TestCompilation(unittest.TestCase):
- def test_compile(self):
- if IS_PYPY or IS_PURE:
- # the test wants to verify that in a Python only
- # setup, the C extension is not generated.
- # However, for efficiency reasons, the tests are usually
- # run in a shared environment, and the test would fail
- # as the C extension is available
- pass
-## with self.assertRaises((AttributeError, ImportError)):
-## from Acquisition import _Acquisition
- else:
+ def test_compilation(self):
+ self.assertEqual(CAPI, not (IS_PYPY or IS_PURE))
+ try:
from Acquisition import _Acquisition
+ cExplicit = _Acquisition.Explicit
+ except ImportError:
+ cExplicit = None # PyPy never has a C module.
+ if CAPI: # pragma: no cover
self.assertTrue(hasattr(_Acquisition, 'AcquisitionCAPI'))
+ self.assertEqual(Explicit, cExplicit)
+ else:
+ self.assertNotEqual(Explicit, cExplicit)
def test_suite():
| Stop checking PURE_PYTHON at build (setup.py) time
This leads to incorrect wheel building. (See https://github.com/zopefoundation/Persistence/issues/27)
Additionally https://github.com/zopefoundation/Acquisition/pull/52/commits/d91643f0d75a7c3ec76e9fe974417beb9d1086e1 could be fixed like https://github.com/zopefoundation/Persistence/pull/26/commits/6645417c325798c7ed04d271626c3936f8b3750a | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/Acquisition/tests.py::TestStory::test_story",
"src/Acquisition/tests.py::test_unwrapped",
"src/Acquisition/tests.py::test_simple",
"src/Acquisition/tests.py::test_muliple",
"src/Acquisition/tests.py::test_pinball",
"src/Acquisition/tests.py::test_explicit",
"src/Acquisition/tests.py::test_mixed_explicit_and_explicit",
"src/Acquisition/tests.py::TestAqAlgorithm::test_AqAlg",
"src/Acquisition/tests.py::TestExplicitAcquisition::test_explicit_acquisition",
"src/Acquisition/tests.py::TestCreatingWrappers::test_creating_wrappers_directly",
"src/Acquisition/tests.py::TestPickle::test_cant_persist_acquisition_wrappers_classic",
"src/Acquisition/tests.py::TestPickle::test_cant_persist_acquisition_wrappers_newstyle",
"src/Acquisition/tests.py::TestPickle::test_cant_pickle_acquisition_wrappers_classic",
"src/Acquisition/tests.py::TestPickle::test_cant_pickle_acquisition_wrappers_newstyle",
"src/Acquisition/tests.py::TestInterfaces::test_interfaces",
"src/Acquisition/tests.py::TestMixin::test_mixin_base",
"src/Acquisition/tests.py::TestMixin::test_mixin_post_class_definition",
"src/Acquisition/tests.py::TestGC::test_Basic_gc",
"src/Acquisition/tests.py::TestGC::test_Wrapper_gc",
"src/Acquisition/tests.py::test_container_proxying",
"src/Acquisition/tests.py::TestAqParentParentInteraction::test___parent__no_wrappers",
"src/Acquisition/tests.py::TestAqParentParentInteraction::test_explicit_wrapper_as___parent__",
"src/Acquisition/tests.py::TestAqParentParentInteraction::test_explicit_wrapper_has_nonwrapper_as_aq_parent",
"src/Acquisition/tests.py::TestAqParentParentInteraction::test_implicit_wrapper_as___parent__",
"src/Acquisition/tests.py::TestAqParentParentInteraction::test_implicit_wrapper_has_nonwrapper_as_aq_parent",
"src/Acquisition/tests.py::TestParentCircles::test___parent__aq_parent_circles",
"src/Acquisition/tests.py::TestParentCircles::test_unwrapped_implicit_acquirer_unwraps__parent__",
"src/Acquisition/tests.py::TestBugs::test__cmp__",
"src/Acquisition/tests.py::TestBugs::test__iter__after_AttributeError",
"src/Acquisition/tests.py::TestBugs::test_bool",
"src/Acquisition/tests.py::TestBugs::test_wrapped_attr",
"src/Acquisition/tests.py::TestSpecialNames::test_special_names",
"src/Acquisition/tests.py::TestWrapper::test_AttributeError_if_object_has_no__bytes__",
"src/Acquisition/tests.py::TestWrapper::test__bytes__is_correcty_wrapped",
"src/Acquisition/tests.py::TestWrapper::test__cmp__is_called_on_wrapped_object",
"src/Acquisition/tests.py::TestWrapper::test_cannot_set_attributes_on_empty_wrappers",
"src/Acquisition/tests.py::TestWrapper::test_deleting_parent_attrs",
"src/Acquisition/tests.py::TestWrapper::test_getitem_setitem_implemented",
"src/Acquisition/tests.py::TestWrapper::test_getitem_setitem_not_implemented",
"src/Acquisition/tests.py::TestWrapper::test_wrapped_methods_have_correct_self",
"src/Acquisition/tests.py::TestWrapper::test_wrapped_objects_are_unwrapped_on_set",
"src/Acquisition/tests.py::TestOf::test__of__exception",
"src/Acquisition/tests.py::TestOf::test_wrapper_calls_of_on_non_wrapper",
"src/Acquisition/tests.py::TestAQInContextOf::test_aq_inContextOf",
"src/Acquisition/tests.py::TestAQInContextOf::test_aq_inContextOf_odd_cases",
"src/Acquisition/tests.py::TestCircles::test_parent_parent_circles",
"src/Acquisition/tests.py::TestCircles::test_parent_parent_parent_circles",
"src/Acquisition/tests.py::TestCircles::test_search_repeated_objects",
"src/Acquisition/tests.py::TestAcquire::test_explicit_module_default",
"src/Acquisition/tests.py::TestAcquire::test_explicit_module_false",
"src/Acquisition/tests.py::TestAcquire::test_explicit_module_true",
"src/Acquisition/tests.py::TestAcquire::test_explicit_wrapper_default",
"src/Acquisition/tests.py::TestAcquire::test_explicit_wrapper_false",
"src/Acquisition/tests.py::TestAcquire::test_explicit_wrapper_true",
"src/Acquisition/tests.py::TestAcquire::test_no_wrapper_but___parent___falls_back_to_default",
"src/Acquisition/tests.py::TestAcquire::test_unwrapped_falls_back_to_default",
"src/Acquisition/tests.py::TestAcquire::test_w_unicode_attr_name",
"src/Acquisition/tests.py::TestAcquire::test_wrapper_falls_back_to_default",
"src/Acquisition/tests.py::TestCooperativeBase::test_explicit___getattribute__is_cooperative",
"src/Acquisition/tests.py::TestCooperativeBase::test_implicit___getattribute__is_cooperative",
"src/Acquisition/tests.py::TestUnicode::test_explicit_aq_unicode_should_be_called",
"src/Acquisition/tests.py::TestUnicode::test_explicit_should_fall_back_to_str",
"src/Acquisition/tests.py::TestUnicode::test_implicit_aq_unicode_should_be_called",
"src/Acquisition/tests.py::TestUnicode::test_implicit_should_fall_back_to_str",
"src/Acquisition/tests.py::TestUnicode::test_str_fallback_should_be_called_with_wrapped_self",
"src/Acquisition/tests.py::TestUnicode::test_unicode_should_be_called_with_wrapped_self",
"src/Acquisition/tests.py::TestProxying::test_explicit_proxy_bool",
"src/Acquisition/tests.py::TestProxying::test_explicit_proxy_call",
"src/Acquisition/tests.py::TestProxying::test_explicit_proxy_comporison",
"src/Acquisition/tests.py::TestProxying::test_explicit_proxy_contains",
"src/Acquisition/tests.py::TestProxying::test_explicit_proxy_hash",
"src/Acquisition/tests.py::TestProxying::test_explicit_proxy_special_meths",
"src/Acquisition/tests.py::TestProxying::test_implicit_proxy_bool",
"src/Acquisition/tests.py::TestProxying::test_implicit_proxy_call",
"src/Acquisition/tests.py::TestProxying::test_implicit_proxy_comporison",
"src/Acquisition/tests.py::TestProxying::test_implicit_proxy_contains",
"src/Acquisition/tests.py::TestProxying::test_implicit_proxy_hash",
"src/Acquisition/tests.py::TestProxying::test_implicit_proxy_special_meths",
"src/Acquisition/tests.py::TestCompilation::test_compilation",
"src/Acquisition/tests.py::test_suite"
] | [] | {
"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
} | "2021-07-23T06:15:09Z" | zpl-2.1 |
|
zopefoundation__BTrees-43 | diff --git a/BTrees/BTreeTemplate.c b/BTrees/BTreeTemplate.c
index 42d2880..ce77853 100644
--- a/BTrees/BTreeTemplate.c
+++ b/BTrees/BTreeTemplate.c
@@ -219,6 +219,8 @@ BTree_check(BTree *self)
return result;
}
+#define _BGET_REPLACE_TYPE_ERROR 1
+#define _BGET_ALLOW_TYPE_ERROR 0
/*
** _BTree_get
**
@@ -229,6 +231,14 @@ BTree_check(BTree *self)
** keyarg the key to search for, as a Python object
** has_key true/false; when false, try to return the associated
** value; when true, return a boolean
+** replace_type_err true/false: When true, ignore the TypeError from
+** a key conversion issue, instead
+** transforming it into a KeyError set. If
+** you are just reading/searching, set to
+** true. If you will be adding/updating,
+** however, set to false. Or use
+** _BGET_REPLACE_TYPE_ERROR
+** and _BGET_ALLOW_TYPE_ERROR, respectively.
** Return
** When has_key false:
** If key exists, its associated value.
@@ -239,14 +249,22 @@ BTree_check(BTree *self)
** If key doesn't exist, 0.
*/
static PyObject *
-_BTree_get(BTree *self, PyObject *keyarg, int has_key)
+_BTree_get(BTree *self, PyObject *keyarg, int has_key, int replace_type_err)
{
KEY_TYPE key;
PyObject *result = NULL; /* guilty until proved innocent */
int copied = 1;
COPY_KEY_FROM_ARG(key, keyarg, copied);
- UNLESS (copied) return NULL;
+ UNLESS (copied)
+ {
+ if (replace_type_err && PyErr_ExceptionMatches(PyExc_TypeError))
+ {
+ PyErr_Clear();
+ PyErr_SetObject(PyExc_KeyError, keyarg);
+ }
+ return NULL;
+ }
PER_USE_OR_RETURN(self, NULL);
if (self->len == 0)
@@ -289,7 +307,7 @@ Done:
static PyObject *
BTree_get(BTree *self, PyObject *key)
{
- return _BTree_get(self, key, 0);
+ return _BTree_get(self, key, 0, _BGET_REPLACE_TYPE_ERROR);
}
/* Create a new bucket for the BTree or TreeSet using the class attribute
@@ -1940,7 +1958,7 @@ BTree_getm(BTree *self, PyObject *args)
UNLESS (PyArg_ParseTuple(args, "O|O", &key, &d))
return NULL;
- if ((r=_BTree_get(self, key, 0)))
+ if ((r=_BTree_get(self, key, 0, _BGET_REPLACE_TYPE_ERROR)))
return r;
UNLESS (PyErr_ExceptionMatches(PyExc_KeyError))
return NULL;
@@ -1952,7 +1970,7 @@ BTree_getm(BTree *self, PyObject *args)
static PyObject *
BTree_has_key(BTree *self, PyObject *key)
{
- return _BTree_get(self, key, 1);
+ return _BTree_get(self, key, 1, _BGET_REPLACE_TYPE_ERROR);
}
static PyObject *
@@ -1965,7 +1983,7 @@ BTree_setdefault(BTree *self, PyObject *args)
if (! PyArg_UnpackTuple(args, "setdefault", 2, 2, &key, &failobj))
return NULL;
- value = _BTree_get(self, key, 0);
+ value = _BTree_get(self, key, 0, _BGET_ALLOW_TYPE_ERROR);
if (value != NULL)
return value;
@@ -1998,7 +2016,7 @@ BTree_pop(BTree *self, PyObject *args)
if (! PyArg_UnpackTuple(args, "pop", 1, 2, &key, &failobj))
return NULL;
- value = _BTree_get(self, key, 0);
+ value = _BTree_get(self, key, 0, _BGET_ALLOW_TYPE_ERROR);
if (value != NULL)
{
/* Delete key and associated value. */
@@ -2043,7 +2061,7 @@ BTree_pop(BTree *self, PyObject *args)
static int
BTree_contains(BTree *self, PyObject *key)
{
- PyObject *asobj = _BTree_get(self, key, 1);
+ PyObject *asobj = _BTree_get(self, key, 1, _BGET_REPLACE_TYPE_ERROR);
int result = -1;
if (asobj != NULL)
@@ -2051,6 +2069,11 @@ BTree_contains(BTree *self, PyObject *key)
result = INT_AS_LONG(asobj) ? 1 : 0;
Py_DECREF(asobj);
}
+ else if (PyErr_ExceptionMatches(PyExc_KeyError))
+ {
+ PyErr_Clear();
+ result = 0;
+ }
return result;
}
diff --git a/BTrees/_base.py b/BTrees/_base.py
index 07498a3..3158d91 100644
--- a/BTrees/_base.py
+++ b/BTrees/_base.py
@@ -269,7 +269,7 @@ def _no_default_comparison(key):
lt = None # pragma: no cover PyPy3
if (lt is None and
getattr(key, '__cmp__', None) is None):
- raise TypeError("Can't use default __cmp__")
+ raise TypeError("Object has default comparison")
class Bucket(_BucketBase):
@@ -863,7 +863,12 @@ class _Tree(_Base):
return child._findbucket(key)
def __contains__(self, key):
- return key in (self._findbucket(self._to_key(key)) or ())
+ try:
+ tree_key = self._to_key(key)
+ except TypeError:
+ # Can't convert the key, so can't possibly be in the tree
+ return False
+ return key in (self._findbucket(tree_key) or ())
def has_key(self, key):
index = self._search(key)
diff --git a/CHANGES.rst b/CHANGES.rst
index ac79910..834fbfb 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -4,7 +4,19 @@
4.3.2 (unreleased)
------------------
-- TBD
+- Make the CPython implementation consistent with the pure-Python
+ implementation and no longer raise ``TypeError`` for an object key
+ (in object-keyed trees) with default comparison on ``__getitem__``,
+ ``get`` or ``in`` operations. Instead, the results will be a
+ ``KeyError``, the default value, and ``False``, respectively.
+ Previously, CPython raised a ``TypeError`` in those cases, while the
+ Python implementation behaved as specified.
+
+ Likewise, non-integer keys in integer-keyed trees
+ will raise ``KeyError``, return the default and return ``False``,
+ respectively, in both implementations. Previously, pure-Python
+ raised a ``KeyError``, returned the default, and raised a
+ ``TypeError``, while CPython raised ``TypeError`` in all three cases.
4.3.1 (2016-05-16)
------------------
@@ -21,7 +33,7 @@
- When testing ``PURE_PYTHON`` environments under ``tox``, avoid poisoning
the user's global wheel cache.
-- Ensure that he pure-Python implementation, used on PyPy and when a C
+- Ensure that the pure-Python implementation, used on PyPy and when a C
compiler isn't available for CPython, pickles identically to the C
version. Unpickling will choose the best available implementation.
This change prevents interoperability problems and database corruption if
| zopefoundation/BTrees | be6e6ea7fed82058dc80874eea4813d73df06f3c | diff --git a/BTrees/tests/test_IOBTree.py b/BTrees/tests/test_IOBTree.py
index 2e2e25e..aa14c4a 100644
--- a/BTrees/tests/test_IOBTree.py
+++ b/BTrees/tests/test_IOBTree.py
@@ -143,6 +143,14 @@ class _TestIOBTreesBase(TypeTest):
def _noneraises(self):
self._makeOne()[None] = 1
+ def testStringAllowedInContains(self):
+ self.assertFalse('key' in self._makeOne())
+
+ def testStringKeyRaisesKeyErrorWhenMissing(self):
+ self.assertRaises(KeyError, self._makeOne().__getitem__, 'key')
+
+ def testStringKeyReturnsDefaultFromGetWhenMissing(self):
+ self.assertEqual(self._makeOne().get('key', 42), 42)
class TestIOBTrees(_TestIOBTreesBase, unittest.TestCase):
diff --git a/BTrees/tests/test_OOBTree.py b/BTrees/tests/test_OOBTree.py
index ffc5686..7152947 100644
--- a/BTrees/tests/test_OOBTree.py
+++ b/BTrees/tests/test_OOBTree.py
@@ -109,7 +109,7 @@ class OOBTreeTest(BTreeTests, unittest.TestCase):
self.assertEqual(list(tree.byValue(22)),
[(y, x) for x, y in reversed(ITEMS[22:])])
- def testRejectDefaultComparison(self):
+ def testRejectDefaultComparisonOnSet(self):
# Check that passing int keys w default comparison fails.
# Only applies to new-style class instances. Old-style
# instances are too hard to introspect.
@@ -126,6 +126,11 @@ class OOBTreeTest(BTreeTests, unittest.TestCase):
self.assertRaises(TypeError, lambda : t.__setitem__(C(), 1))
+ with self.assertRaises(TypeError) as raising:
+ t[C()] = 1
+
+ self.assertEqual(raising.exception.args[0], "Object has default comparison")
+
if PY2: # we only check for __cmp__ on Python2
class With___cmp__(object):
@@ -145,6 +150,15 @@ class OOBTreeTest(BTreeTests, unittest.TestCase):
t.clear()
+ def testAcceptDefaultComparisonOnGet(self):
+ # Issue #42
+ t = self._makeOne()
+ class C(object):
+ pass
+
+ self.assertEqual(t.get(C(), 42), 42)
+ self.assertRaises(KeyError, t.__getitem__, C())
+ self.assertFalse(C() in t)
class OOBTreePyTest(OOBTreeTest):
#
| BTree.get(object()) raises TypeError on CPython, returns default on PyPy
I ran into an implementation difference between the C version and the Python versions.
Here's PyPy:
```python
Python 2.7.10 (7e8df3df9641, Jun 14 2016, 13:30:54)
[PyPy 5.3.1 with GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>> import BTrees
>>>> BTrees.OOBTree.OOBTree().get(object())
>>>>
```
Here's CPython:
```python
Python 2.7.12 (default, Jul 11 2016, 16:16:26)
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import BTrees
>>> BTrees.OOBTree.OOBTree().get(object())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Object has default comparison
>>>
```
The specific type of object with default comparison doesn't really matter. And they both raise a TypeError if you try to set a key with default comparison (albeit with different error messages).
Which is the right behaviour here? I would argue that the Python behaviour is certainly nicer and friendlier to the user. It makes it easier to substitute a BTree for a dict in more places. In fact, on CPython, I had to subclass the BTree to be able to use it in place of a dict because of this TypeError (even though I had already made sure that we would never try to set such a value, sometimes we still query for them).
If there's consensus I can put together a PR to bring them into line. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"BTrees/tests/test_IOBTree.py::TestIOBTreesPy::testStringAllowedInContains",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testRejectDefaultComparisonOnSet"
] | [
"BTrees/tests/test_IOBTree.py::TestLongIntKeys::testLongIntKeysWork",
"BTrees/tests/test_IOBTree.py::TestLongIntKeys::testLongIntKeysOutOfRange",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testBadUpdateTupleSize",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testClear",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testDeleteInvalidKeyRaisesKeyError",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testEmptyRangeSearches",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testGetItemFails",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testGetReturnsDefault",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testHasKeyWorks",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testItemsNegativeIndex",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testItemsWorks",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testIterators",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testKeysNegativeIndex",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testKeysWorks",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testLen",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testMaxKeyMinKey",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testPop",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testRangedIterators",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testReplaceWorks",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testRepr",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testSetItemGetItemWorks",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testSetdefault",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testSetstateArgumentChecking",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testShortRepr",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testSimpleExclusivRanges",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testSimpleExclusiveKeyRange",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testSlicing",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testUpdate",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testUpdateFromPersistentMapping",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testValuesNegativeIndex",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testValuesWorks",
"BTrees/tests/test_IOBTree.py::IOBucketTest::testValuesWorks1",
"BTrees/tests/test_IOBTree.py::IOBucketTest::test_impl_pickle",
"BTrees/tests/test_IOBTree.py::IOBucketTest::test_isinstance_subclass",
"BTrees/tests/test_IOBTree.py::IOBucketTest::test_pickle_empty",
"BTrees/tests/test_IOBTree.py::IOBucketTest::test_pickle_subclass",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testBadUpdateTupleSize",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testClear",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testDeleteInvalidKeyRaisesKeyError",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testEmptyRangeSearches",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testGetItemFails",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testGetReturnsDefault",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testHasKeyWorks",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testItemsNegativeIndex",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testItemsWorks",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testIterators",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testKeysNegativeIndex",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testKeysWorks",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testLen",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testMaxKeyMinKey",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testPop",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testRangedIterators",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testReplaceWorks",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testRepr",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testSetItemGetItemWorks",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testSetdefault",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testSetstateArgumentChecking",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testShortRepr",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testSimpleExclusivRanges",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testSimpleExclusiveKeyRange",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testSlicing",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testUpdate",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testUpdateFromPersistentMapping",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testValuesNegativeIndex",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testValuesWorks",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::testValuesWorks1",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::test_impl_pickle",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::test_isinstance_subclass",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::test_pickle_empty",
"BTrees/tests/test_IOBTree.py::IOBucketPyTest::test_pickle_subclass",
"BTrees/tests/test_IOBTree.py::IOTreeSetTest::testAddingOneSetsChanged",
"BTrees/tests/test_IOBTree.py::IOTreeSetTest::testBigInsert",
"BTrees/tests/test_IOBTree.py::IOTreeSetTest::testClear",
"BTrees/tests/test_IOBTree.py::IOTreeSetTest::testDuplicateInsert",
"BTrees/tests/test_IOBTree.py::IOTreeSetTest::testEmptyRangeSearches",
"BTrees/tests/test_IOBTree.py::IOTreeSetTest::testHasKeyFails",
"BTrees/tests/test_IOBTree.py::IOTreeSetTest::testInsert",
"BTrees/tests/test_IOBTree.py::IOTreeSetTest::testInsertReturnsValue",
"BTrees/tests/test_IOBTree.py::IOTreeSetTest::testIterator",
"BTrees/tests/test_IOBTree.py::IOTreeSetTest::testKeys",
"BTrees/tests/test_IOBTree.py::IOTreeSetTest::testMaxKeyMinKey",
"BTrees/tests/test_IOBTree.py::IOTreeSetTest::testRemoveFails",
"BTrees/tests/test_IOBTree.py::IOTreeSetTest::testRemoveInSmallSetSetsChanged",
"BTrees/tests/test_IOBTree.py::IOTreeSetTest::testRemoveSucceeds",
"BTrees/tests/test_IOBTree.py::IOTreeSetTest::testSetstateArgumentChecking",
"BTrees/tests/test_IOBTree.py::IOTreeSetTest::testShortRepr",
"BTrees/tests/test_IOBTree.py::IOTreeSetTest::testSimpleExclusiveKeyRange",
"BTrees/tests/test_IOBTree.py::IOTreeSetTest::testSlicing",
"BTrees/tests/test_IOBTree.py::IOTreeSetTest::testUpdate",
"BTrees/tests/test_IOBTree.py::IOTreeSetTest::test_impl_pickle",
"BTrees/tests/test_IOBTree.py::IOTreeSetTest::test_isinstance_subclass",
"BTrees/tests/test_IOBTree.py::IOTreeSetTest::test_pickle_empty",
"BTrees/tests/test_IOBTree.py::IOTreeSetTest::test_pickle_subclass",
"BTrees/tests/test_IOBTree.py::IOTreeSetPyTest::testAddingOneSetsChanged",
"BTrees/tests/test_IOBTree.py::IOTreeSetPyTest::testBigInsert",
"BTrees/tests/test_IOBTree.py::IOTreeSetPyTest::testClear",
"BTrees/tests/test_IOBTree.py::IOTreeSetPyTest::testDuplicateInsert",
"BTrees/tests/test_IOBTree.py::IOTreeSetPyTest::testEmptyRangeSearches",
"BTrees/tests/test_IOBTree.py::IOTreeSetPyTest::testHasKeyFails",
"BTrees/tests/test_IOBTree.py::IOTreeSetPyTest::testInsert",
"BTrees/tests/test_IOBTree.py::IOTreeSetPyTest::testInsertReturnsValue",
"BTrees/tests/test_IOBTree.py::IOTreeSetPyTest::testIterator",
"BTrees/tests/test_IOBTree.py::IOTreeSetPyTest::testKeys",
"BTrees/tests/test_IOBTree.py::IOTreeSetPyTest::testMaxKeyMinKey",
"BTrees/tests/test_IOBTree.py::IOTreeSetPyTest::testRemoveFails",
"BTrees/tests/test_IOBTree.py::IOTreeSetPyTest::testRemoveInSmallSetSetsChanged",
"BTrees/tests/test_IOBTree.py::IOTreeSetPyTest::testRemoveSucceeds",
"BTrees/tests/test_IOBTree.py::IOTreeSetPyTest::testSetstateArgumentChecking",
"BTrees/tests/test_IOBTree.py::IOTreeSetPyTest::testShortRepr",
"BTrees/tests/test_IOBTree.py::IOTreeSetPyTest::testSimpleExclusiveKeyRange",
"BTrees/tests/test_IOBTree.py::IOTreeSetPyTest::testSlicing",
"BTrees/tests/test_IOBTree.py::IOTreeSetPyTest::testUpdate",
"BTrees/tests/test_IOBTree.py::IOTreeSetPyTest::test_impl_pickle",
"BTrees/tests/test_IOBTree.py::IOTreeSetPyTest::test_isinstance_subclass",
"BTrees/tests/test_IOBTree.py::IOTreeSetPyTest::test_pickle_empty",
"BTrees/tests/test_IOBTree.py::IOTreeSetPyTest::test_pickle_subclass",
"BTrees/tests/test_IOBTree.py::IOSetTest::testAddingOneSetsChanged",
"BTrees/tests/test_IOBTree.py::IOSetTest::testBigInsert",
"BTrees/tests/test_IOBTree.py::IOSetTest::testClear",
"BTrees/tests/test_IOBTree.py::IOSetTest::testDuplicateInsert",
"BTrees/tests/test_IOBTree.py::IOSetTest::testEmptyRangeSearches",
"BTrees/tests/test_IOBTree.py::IOSetTest::testGetItem",
"BTrees/tests/test_IOBTree.py::IOSetTest::testHasKeyFails",
"BTrees/tests/test_IOBTree.py::IOSetTest::testInsert",
"BTrees/tests/test_IOBTree.py::IOSetTest::testInsertReturnsValue",
"BTrees/tests/test_IOBTree.py::IOSetTest::testIterator",
"BTrees/tests/test_IOBTree.py::IOSetTest::testKeys",
"BTrees/tests/test_IOBTree.py::IOSetTest::testLen",
"BTrees/tests/test_IOBTree.py::IOSetTest::testMaxKeyMinKey",
"BTrees/tests/test_IOBTree.py::IOSetTest::testRemoveFails",
"BTrees/tests/test_IOBTree.py::IOSetTest::testRemoveInSmallSetSetsChanged",
"BTrees/tests/test_IOBTree.py::IOSetTest::testRemoveSucceeds",
"BTrees/tests/test_IOBTree.py::IOSetTest::testSetstateArgumentChecking",
"BTrees/tests/test_IOBTree.py::IOSetTest::testShortRepr",
"BTrees/tests/test_IOBTree.py::IOSetTest::testSimpleExclusiveKeyRange",
"BTrees/tests/test_IOBTree.py::IOSetTest::testSlicing",
"BTrees/tests/test_IOBTree.py::IOSetTest::testUpdate",
"BTrees/tests/test_IOBTree.py::IOSetTest::test_impl_pickle",
"BTrees/tests/test_IOBTree.py::IOSetTest::test_isinstance_subclass",
"BTrees/tests/test_IOBTree.py::IOSetTest::test_pickle_empty",
"BTrees/tests/test_IOBTree.py::IOSetTest::test_pickle_subclass",
"BTrees/tests/test_IOBTree.py::IOSetPyTest::testAddingOneSetsChanged",
"BTrees/tests/test_IOBTree.py::IOSetPyTest::testBigInsert",
"BTrees/tests/test_IOBTree.py::IOSetPyTest::testClear",
"BTrees/tests/test_IOBTree.py::IOSetPyTest::testDuplicateInsert",
"BTrees/tests/test_IOBTree.py::IOSetPyTest::testEmptyRangeSearches",
"BTrees/tests/test_IOBTree.py::IOSetPyTest::testGetItem",
"BTrees/tests/test_IOBTree.py::IOSetPyTest::testHasKeyFails",
"BTrees/tests/test_IOBTree.py::IOSetPyTest::testInsert",
"BTrees/tests/test_IOBTree.py::IOSetPyTest::testInsertReturnsValue",
"BTrees/tests/test_IOBTree.py::IOSetPyTest::testIterator",
"BTrees/tests/test_IOBTree.py::IOSetPyTest::testKeys",
"BTrees/tests/test_IOBTree.py::IOSetPyTest::testLen",
"BTrees/tests/test_IOBTree.py::IOSetPyTest::testMaxKeyMinKey",
"BTrees/tests/test_IOBTree.py::IOSetPyTest::testRemoveFails",
"BTrees/tests/test_IOBTree.py::IOSetPyTest::testRemoveInSmallSetSetsChanged",
"BTrees/tests/test_IOBTree.py::IOSetPyTest::testRemoveSucceeds",
"BTrees/tests/test_IOBTree.py::IOSetPyTest::testSetstateArgumentChecking",
"BTrees/tests/test_IOBTree.py::IOSetPyTest::testShortRepr",
"BTrees/tests/test_IOBTree.py::IOSetPyTest::testSimpleExclusiveKeyRange",
"BTrees/tests/test_IOBTree.py::IOSetPyTest::testSlicing",
"BTrees/tests/test_IOBTree.py::IOSetPyTest::testUpdate",
"BTrees/tests/test_IOBTree.py::IOSetPyTest::test_impl_pickle",
"BTrees/tests/test_IOBTree.py::IOSetPyTest::test_isinstance_subclass",
"BTrees/tests/test_IOBTree.py::IOSetPyTest::test_pickle_empty",
"BTrees/tests/test_IOBTree.py::IOSetPyTest::test_pickle_subclass",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testAddTwoSetsChanged",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testBadUpdateTupleSize",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testClear",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testDamagedIterator",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testDeleteInvalidKeyRaisesKeyError",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testDeleteNoChildrenWorks",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testDeleteOneChildWorks",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testDeleteRootWorks",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testDeleteTwoChildrenInorderSuccessorWorks",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testDeleteTwoChildrenNoInorderSuccessorWorks",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testEmptyRangeSearches",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testGetItemFails",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testGetReturnsDefault",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testHasKeyWorks",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testInsertMethod",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testItemsNegativeIndex",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testItemsWorks",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testIterators",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testKeysNegativeIndex",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testKeysWorks",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testLen",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testMaxKeyMinKey",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testPathologicalLeftBranching",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testPathologicalRangeSearch",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testPathologicalRightBranching",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testPop",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testRandomDeletes",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testRandomNonOverlappingInserts",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testRandomOverlappingInserts",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testRangeSearchAfterRandomInsert",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testRangeSearchAfterSequentialInsert",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testRangedIterators",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testRemoveInSmallMapSetsChanged",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testReplaceWorks",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testRepr",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testSetItemGetItemWorks",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testSetdefault",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testSetstateArgumentChecking",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testShortRepr",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testSimpleExclusivRanges",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testSimpleExclusiveKeyRange",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testSlicing",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testSuccessorChildParentRewriteExerciseCase",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testTargetedDeletes",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testUpdate",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testUpdateFromPersistentMapping",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testValuesNegativeIndex",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testValuesWorks",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::testValuesWorks1",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::test_impl_pickle",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::test_isinstance_subclass",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::test_legacy_py_pickle",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::test_pickle_empty",
"BTrees/tests/test_IOBTree.py::IOBTreeTest::test_pickle_subclass",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testAddTwoSetsChanged",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testBadUpdateTupleSize",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testClear",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testDamagedIterator",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testDeleteInvalidKeyRaisesKeyError",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testDeleteNoChildrenWorks",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testDeleteOneChildWorks",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testDeleteRootWorks",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testDeleteTwoChildrenInorderSuccessorWorks",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testDeleteTwoChildrenNoInorderSuccessorWorks",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testEmptyRangeSearches",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testGetItemFails",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testGetReturnsDefault",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testHasKeyWorks",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testInsertMethod",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testItemsNegativeIndex",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testItemsWorks",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testIterators",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testKeysNegativeIndex",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testKeysWorks",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testLen",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testMaxKeyMinKey",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testPathologicalLeftBranching",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testPathologicalRangeSearch",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testPathologicalRightBranching",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testPop",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testRandomDeletes",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testRandomNonOverlappingInserts",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testRandomOverlappingInserts",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testRangeSearchAfterRandomInsert",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testRangeSearchAfterSequentialInsert",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testRangedIterators",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testRemoveInSmallMapSetsChanged",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testReplaceWorks",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testRepr",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testSetItemGetItemWorks",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testSetdefault",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testSetstateArgumentChecking",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testShortRepr",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testSimpleExclusivRanges",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testSimpleExclusiveKeyRange",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testSlicing",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testSuccessorChildParentRewriteExerciseCase",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testTargetedDeletes",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testUpdate",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testUpdateFromPersistentMapping",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testValuesNegativeIndex",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testValuesWorks",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::testValuesWorks1",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::test_impl_pickle",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::test_isinstance_subclass",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::test_legacy_py_pickle",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::test_pickle_empty",
"BTrees/tests/test_IOBTree.py::IOBTreePyTest::test_pickle_subclass",
"BTrees/tests/test_IOBTree.py::TestIOBTrees::testBadTypeRaises",
"BTrees/tests/test_IOBTree.py::TestIOBTreesPy::testBadTypeRaises",
"BTrees/tests/test_IOBTree.py::TestIOBTreesPy::testStringKeyRaisesKeyErrorWhenMissing",
"BTrees/tests/test_IOBTree.py::TestIOBTreesPy::testStringKeyReturnsDefaultFromGetWhenMissing",
"BTrees/tests/test_IOBTree.py::TestIOSets::testBadBadKeyAfterFirst",
"BTrees/tests/test_IOBTree.py::TestIOSets::testNonIntegerInsertRaises",
"BTrees/tests/test_IOBTree.py::TestIOSetsPy::testBadBadKeyAfterFirst",
"BTrees/tests/test_IOBTree.py::TestIOSetsPy::testNonIntegerInsertRaises",
"BTrees/tests/test_IOBTree.py::TestIOTreeSets::testBadBadKeyAfterFirst",
"BTrees/tests/test_IOBTree.py::TestIOTreeSets::testNonIntegerInsertRaises",
"BTrees/tests/test_IOBTree.py::TestIOTreeSetsPy::testBadBadKeyAfterFirst",
"BTrees/tests/test_IOBTree.py::TestIOTreeSetsPy::testNonIntegerInsertRaises",
"BTrees/tests/test_IOBTree.py::PureIO::testDifference",
"BTrees/tests/test_IOBTree.py::PureIO::testEmptyDifference",
"BTrees/tests/test_IOBTree.py::PureIO::testEmptyIntersection",
"BTrees/tests/test_IOBTree.py::PureIO::testEmptyUnion",
"BTrees/tests/test_IOBTree.py::PureIO::testIntersection",
"BTrees/tests/test_IOBTree.py::PureIO::testLargerInputs",
"BTrees/tests/test_IOBTree.py::PureIO::testNone",
"BTrees/tests/test_IOBTree.py::PureIO::testUnion",
"BTrees/tests/test_IOBTree.py::PureIOPy::testDifference",
"BTrees/tests/test_IOBTree.py::PureIOPy::testEmptyDifference",
"BTrees/tests/test_IOBTree.py::PureIOPy::testEmptyIntersection",
"BTrees/tests/test_IOBTree.py::PureIOPy::testEmptyUnion",
"BTrees/tests/test_IOBTree.py::PureIOPy::testIntersection",
"BTrees/tests/test_IOBTree.py::PureIOPy::testLargerInputs",
"BTrees/tests/test_IOBTree.py::PureIOPy::testNone",
"BTrees/tests/test_IOBTree.py::PureIOPy::testUnion",
"BTrees/tests/test_IOBTree.py::TestIOMultiUnion::testBigInput",
"BTrees/tests/test_IOBTree.py::TestIOMultiUnion::testEmpty",
"BTrees/tests/test_IOBTree.py::TestIOMultiUnion::testFunkyKeyIteration",
"BTrees/tests/test_IOBTree.py::TestIOMultiUnion::testLotsOfLittleOnes",
"BTrees/tests/test_IOBTree.py::TestIOMultiUnion::testOne",
"BTrees/tests/test_IOBTree.py::TestIOMultiUnion::testValuesIgnored",
"BTrees/tests/test_IOBTree.py::TestIOMultiUnionPy::testBigInput",
"BTrees/tests/test_IOBTree.py::TestIOMultiUnionPy::testEmpty",
"BTrees/tests/test_IOBTree.py::TestIOMultiUnionPy::testFunkyKeyIteration",
"BTrees/tests/test_IOBTree.py::TestIOMultiUnionPy::testLotsOfLittleOnes",
"BTrees/tests/test_IOBTree.py::TestIOMultiUnionPy::testOne",
"BTrees/tests/test_IOBTree.py::TestIOMultiUnionPy::testValuesIgnored",
"BTrees/tests/test_IOBTree.py::IOBTreeConflictTests::testFailMergeDelete",
"BTrees/tests/test_IOBTree.py::IOBTreeConflictTests::testFailMergeDeleteAndUpdate",
"BTrees/tests/test_IOBTree.py::IOBTreeConflictTests::testFailMergeEmptyAndFill",
"BTrees/tests/test_IOBTree.py::IOBTreeConflictTests::testFailMergeInsert",
"BTrees/tests/test_IOBTree.py::IOBTreeConflictTests::testFailMergeUpdate",
"BTrees/tests/test_IOBTree.py::IOBTreeConflictTests::testMergeDelete",
"BTrees/tests/test_IOBTree.py::IOBTreeConflictTests::testMergeDeleteAndUpdate",
"BTrees/tests/test_IOBTree.py::IOBTreeConflictTests::testMergeEmpty",
"BTrees/tests/test_IOBTree.py::IOBTreeConflictTests::testMergeInserts",
"BTrees/tests/test_IOBTree.py::IOBTreeConflictTests::testMergeInsertsFromEmpty",
"BTrees/tests/test_IOBTree.py::IOBTreeConflictTests::testMergeUpdate",
"BTrees/tests/test_IOBTree.py::IOBTreeConflictTestsPy::testFailMergeDelete",
"BTrees/tests/test_IOBTree.py::IOBTreeConflictTestsPy::testFailMergeDeleteAndUpdate",
"BTrees/tests/test_IOBTree.py::IOBTreeConflictTestsPy::testFailMergeEmptyAndFill",
"BTrees/tests/test_IOBTree.py::IOBTreeConflictTestsPy::testFailMergeInsert",
"BTrees/tests/test_IOBTree.py::IOBTreeConflictTestsPy::testFailMergeUpdate",
"BTrees/tests/test_IOBTree.py::IOBTreeConflictTestsPy::testMergeDelete",
"BTrees/tests/test_IOBTree.py::IOBTreeConflictTestsPy::testMergeDeleteAndUpdate",
"BTrees/tests/test_IOBTree.py::IOBTreeConflictTestsPy::testMergeEmpty",
"BTrees/tests/test_IOBTree.py::IOBTreeConflictTestsPy::testMergeInserts",
"BTrees/tests/test_IOBTree.py::IOBTreeConflictTestsPy::testMergeInsertsFromEmpty",
"BTrees/tests/test_IOBTree.py::IOBTreeConflictTestsPy::testMergeUpdate",
"BTrees/tests/test_IOBTree.py::IOBucketConflictTests::testFailMergeDelete",
"BTrees/tests/test_IOBTree.py::IOBucketConflictTests::testFailMergeDeleteAndUpdate",
"BTrees/tests/test_IOBTree.py::IOBucketConflictTests::testFailMergeEmptyAndFill",
"BTrees/tests/test_IOBTree.py::IOBucketConflictTests::testFailMergeInsert",
"BTrees/tests/test_IOBTree.py::IOBucketConflictTests::testFailMergeUpdate",
"BTrees/tests/test_IOBTree.py::IOBucketConflictTests::testMergeDelete",
"BTrees/tests/test_IOBTree.py::IOBucketConflictTests::testMergeDeleteAndUpdate",
"BTrees/tests/test_IOBTree.py::IOBucketConflictTests::testMergeEmpty",
"BTrees/tests/test_IOBTree.py::IOBucketConflictTests::testMergeInserts",
"BTrees/tests/test_IOBTree.py::IOBucketConflictTests::testMergeInsertsFromEmpty",
"BTrees/tests/test_IOBTree.py::IOBucketConflictTests::testMergeUpdate",
"BTrees/tests/test_IOBTree.py::IOBucketConflictTestsPy::testFailMergeDelete",
"BTrees/tests/test_IOBTree.py::IOBucketConflictTestsPy::testFailMergeDeleteAndUpdate",
"BTrees/tests/test_IOBTree.py::IOBucketConflictTestsPy::testFailMergeEmptyAndFill",
"BTrees/tests/test_IOBTree.py::IOBucketConflictTestsPy::testFailMergeInsert",
"BTrees/tests/test_IOBTree.py::IOBucketConflictTestsPy::testFailMergeUpdate",
"BTrees/tests/test_IOBTree.py::IOBucketConflictTestsPy::testMergeDelete",
"BTrees/tests/test_IOBTree.py::IOBucketConflictTestsPy::testMergeDeleteAndUpdate",
"BTrees/tests/test_IOBTree.py::IOBucketConflictTestsPy::testMergeEmpty",
"BTrees/tests/test_IOBTree.py::IOBucketConflictTestsPy::testMergeInserts",
"BTrees/tests/test_IOBTree.py::IOBucketConflictTestsPy::testMergeInsertsFromEmpty",
"BTrees/tests/test_IOBTree.py::IOBucketConflictTestsPy::testMergeUpdate",
"BTrees/tests/test_IOBTree.py::IOTreeSetConflictTests::testFailMergeDelete",
"BTrees/tests/test_IOBTree.py::IOTreeSetConflictTests::testFailMergeEmptyAndFill",
"BTrees/tests/test_IOBTree.py::IOTreeSetConflictTests::testFailMergeInsert",
"BTrees/tests/test_IOBTree.py::IOTreeSetConflictTests::testMergeDelete",
"BTrees/tests/test_IOBTree.py::IOTreeSetConflictTests::testMergeEmpty",
"BTrees/tests/test_IOBTree.py::IOTreeSetConflictTests::testMergeInserts",
"BTrees/tests/test_IOBTree.py::IOTreeSetConflictTests::testMergeInsertsFromEmpty",
"BTrees/tests/test_IOBTree.py::IOTreeSetConflictTestsPy::testFailMergeDelete",
"BTrees/tests/test_IOBTree.py::IOTreeSetConflictTestsPy::testFailMergeEmptyAndFill",
"BTrees/tests/test_IOBTree.py::IOTreeSetConflictTestsPy::testFailMergeInsert",
"BTrees/tests/test_IOBTree.py::IOTreeSetConflictTestsPy::testMergeDelete",
"BTrees/tests/test_IOBTree.py::IOTreeSetConflictTestsPy::testMergeEmpty",
"BTrees/tests/test_IOBTree.py::IOTreeSetConflictTestsPy::testMergeInserts",
"BTrees/tests/test_IOBTree.py::IOTreeSetConflictTestsPy::testMergeInsertsFromEmpty",
"BTrees/tests/test_IOBTree.py::IOSetConflictTests::testFailMergeDelete",
"BTrees/tests/test_IOBTree.py::IOSetConflictTests::testFailMergeEmptyAndFill",
"BTrees/tests/test_IOBTree.py::IOSetConflictTests::testFailMergeInsert",
"BTrees/tests/test_IOBTree.py::IOSetConflictTests::testMergeDelete",
"BTrees/tests/test_IOBTree.py::IOSetConflictTests::testMergeEmpty",
"BTrees/tests/test_IOBTree.py::IOSetConflictTests::testMergeInserts",
"BTrees/tests/test_IOBTree.py::IOSetConflictTests::testMergeInsertsFromEmpty",
"BTrees/tests/test_IOBTree.py::IOSetConflictTestsPy::testFailMergeDelete",
"BTrees/tests/test_IOBTree.py::IOSetConflictTestsPy::testFailMergeEmptyAndFill",
"BTrees/tests/test_IOBTree.py::IOSetConflictTestsPy::testFailMergeInsert",
"BTrees/tests/test_IOBTree.py::IOSetConflictTestsPy::testMergeDelete",
"BTrees/tests/test_IOBTree.py::IOSetConflictTestsPy::testMergeEmpty",
"BTrees/tests/test_IOBTree.py::IOSetConflictTestsPy::testMergeInserts",
"BTrees/tests/test_IOBTree.py::IOSetConflictTestsPy::testMergeInsertsFromEmpty",
"BTrees/tests/test_IOBTree.py::IOModuleTest::testFamily",
"BTrees/tests/test_IOBTree.py::IOModuleTest::testModuleProvides",
"BTrees/tests/test_IOBTree.py::IOModuleTest::testNames",
"BTrees/tests/test_IOBTree.py::IOModuleTest::test_weightedIntersection_not_present",
"BTrees/tests/test_IOBTree.py::IOModuleTest::test_weightedUnion_not_present",
"BTrees/tests/test_IOBTree.py::test_suite",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testBadUpdateTupleSize",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testClear",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testDeleteInvalidKeyRaisesKeyError",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testEmptyRangeSearches",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testGetItemFails",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testGetReturnsDefault",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testHasKeyWorks",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testItemsNegativeIndex",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testItemsWorks",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testIterators",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testKeysNegativeIndex",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testKeysWorks",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testLen",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testMaxKeyMinKey",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testPop",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testRangedIterators",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testReplaceWorks",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testRepr",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testSetItemGetItemWorks",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testSetdefault",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testSetstateArgumentChecking",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testShortRepr",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testSimpleExclusivRanges",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testSimpleExclusiveKeyRange",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testSlicing",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testUpdate",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testUpdateFromPersistentMapping",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testValuesNegativeIndex",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testValuesWorks",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testValuesWorks1",
"BTrees/tests/test_OOBTree.py::OOBucketTest::test_impl_pickle",
"BTrees/tests/test_OOBTree.py::OOBucketTest::test_isinstance_subclass",
"BTrees/tests/test_OOBTree.py::OOBucketTest::test_pickle_empty",
"BTrees/tests/test_OOBTree.py::OOBucketTest::test_pickle_subclass",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testBadUpdateTupleSize",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testClear",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testDeleteInvalidKeyRaisesKeyError",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testEmptyRangeSearches",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testGetItemFails",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testGetReturnsDefault",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testHasKeyWorks",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testItemsNegativeIndex",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testItemsWorks",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testIterators",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testKeysNegativeIndex",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testKeysWorks",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testLen",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testMaxKeyMinKey",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testPop",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testRangedIterators",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testReplaceWorks",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testRepr",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testSetItemGetItemWorks",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testSetdefault",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testSetstateArgumentChecking",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testShortRepr",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testSimpleExclusivRanges",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testSimpleExclusiveKeyRange",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testSlicing",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testUpdate",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testUpdateFromPersistentMapping",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testValuesNegativeIndex",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testValuesWorks",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testValuesWorks1",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::test_impl_pickle",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::test_isinstance_subclass",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::test_pickle_empty",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::test_pickle_subclass",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testAddingOneSetsChanged",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testBigInsert",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testClear",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testDuplicateInsert",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testEmptyRangeSearches",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testHasKeyFails",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testInsert",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testInsertReturnsValue",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testIterator",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testKeys",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testMaxKeyMinKey",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testRemoveFails",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testRemoveInSmallSetSetsChanged",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testRemoveSucceeds",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testSetstateArgumentChecking",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testShortRepr",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testSimpleExclusiveKeyRange",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testSlicing",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testUpdate",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::test_impl_pickle",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::test_isinstance_subclass",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::test_pickle_empty",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::test_pickle_subclass",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testAddingOneSetsChanged",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testBigInsert",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testClear",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testDuplicateInsert",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testEmptyRangeSearches",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testHasKeyFails",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testInsert",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testInsertReturnsValue",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testIterator",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testKeys",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testMaxKeyMinKey",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testRemoveFails",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testRemoveInSmallSetSetsChanged",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testRemoveSucceeds",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testSetstateArgumentChecking",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testShortRepr",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testSimpleExclusiveKeyRange",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testSlicing",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testUpdate",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::test_impl_pickle",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::test_isinstance_subclass",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::test_pickle_empty",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::test_pickle_subclass",
"BTrees/tests/test_OOBTree.py::OOSetTest::testAddingOneSetsChanged",
"BTrees/tests/test_OOBTree.py::OOSetTest::testBigInsert",
"BTrees/tests/test_OOBTree.py::OOSetTest::testClear",
"BTrees/tests/test_OOBTree.py::OOSetTest::testDuplicateInsert",
"BTrees/tests/test_OOBTree.py::OOSetTest::testEmptyRangeSearches",
"BTrees/tests/test_OOBTree.py::OOSetTest::testGetItem",
"BTrees/tests/test_OOBTree.py::OOSetTest::testHasKeyFails",
"BTrees/tests/test_OOBTree.py::OOSetTest::testInsert",
"BTrees/tests/test_OOBTree.py::OOSetTest::testInsertReturnsValue",
"BTrees/tests/test_OOBTree.py::OOSetTest::testIterator",
"BTrees/tests/test_OOBTree.py::OOSetTest::testKeys",
"BTrees/tests/test_OOBTree.py::OOSetTest::testLen",
"BTrees/tests/test_OOBTree.py::OOSetTest::testMaxKeyMinKey",
"BTrees/tests/test_OOBTree.py::OOSetTest::testRemoveFails",
"BTrees/tests/test_OOBTree.py::OOSetTest::testRemoveInSmallSetSetsChanged",
"BTrees/tests/test_OOBTree.py::OOSetTest::testRemoveSucceeds",
"BTrees/tests/test_OOBTree.py::OOSetTest::testSetstateArgumentChecking",
"BTrees/tests/test_OOBTree.py::OOSetTest::testShortRepr",
"BTrees/tests/test_OOBTree.py::OOSetTest::testSimpleExclusiveKeyRange",
"BTrees/tests/test_OOBTree.py::OOSetTest::testSlicing",
"BTrees/tests/test_OOBTree.py::OOSetTest::testUpdate",
"BTrees/tests/test_OOBTree.py::OOSetTest::test_impl_pickle",
"BTrees/tests/test_OOBTree.py::OOSetTest::test_isinstance_subclass",
"BTrees/tests/test_OOBTree.py::OOSetTest::test_pickle_empty",
"BTrees/tests/test_OOBTree.py::OOSetTest::test_pickle_subclass",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testAddingOneSetsChanged",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testBigInsert",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testClear",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testDuplicateInsert",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testEmptyRangeSearches",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testGetItem",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testHasKeyFails",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testInsert",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testInsertReturnsValue",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testIterator",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testKeys",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testLen",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testMaxKeyMinKey",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testRemoveFails",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testRemoveInSmallSetSetsChanged",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testRemoveSucceeds",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testSetstateArgumentChecking",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testShortRepr",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testSimpleExclusiveKeyRange",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testSlicing",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testUpdate",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::test_impl_pickle",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::test_isinstance_subclass",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::test_pickle_empty",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::test_pickle_subclass",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testAddTwoSetsChanged",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testBadUpdateTupleSize",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testClear",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testDamagedIterator",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testDeleteInvalidKeyRaisesKeyError",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testDeleteNoChildrenWorks",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testDeleteOneChildWorks",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testDeleteRootWorks",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testDeleteTwoChildrenInorderSuccessorWorks",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testDeleteTwoChildrenNoInorderSuccessorWorks",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testEmptyRangeSearches",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testGetItemFails",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testGetReturnsDefault",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testHasKeyWorks",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testInsertMethod",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testItemsNegativeIndex",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testItemsWorks",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testIterators",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testKeysNegativeIndex",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testKeysWorks",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testLen",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testMaxKeyMinKey",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testPathologicalLeftBranching",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testPathologicalRangeSearch",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testPathologicalRightBranching",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testPop",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testRandomDeletes",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testRandomNonOverlappingInserts",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testRandomOverlappingInserts",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testRangeSearchAfterRandomInsert",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testRangeSearchAfterSequentialInsert",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testRangedIterators",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testRejectDefaultComparisonOnSet",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testRemoveInSmallMapSetsChanged",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testReplaceWorks",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testRepr",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testSetItemGetItemWorks",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testSetdefault",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testSetstateArgumentChecking",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testShortRepr",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testSimpleExclusivRanges",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testSimpleExclusiveKeyRange",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testSlicing",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testSuccessorChildParentRewriteExerciseCase",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testTargetedDeletes",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testUpdate",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testUpdateFromPersistentMapping",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testValuesNegativeIndex",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testValuesWorks",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testValuesWorks1",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::test_byValue",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::test_impl_pickle",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::test_isinstance_subclass",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::test_legacy_py_pickle",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::test_pickle_empty",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::test_pickle_subclass",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testAcceptDefaultComparisonOnGet",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testAddTwoSetsChanged",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testBadUpdateTupleSize",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testClear",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testDamagedIterator",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testDeleteInvalidKeyRaisesKeyError",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testDeleteNoChildrenWorks",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testDeleteOneChildWorks",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testDeleteRootWorks",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testDeleteTwoChildrenInorderSuccessorWorks",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testDeleteTwoChildrenNoInorderSuccessorWorks",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testEmptyRangeSearches",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testGetItemFails",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testGetReturnsDefault",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testHasKeyWorks",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testInsertMethod",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testItemsNegativeIndex",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testItemsWorks",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testIterators",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testKeysNegativeIndex",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testKeysWorks",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testLen",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testMaxKeyMinKey",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testPathologicalLeftBranching",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testPathologicalRangeSearch",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testPathologicalRightBranching",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testPop",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testRandomDeletes",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testRandomNonOverlappingInserts",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testRandomOverlappingInserts",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testRangeSearchAfterRandomInsert",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testRangeSearchAfterSequentialInsert",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testRangedIterators",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testRemoveInSmallMapSetsChanged",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testReplaceWorks",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testRepr",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testSetItemGetItemWorks",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testSetdefault",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testSetstateArgumentChecking",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testShortRepr",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testSimpleExclusivRanges",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testSimpleExclusiveKeyRange",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testSlicing",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testSuccessorChildParentRewriteExerciseCase",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testTargetedDeletes",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testUpdate",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testUpdateFromPersistentMapping",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testValuesNegativeIndex",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testValuesWorks",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testValuesWorks1",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::test_byValue",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::test_impl_pickle",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::test_isinstance_subclass",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::test_legacy_py_pickle",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::test_pickle_empty",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::test_pickle_subclass",
"BTrees/tests/test_OOBTree.py::PureOO::testDifference",
"BTrees/tests/test_OOBTree.py::PureOO::testEmptyDifference",
"BTrees/tests/test_OOBTree.py::PureOO::testEmptyIntersection",
"BTrees/tests/test_OOBTree.py::PureOO::testEmptyUnion",
"BTrees/tests/test_OOBTree.py::PureOO::testIntersection",
"BTrees/tests/test_OOBTree.py::PureOO::testLargerInputs",
"BTrees/tests/test_OOBTree.py::PureOO::testNone",
"BTrees/tests/test_OOBTree.py::PureOO::testUnion",
"BTrees/tests/test_OOBTree.py::PureOOPy::testDifference",
"BTrees/tests/test_OOBTree.py::PureOOPy::testEmptyDifference",
"BTrees/tests/test_OOBTree.py::PureOOPy::testEmptyIntersection",
"BTrees/tests/test_OOBTree.py::PureOOPy::testEmptyUnion",
"BTrees/tests/test_OOBTree.py::PureOOPy::testIntersection",
"BTrees/tests/test_OOBTree.py::PureOOPy::testLargerInputs",
"BTrees/tests/test_OOBTree.py::PureOOPy::testNone",
"BTrees/tests/test_OOBTree.py::PureOOPy::testUnion",
"BTrees/tests/test_OOBTree.py::OOBucketConflictTests::testFailMergeDelete",
"BTrees/tests/test_OOBTree.py::OOBucketConflictTests::testFailMergeDeleteAndUpdate",
"BTrees/tests/test_OOBTree.py::OOBucketConflictTests::testFailMergeEmptyAndFill",
"BTrees/tests/test_OOBTree.py::OOBucketConflictTests::testFailMergeInsert",
"BTrees/tests/test_OOBTree.py::OOBucketConflictTests::testFailMergeUpdate",
"BTrees/tests/test_OOBTree.py::OOBucketConflictTests::testMergeDelete",
"BTrees/tests/test_OOBTree.py::OOBucketConflictTests::testMergeDeleteAndUpdate",
"BTrees/tests/test_OOBTree.py::OOBucketConflictTests::testMergeEmpty",
"BTrees/tests/test_OOBTree.py::OOBucketConflictTests::testMergeInserts",
"BTrees/tests/test_OOBTree.py::OOBucketConflictTests::testMergeInsertsFromEmpty",
"BTrees/tests/test_OOBTree.py::OOBucketConflictTests::testMergeUpdate",
"BTrees/tests/test_OOBTree.py::OOBucketPyConflictTests::testFailMergeDelete",
"BTrees/tests/test_OOBTree.py::OOBucketPyConflictTests::testFailMergeDeleteAndUpdate",
"BTrees/tests/test_OOBTree.py::OOBucketPyConflictTests::testFailMergeEmptyAndFill",
"BTrees/tests/test_OOBTree.py::OOBucketPyConflictTests::testFailMergeInsert",
"BTrees/tests/test_OOBTree.py::OOBucketPyConflictTests::testFailMergeUpdate",
"BTrees/tests/test_OOBTree.py::OOBucketPyConflictTests::testMergeDelete",
"BTrees/tests/test_OOBTree.py::OOBucketPyConflictTests::testMergeDeleteAndUpdate",
"BTrees/tests/test_OOBTree.py::OOBucketPyConflictTests::testMergeEmpty",
"BTrees/tests/test_OOBTree.py::OOBucketPyConflictTests::testMergeInserts",
"BTrees/tests/test_OOBTree.py::OOBucketPyConflictTests::testMergeInsertsFromEmpty",
"BTrees/tests/test_OOBTree.py::OOBucketPyConflictTests::testMergeUpdate",
"BTrees/tests/test_OOBTree.py::OOSetConflictTests::testFailMergeDelete",
"BTrees/tests/test_OOBTree.py::OOSetConflictTests::testFailMergeEmptyAndFill",
"BTrees/tests/test_OOBTree.py::OOSetConflictTests::testFailMergeInsert",
"BTrees/tests/test_OOBTree.py::OOSetConflictTests::testMergeDelete",
"BTrees/tests/test_OOBTree.py::OOSetConflictTests::testMergeEmpty",
"BTrees/tests/test_OOBTree.py::OOSetConflictTests::testMergeInserts",
"BTrees/tests/test_OOBTree.py::OOSetConflictTests::testMergeInsertsFromEmpty",
"BTrees/tests/test_OOBTree.py::OOSetPyConflictTests::testFailMergeDelete",
"BTrees/tests/test_OOBTree.py::OOSetPyConflictTests::testFailMergeEmptyAndFill",
"BTrees/tests/test_OOBTree.py::OOSetPyConflictTests::testFailMergeInsert",
"BTrees/tests/test_OOBTree.py::OOSetPyConflictTests::testMergeDelete",
"BTrees/tests/test_OOBTree.py::OOSetPyConflictTests::testMergeEmpty",
"BTrees/tests/test_OOBTree.py::OOSetPyConflictTests::testMergeInserts",
"BTrees/tests/test_OOBTree.py::OOSetPyConflictTests::testMergeInsertsFromEmpty",
"BTrees/tests/test_OOBTree.py::OOBTreeConflictTests::testFailMergeDelete",
"BTrees/tests/test_OOBTree.py::OOBTreeConflictTests::testFailMergeDeleteAndUpdate",
"BTrees/tests/test_OOBTree.py::OOBTreeConflictTests::testFailMergeEmptyAndFill",
"BTrees/tests/test_OOBTree.py::OOBTreeConflictTests::testFailMergeInsert",
"BTrees/tests/test_OOBTree.py::OOBTreeConflictTests::testFailMergeUpdate",
"BTrees/tests/test_OOBTree.py::OOBTreeConflictTests::testMergeDelete",
"BTrees/tests/test_OOBTree.py::OOBTreeConflictTests::testMergeDeleteAndUpdate",
"BTrees/tests/test_OOBTree.py::OOBTreeConflictTests::testMergeEmpty",
"BTrees/tests/test_OOBTree.py::OOBTreeConflictTests::testMergeInserts",
"BTrees/tests/test_OOBTree.py::OOBTreeConflictTests::testMergeInsertsFromEmpty",
"BTrees/tests/test_OOBTree.py::OOBTreeConflictTests::testMergeUpdate",
"BTrees/tests/test_OOBTree.py::OOBTreePyConflictTests::testFailMergeDelete",
"BTrees/tests/test_OOBTree.py::OOBTreePyConflictTests::testFailMergeDeleteAndUpdate",
"BTrees/tests/test_OOBTree.py::OOBTreePyConflictTests::testFailMergeEmptyAndFill",
"BTrees/tests/test_OOBTree.py::OOBTreePyConflictTests::testFailMergeInsert",
"BTrees/tests/test_OOBTree.py::OOBTreePyConflictTests::testFailMergeUpdate",
"BTrees/tests/test_OOBTree.py::OOBTreePyConflictTests::testMergeDelete",
"BTrees/tests/test_OOBTree.py::OOBTreePyConflictTests::testMergeDeleteAndUpdate",
"BTrees/tests/test_OOBTree.py::OOBTreePyConflictTests::testMergeEmpty",
"BTrees/tests/test_OOBTree.py::OOBTreePyConflictTests::testMergeInserts",
"BTrees/tests/test_OOBTree.py::OOBTreePyConflictTests::testMergeInsertsFromEmpty",
"BTrees/tests/test_OOBTree.py::OOBTreePyConflictTests::testMergeUpdate",
"BTrees/tests/test_OOBTree.py::OOTreeSetConflictTests::testFailMergeDelete",
"BTrees/tests/test_OOBTree.py::OOTreeSetConflictTests::testFailMergeEmptyAndFill",
"BTrees/tests/test_OOBTree.py::OOTreeSetConflictTests::testFailMergeInsert",
"BTrees/tests/test_OOBTree.py::OOTreeSetConflictTests::testMergeDelete",
"BTrees/tests/test_OOBTree.py::OOTreeSetConflictTests::testMergeEmpty",
"BTrees/tests/test_OOBTree.py::OOTreeSetConflictTests::testMergeInserts",
"BTrees/tests/test_OOBTree.py::OOTreeSetConflictTests::testMergeInsertsFromEmpty",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyConflictTests::testFailMergeDelete",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyConflictTests::testFailMergeEmptyAndFill",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyConflictTests::testFailMergeInsert",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyConflictTests::testMergeDelete",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyConflictTests::testMergeEmpty",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyConflictTests::testMergeInserts",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyConflictTests::testMergeInsertsFromEmpty",
"BTrees/tests/test_OOBTree.py::OOModuleTest::testFamily",
"BTrees/tests/test_OOBTree.py::OOModuleTest::testModuleProvides",
"BTrees/tests/test_OOBTree.py::OOModuleTest::testNames",
"BTrees/tests/test_OOBTree.py::OOModuleTest::test_multiunion_not_present",
"BTrees/tests/test_OOBTree.py::OOModuleTest::test_weightedIntersection_not_present",
"BTrees/tests/test_OOBTree.py::OOModuleTest::test_weightedUnion_not_present",
"BTrees/tests/test_OOBTree.py::test_suite"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2016-08-03T13:24:53Z" | zpl-2.1 |
|
zopefoundation__BTrees-56 | diff --git a/BTrees/_base.py b/BTrees/_base.py
index 3158d91..bef710a 100644
--- a/BTrees/_base.py
+++ b/BTrees/_base.py
@@ -111,7 +111,7 @@ class _BucketBase(_Base):
while low < high:
i = (low + high) // 2
k = keys[i]
- if k == key:
+ if k is key or k == key:
return i
if k < key:
low = i + 1
diff --git a/CHANGES.rst b/CHANGES.rst
index c396cf6..d40ebd9 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -6,10 +6,18 @@
- Make the CPython implementation consistent with the pure-Python
implementation and only check object keys for default comparison
- when setting keys. In Python 2 this makes it possible to remove
- keys that were added using a less restrictive version of BTrees.
- (In Python 3 keys that are unorderable still cannot be removed.)
- See: https://github.com/zopefoundation/BTrees/issues/53
+ when setting keys. In Python 2 this makes it possible to remove keys
+ that were added using a less restrictive version of BTrees. (In
+ Python 3 keys that are unorderable still cannot be removed.)
+ Likewise, all versions can unpickle trees that already had such
+ keys. See: https://github.com/zopefoundation/BTrees/issues/53 and
+ https://github.com/zopefoundation/BTrees/issues/51
+
+- Make the Python implementation consistent with the CPython
+ implementation and check object key identity before checking
+ equality and performing comparisons. This can allow fixing trees
+ that have keys that now have broken comparison functions. See
+ https://github.com/zopefoundation/BTrees/issues/50
- Make the CPython implementation consistent with the pure-Python
implementation and no longer raise ``TypeError`` for an object key
| zopefoundation/BTrees | 1fb38674c67b084b4c0453a3d5cefb79eca967af | diff --git a/BTrees/tests/test_OOBTree.py b/BTrees/tests/test_OOBTree.py
index 36643ab..08d77f9 100644
--- a/BTrees/tests/test_OOBTree.py
+++ b/BTrees/tests/test_OOBTree.py
@@ -161,12 +161,12 @@ class OOBTreeTest(BTreeTests, unittest.TestCase):
self.assertRaises(KeyError, t.__getitem__, C())
self.assertFalse(C() in t)
- # Check that a None key can be deleted in Python 2.
- # This doesn't work on Python 3 because None is unorderable,
- # so the tree can't be searched. But None also can't be inserted,
- # and we don't support migrating Python 2 databases to Python 3.
@_skip_under_Py3k
def testDeleteNoneKey(self):
+ # Check that a None key can be deleted in Python 2.
+ # This doesn't work on Python 3 because None is unorderable,
+ # so the tree can't be searched. But None also can't be inserted,
+ # and we don't support migrating Python 2 databases to Python 3.
t = self._makeOne()
bucket_state = ((None, 42),)
tree_state = ((bucket_state,),)
@@ -175,6 +175,45 @@ class OOBTreeTest(BTreeTests, unittest.TestCase):
self.assertEqual(t[None], 42)
del t[None]
+ def testUnpickleNoneKey(self):
+ # All versions (py2 and py3, C and Python) can unpickle
+ # data that looks like this: {None: 42}, even though None
+ # is unorderable..
+ # This pickle was captured in BTree/ZODB3 3.10.7
+ data = b'ccopy_reg\n__newobj__\np0\n(cBTrees.OOBTree\nOOBTree\np1\ntp2\nRp3\n((((NI42\ntp4\ntp5\ntp6\ntp7\nb.'
+
+ import pickle
+ t = pickle.loads(data)
+ keys = list(t)
+ self.assertEqual([None], keys)
+
+ def testIdentityTrumpsBrokenComparison(self):
+ # Identical keys always match, even if their comparison is
+ # broken. See https://github.com/zopefoundation/BTrees/issues/50
+ from functools import total_ordering
+
+ @total_ordering
+ class Bad(object):
+ def __eq__(self, other):
+ return False
+
+ def __cmp__(self, other):
+ return 1
+
+ def __lt__(self, other):
+ return False
+
+ t = self._makeOne()
+ bad_key = Bad()
+ t[bad_key] = 42
+
+ self.assertIn(bad_key, t)
+ self.assertEqual(list(t), [bad_key])
+
+ del t[bad_key]
+ self.assertNotIn(bad_key, t)
+ self.assertEqual(list(t), [])
+
class OOBTreePyTest(OOBTreeTest):
#
| C/Py difference: keys that are the same object
The C implementation does a comparison [by first checking whether the two keys are the same pointer](https://github.com/python/cpython/blob/2.7/Objects/object.c#L997); the Python implementation just goes [right to the `==` operator](https://github.com/zopefoundation/BTrees/blob/master/BTrees/_base.py#L114). In some cases of (broken?) objects this leads to a discrepancy: The C implementation can find a key, but the Python implementation cannot.
I would suggest that the Python implementation should use `k is key or k == key` to clear this up.
See https://groups.google.com/forum/#!topic/zodb/xhVM0ejl6aE | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testIdentityTrumpsBrokenComparison"
] | [
"BTrees/tests/test_OOBTree.py::OOBucketTest::testBadUpdateTupleSize",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testClear",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testDeleteInvalidKeyRaisesKeyError",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testEmptyRangeSearches",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testGetItemFails",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testGetReturnsDefault",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testHasKeyWorks",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testItemsNegativeIndex",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testItemsWorks",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testIterators",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testKeysNegativeIndex",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testKeysWorks",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testLen",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testMaxKeyMinKey",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testPop",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testRangedIterators",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testReplaceWorks",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testRepr",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testSetItemGetItemWorks",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testSetdefault",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testSetstateArgumentChecking",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testShortRepr",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testSimpleExclusivRanges",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testSimpleExclusiveKeyRange",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testSlicing",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testUpdate",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testUpdateFromPersistentMapping",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testValuesNegativeIndex",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testValuesWorks",
"BTrees/tests/test_OOBTree.py::OOBucketTest::testValuesWorks1",
"BTrees/tests/test_OOBTree.py::OOBucketTest::test_impl_pickle",
"BTrees/tests/test_OOBTree.py::OOBucketTest::test_isinstance_subclass",
"BTrees/tests/test_OOBTree.py::OOBucketTest::test_pickle_empty",
"BTrees/tests/test_OOBTree.py::OOBucketTest::test_pickle_subclass",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testBadUpdateTupleSize",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testClear",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testDeleteInvalidKeyRaisesKeyError",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testEmptyRangeSearches",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testGetItemFails",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testGetReturnsDefault",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testHasKeyWorks",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testItemsNegativeIndex",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testItemsWorks",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testIterators",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testKeysNegativeIndex",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testKeysWorks",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testLen",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testMaxKeyMinKey",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testPop",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testRangedIterators",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testReplaceWorks",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testRepr",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testSetItemGetItemWorks",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testSetdefault",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testSetstateArgumentChecking",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testShortRepr",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testSimpleExclusivRanges",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testSimpleExclusiveKeyRange",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testSlicing",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testUpdate",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testUpdateFromPersistentMapping",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testValuesNegativeIndex",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testValuesWorks",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::testValuesWorks1",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::test_impl_pickle",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::test_isinstance_subclass",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::test_pickle_empty",
"BTrees/tests/test_OOBTree.py::OOBucketPyTest::test_pickle_subclass",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testAddingOneSetsChanged",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testBigInsert",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testClear",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testDuplicateInsert",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testEmptyRangeSearches",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testHasKeyFails",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testInsert",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testInsertReturnsValue",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testIterator",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testKeys",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testMaxKeyMinKey",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testRemoveFails",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testRemoveInSmallSetSetsChanged",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testRemoveSucceeds",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testSetstateArgumentChecking",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testShortRepr",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testSimpleExclusiveKeyRange",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testSlicing",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::testUpdate",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::test_impl_pickle",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::test_isinstance_subclass",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::test_pickle_empty",
"BTrees/tests/test_OOBTree.py::OOTreeSetTest::test_pickle_subclass",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testAddingOneSetsChanged",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testBigInsert",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testClear",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testDuplicateInsert",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testEmptyRangeSearches",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testHasKeyFails",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testInsert",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testInsertReturnsValue",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testIterator",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testKeys",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testMaxKeyMinKey",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testRemoveFails",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testRemoveInSmallSetSetsChanged",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testRemoveSucceeds",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testSetstateArgumentChecking",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testShortRepr",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testSimpleExclusiveKeyRange",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testSlicing",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::testUpdate",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::test_impl_pickle",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::test_isinstance_subclass",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::test_pickle_empty",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyTest::test_pickle_subclass",
"BTrees/tests/test_OOBTree.py::OOSetTest::testAddingOneSetsChanged",
"BTrees/tests/test_OOBTree.py::OOSetTest::testBigInsert",
"BTrees/tests/test_OOBTree.py::OOSetTest::testClear",
"BTrees/tests/test_OOBTree.py::OOSetTest::testDuplicateInsert",
"BTrees/tests/test_OOBTree.py::OOSetTest::testEmptyRangeSearches",
"BTrees/tests/test_OOBTree.py::OOSetTest::testGetItem",
"BTrees/tests/test_OOBTree.py::OOSetTest::testHasKeyFails",
"BTrees/tests/test_OOBTree.py::OOSetTest::testInsert",
"BTrees/tests/test_OOBTree.py::OOSetTest::testInsertReturnsValue",
"BTrees/tests/test_OOBTree.py::OOSetTest::testIterator",
"BTrees/tests/test_OOBTree.py::OOSetTest::testKeys",
"BTrees/tests/test_OOBTree.py::OOSetTest::testLen",
"BTrees/tests/test_OOBTree.py::OOSetTest::testMaxKeyMinKey",
"BTrees/tests/test_OOBTree.py::OOSetTest::testRemoveFails",
"BTrees/tests/test_OOBTree.py::OOSetTest::testRemoveInSmallSetSetsChanged",
"BTrees/tests/test_OOBTree.py::OOSetTest::testRemoveSucceeds",
"BTrees/tests/test_OOBTree.py::OOSetTest::testSetstateArgumentChecking",
"BTrees/tests/test_OOBTree.py::OOSetTest::testShortRepr",
"BTrees/tests/test_OOBTree.py::OOSetTest::testSimpleExclusiveKeyRange",
"BTrees/tests/test_OOBTree.py::OOSetTest::testSlicing",
"BTrees/tests/test_OOBTree.py::OOSetTest::testUpdate",
"BTrees/tests/test_OOBTree.py::OOSetTest::test_impl_pickle",
"BTrees/tests/test_OOBTree.py::OOSetTest::test_isinstance_subclass",
"BTrees/tests/test_OOBTree.py::OOSetTest::test_pickle_empty",
"BTrees/tests/test_OOBTree.py::OOSetTest::test_pickle_subclass",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testAddingOneSetsChanged",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testBigInsert",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testClear",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testDuplicateInsert",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testEmptyRangeSearches",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testGetItem",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testHasKeyFails",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testInsert",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testInsertReturnsValue",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testIterator",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testKeys",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testLen",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testMaxKeyMinKey",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testRemoveFails",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testRemoveInSmallSetSetsChanged",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testRemoveSucceeds",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testSetstateArgumentChecking",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testShortRepr",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testSimpleExclusiveKeyRange",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testSlicing",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::testUpdate",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::test_impl_pickle",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::test_isinstance_subclass",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::test_pickle_empty",
"BTrees/tests/test_OOBTree.py::OOSetPyTest::test_pickle_subclass",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testAcceptDefaultComparisonOnGet",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testAddTwoSetsChanged",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testBadUpdateTupleSize",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testClear",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testDamagedIterator",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testDeleteInvalidKeyRaisesKeyError",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testDeleteNoChildrenWorks",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testDeleteOneChildWorks",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testDeleteRootWorks",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testDeleteTwoChildrenInorderSuccessorWorks",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testDeleteTwoChildrenNoInorderSuccessorWorks",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testEmptyRangeSearches",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testGetItemFails",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testGetReturnsDefault",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testHasKeyWorks",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testIdentityTrumpsBrokenComparison",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testInsertMethod",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testItemsNegativeIndex",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testItemsWorks",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testIterators",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testKeysNegativeIndex",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testKeysWorks",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testLen",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testMaxKeyMinKey",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testPathologicalLeftBranching",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testPathologicalRangeSearch",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testPathologicalRightBranching",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testPop",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testRandomDeletes",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testRandomNonOverlappingInserts",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testRandomOverlappingInserts",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testRangeSearchAfterRandomInsert",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testRangeSearchAfterSequentialInsert",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testRangedIterators",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testRejectDefaultComparisonOnSet",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testRemoveInSmallMapSetsChanged",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testReplaceWorks",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testRepr",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testSetItemGetItemWorks",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testSetdefault",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testSetstateArgumentChecking",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testShortRepr",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testSimpleExclusivRanges",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testSimpleExclusiveKeyRange",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testSlicing",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testSuccessorChildParentRewriteExerciseCase",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testTargetedDeletes",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testUnpickleNoneKey",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testUpdate",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testUpdateFromPersistentMapping",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testValuesNegativeIndex",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testValuesWorks",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::testValuesWorks1",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::test_byValue",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::test_impl_pickle",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::test_isinstance_subclass",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::test_legacy_py_pickle",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::test_pickle_empty",
"BTrees/tests/test_OOBTree.py::OOBTreeTest::test_pickle_subclass",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testAcceptDefaultComparisonOnGet",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testAddTwoSetsChanged",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testBadUpdateTupleSize",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testClear",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testDamagedIterator",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testDeleteInvalidKeyRaisesKeyError",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testDeleteNoChildrenWorks",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testDeleteOneChildWorks",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testDeleteRootWorks",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testDeleteTwoChildrenInorderSuccessorWorks",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testDeleteTwoChildrenNoInorderSuccessorWorks",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testEmptyRangeSearches",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testGetItemFails",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testGetReturnsDefault",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testHasKeyWorks",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testInsertMethod",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testItemsNegativeIndex",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testItemsWorks",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testIterators",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testKeysNegativeIndex",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testKeysWorks",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testLen",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testMaxKeyMinKey",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testPathologicalLeftBranching",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testPathologicalRangeSearch",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testPathologicalRightBranching",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testPop",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testRandomDeletes",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testRandomNonOverlappingInserts",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testRandomOverlappingInserts",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testRangeSearchAfterRandomInsert",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testRangeSearchAfterSequentialInsert",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testRangedIterators",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testRejectDefaultComparisonOnSet",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testRemoveInSmallMapSetsChanged",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testReplaceWorks",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testRepr",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testSetItemGetItemWorks",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testSetdefault",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testSetstateArgumentChecking",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testShortRepr",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testSimpleExclusivRanges",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testSimpleExclusiveKeyRange",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testSlicing",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testSuccessorChildParentRewriteExerciseCase",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testTargetedDeletes",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testUnpickleNoneKey",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testUpdate",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testUpdateFromPersistentMapping",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testValuesNegativeIndex",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testValuesWorks",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::testValuesWorks1",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::test_byValue",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::test_impl_pickle",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::test_isinstance_subclass",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::test_legacy_py_pickle",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::test_pickle_empty",
"BTrees/tests/test_OOBTree.py::OOBTreePyTest::test_pickle_subclass",
"BTrees/tests/test_OOBTree.py::PureOO::testDifference",
"BTrees/tests/test_OOBTree.py::PureOO::testEmptyDifference",
"BTrees/tests/test_OOBTree.py::PureOO::testEmptyIntersection",
"BTrees/tests/test_OOBTree.py::PureOO::testEmptyUnion",
"BTrees/tests/test_OOBTree.py::PureOO::testIntersection",
"BTrees/tests/test_OOBTree.py::PureOO::testLargerInputs",
"BTrees/tests/test_OOBTree.py::PureOO::testNone",
"BTrees/tests/test_OOBTree.py::PureOO::testUnion",
"BTrees/tests/test_OOBTree.py::PureOOPy::testDifference",
"BTrees/tests/test_OOBTree.py::PureOOPy::testEmptyDifference",
"BTrees/tests/test_OOBTree.py::PureOOPy::testEmptyIntersection",
"BTrees/tests/test_OOBTree.py::PureOOPy::testEmptyUnion",
"BTrees/tests/test_OOBTree.py::PureOOPy::testIntersection",
"BTrees/tests/test_OOBTree.py::PureOOPy::testLargerInputs",
"BTrees/tests/test_OOBTree.py::PureOOPy::testNone",
"BTrees/tests/test_OOBTree.py::PureOOPy::testUnion",
"BTrees/tests/test_OOBTree.py::OOBucketConflictTests::testFailMergeDelete",
"BTrees/tests/test_OOBTree.py::OOBucketConflictTests::testFailMergeDeleteAndUpdate",
"BTrees/tests/test_OOBTree.py::OOBucketConflictTests::testFailMergeEmptyAndFill",
"BTrees/tests/test_OOBTree.py::OOBucketConflictTests::testFailMergeInsert",
"BTrees/tests/test_OOBTree.py::OOBucketConflictTests::testFailMergeUpdate",
"BTrees/tests/test_OOBTree.py::OOBucketConflictTests::testMergeDelete",
"BTrees/tests/test_OOBTree.py::OOBucketConflictTests::testMergeDeleteAndUpdate",
"BTrees/tests/test_OOBTree.py::OOBucketConflictTests::testMergeEmpty",
"BTrees/tests/test_OOBTree.py::OOBucketConflictTests::testMergeInserts",
"BTrees/tests/test_OOBTree.py::OOBucketConflictTests::testMergeInsertsFromEmpty",
"BTrees/tests/test_OOBTree.py::OOBucketConflictTests::testMergeUpdate",
"BTrees/tests/test_OOBTree.py::OOBucketPyConflictTests::testFailMergeDelete",
"BTrees/tests/test_OOBTree.py::OOBucketPyConflictTests::testFailMergeDeleteAndUpdate",
"BTrees/tests/test_OOBTree.py::OOBucketPyConflictTests::testFailMergeEmptyAndFill",
"BTrees/tests/test_OOBTree.py::OOBucketPyConflictTests::testFailMergeInsert",
"BTrees/tests/test_OOBTree.py::OOBucketPyConflictTests::testFailMergeUpdate",
"BTrees/tests/test_OOBTree.py::OOBucketPyConflictTests::testMergeDelete",
"BTrees/tests/test_OOBTree.py::OOBucketPyConflictTests::testMergeDeleteAndUpdate",
"BTrees/tests/test_OOBTree.py::OOBucketPyConflictTests::testMergeEmpty",
"BTrees/tests/test_OOBTree.py::OOBucketPyConflictTests::testMergeInserts",
"BTrees/tests/test_OOBTree.py::OOBucketPyConflictTests::testMergeInsertsFromEmpty",
"BTrees/tests/test_OOBTree.py::OOBucketPyConflictTests::testMergeUpdate",
"BTrees/tests/test_OOBTree.py::OOSetConflictTests::testFailMergeDelete",
"BTrees/tests/test_OOBTree.py::OOSetConflictTests::testFailMergeEmptyAndFill",
"BTrees/tests/test_OOBTree.py::OOSetConflictTests::testFailMergeInsert",
"BTrees/tests/test_OOBTree.py::OOSetConflictTests::testMergeDelete",
"BTrees/tests/test_OOBTree.py::OOSetConflictTests::testMergeEmpty",
"BTrees/tests/test_OOBTree.py::OOSetConflictTests::testMergeInserts",
"BTrees/tests/test_OOBTree.py::OOSetConflictTests::testMergeInsertsFromEmpty",
"BTrees/tests/test_OOBTree.py::OOSetPyConflictTests::testFailMergeDelete",
"BTrees/tests/test_OOBTree.py::OOSetPyConflictTests::testFailMergeEmptyAndFill",
"BTrees/tests/test_OOBTree.py::OOSetPyConflictTests::testFailMergeInsert",
"BTrees/tests/test_OOBTree.py::OOSetPyConflictTests::testMergeDelete",
"BTrees/tests/test_OOBTree.py::OOSetPyConflictTests::testMergeEmpty",
"BTrees/tests/test_OOBTree.py::OOSetPyConflictTests::testMergeInserts",
"BTrees/tests/test_OOBTree.py::OOSetPyConflictTests::testMergeInsertsFromEmpty",
"BTrees/tests/test_OOBTree.py::OOBTreeConflictTests::testFailMergeDelete",
"BTrees/tests/test_OOBTree.py::OOBTreeConflictTests::testFailMergeDeleteAndUpdate",
"BTrees/tests/test_OOBTree.py::OOBTreeConflictTests::testFailMergeEmptyAndFill",
"BTrees/tests/test_OOBTree.py::OOBTreeConflictTests::testFailMergeInsert",
"BTrees/tests/test_OOBTree.py::OOBTreeConflictTests::testFailMergeUpdate",
"BTrees/tests/test_OOBTree.py::OOBTreeConflictTests::testMergeDelete",
"BTrees/tests/test_OOBTree.py::OOBTreeConflictTests::testMergeDeleteAndUpdate",
"BTrees/tests/test_OOBTree.py::OOBTreeConflictTests::testMergeEmpty",
"BTrees/tests/test_OOBTree.py::OOBTreeConflictTests::testMergeInserts",
"BTrees/tests/test_OOBTree.py::OOBTreeConflictTests::testMergeInsertsFromEmpty",
"BTrees/tests/test_OOBTree.py::OOBTreeConflictTests::testMergeUpdate",
"BTrees/tests/test_OOBTree.py::OOBTreePyConflictTests::testFailMergeDelete",
"BTrees/tests/test_OOBTree.py::OOBTreePyConflictTests::testFailMergeDeleteAndUpdate",
"BTrees/tests/test_OOBTree.py::OOBTreePyConflictTests::testFailMergeEmptyAndFill",
"BTrees/tests/test_OOBTree.py::OOBTreePyConflictTests::testFailMergeInsert",
"BTrees/tests/test_OOBTree.py::OOBTreePyConflictTests::testFailMergeUpdate",
"BTrees/tests/test_OOBTree.py::OOBTreePyConflictTests::testMergeDelete",
"BTrees/tests/test_OOBTree.py::OOBTreePyConflictTests::testMergeDeleteAndUpdate",
"BTrees/tests/test_OOBTree.py::OOBTreePyConflictTests::testMergeEmpty",
"BTrees/tests/test_OOBTree.py::OOBTreePyConflictTests::testMergeInserts",
"BTrees/tests/test_OOBTree.py::OOBTreePyConflictTests::testMergeInsertsFromEmpty",
"BTrees/tests/test_OOBTree.py::OOBTreePyConflictTests::testMergeUpdate",
"BTrees/tests/test_OOBTree.py::OOTreeSetConflictTests::testFailMergeDelete",
"BTrees/tests/test_OOBTree.py::OOTreeSetConflictTests::testFailMergeEmptyAndFill",
"BTrees/tests/test_OOBTree.py::OOTreeSetConflictTests::testFailMergeInsert",
"BTrees/tests/test_OOBTree.py::OOTreeSetConflictTests::testMergeDelete",
"BTrees/tests/test_OOBTree.py::OOTreeSetConflictTests::testMergeEmpty",
"BTrees/tests/test_OOBTree.py::OOTreeSetConflictTests::testMergeInserts",
"BTrees/tests/test_OOBTree.py::OOTreeSetConflictTests::testMergeInsertsFromEmpty",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyConflictTests::testFailMergeDelete",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyConflictTests::testFailMergeEmptyAndFill",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyConflictTests::testFailMergeInsert",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyConflictTests::testMergeDelete",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyConflictTests::testMergeEmpty",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyConflictTests::testMergeInserts",
"BTrees/tests/test_OOBTree.py::OOTreeSetPyConflictTests::testMergeInsertsFromEmpty",
"BTrees/tests/test_OOBTree.py::OOModuleTest::testFamily",
"BTrees/tests/test_OOBTree.py::OOModuleTest::testModuleProvides",
"BTrees/tests/test_OOBTree.py::OOModuleTest::testNames",
"BTrees/tests/test_OOBTree.py::OOModuleTest::test_multiunion_not_present",
"BTrees/tests/test_OOBTree.py::OOModuleTest::test_weightedIntersection_not_present",
"BTrees/tests/test_OOBTree.py::OOModuleTest::test_weightedUnion_not_present",
"BTrees/tests/test_OOBTree.py::test_suite"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2016-12-22T20:41:55Z" | zpl-2.1 |
|
zopefoundation__DateTime-37 | diff --git a/CHANGES.rst b/CHANGES.rst
index a161db6..1811e84 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -4,7 +4,8 @@ Changelog
4.5 (unreleased)
----------------
-- Nothing changed yet.
+- Add ``__format__`` method for DateTime objects
+ (`#35 <https://github.com/zopefoundation/DateTime/issues/35>`_)
4.4 (2022-02-11)
diff --git a/src/DateTime/DateTime.py b/src/DateTime/DateTime.py
index 1f0fde7..f52e2f2 100644
--- a/src/DateTime/DateTime.py
+++ b/src/DateTime/DateTime.py
@@ -1795,6 +1795,14 @@ class DateTime(object):
return '%4.4d/%2.2d/%2.2d %2.2d:%2.2d:%06.6f %s' % (
y, m, d, h, mn, s, t)
+ def __format__(self, fmt):
+ """Render a DateTime in an f-string."""
+ if not isinstance(fmt, str):
+ raise TypeError("must be str, not %s" % type(fmt).__name__)
+ if len(fmt) != 0:
+ return self.strftime(fmt)
+ return str(self)
+
def __hash__(self):
"""Compute a hash value for a DateTime."""
return int(((self._year % 100 * 12 + self._month) * 31 +
| zopefoundation/DateTime | 3fc0626e05f11e899cb60d31177d531b29e53368 | diff --git a/src/DateTime/tests/test_datetime.py b/src/DateTime/tests/test_datetime.py
index ebb539a..49c31b6 100644
--- a/src/DateTime/tests/test_datetime.py
+++ b/src/DateTime/tests/test_datetime.py
@@ -39,7 +39,7 @@ else: # pragma: PY2
try:
__file__
-except NameError:
+except NameError: # pragma: no cover
f = sys.argv[0]
else:
f = __file__
@@ -683,6 +683,19 @@ class DateTimeTests(unittest.TestCase):
self.assertEqual(dt.__roles__, None)
self.assertEqual(dt.__allow_access_to_unprotected_subobjects__, 1)
+ @unittest.skipUnless(PY3K, 'format method is Python 3 only')
+ def test_format(self):
+ dt = DateTime(1968, 3, 10, 23, 45, 0, 'Europe/Vienna')
+ fmt = '%-d.%-m.%Y %H:%M'
+ result = dt.strftime(fmt)
+ unformatted_result = '1968/03/10 23:45:00 Europe/Vienna'
+ self.assertEqual(result, '{:%-d.%-m.%Y %H:%M}'.format(dt))
+ self.assertEqual(unformatted_result, '{:}'.format(dt))
+ self.assertEqual(unformatted_result, '{}'.format(dt))
+ eval("self.assertEqual(result, f'{dt:{fmt}}')")
+ eval("self.assertEqual(unformatted_result ,f'{dt:}')")
+ eval("self.assertEqual(unformatted_result, f'{dt}')")
+
def test_suite():
import doctest
| supporting fstring formatting
It would be great if DateTime could support the new fstring formatting like datetime already does:
```
import datetime, DateTime
for now in (datetime.datetime.now(), DateTime.DateTime()):
try:
print(type(now), f'{now = :%-d.%-m.%Y %H:%M}')
except TypeError as e:
print(type(now), e)
```
prints -->
```
<class 'datetime.datetime'> now = 26.5.2022 05:45
<class 'DateTime.DateTime.DateTime'> unsupported format string passed to DateTime.__format__
```
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_format"
] | [
"src/DateTime/tests/test_datetime.py::DateTimeTests::testAddPrecision",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testBasicTZ",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testBug1203",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConstructor3",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConstructor4",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConstructor5",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConstructor6",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConstructor7",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConversions",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testCopyConstructor",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testCopyConstructorPreservesTimezone",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testDSTInEffect",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testDSTNotInEffect",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testDayOfWeek",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testEDTTimezone",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testISO8601",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testInternationalDateformat",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testJulianWeek",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testOldDate",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testParseISO8601",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testRFC822",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testStrftimeFarDates",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testStrftimeTZhandling",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testStrftimeUnicode",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testSubtraction",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testTZ1add",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testTZ1diff",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testTZ1sub",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testTZ2",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testTZDiffDaylight",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testTimezoneNaiveHandling",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testY10KDate",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testZoneInFarDates",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_calcTimezoneName",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_compare_methods",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_compare_methods_none",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_interface",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_intl_format_hyphen",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle_old",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle_old_without_micros",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle_with_micros",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle_with_numerical_tz",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle_with_tz",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_security",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_tzoffset",
"src/DateTime/tests/test_datetime.py::test_suite"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2022-06-27T06:36:15Z" | zpl-2.1 |
|
zopefoundation__DateTime-42 | diff --git a/CHANGES.rst b/CHANGES.rst
index b1a8f10..68f43b1 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -4,12 +4,15 @@ Changelog
4.7 (unreleased)
----------------
+- Fix rounding problem with `DateTime` addition beyond the year 2038
+ (`#41 <https://github.com/zopefoundation/DateTime/issues/41>`_)
+
4.6 (2022-09-10)
----------------
- Fix ``__format__`` method for DateTime objects
- (`#39 <https://github.com/zopefoundation/DateTime/issues/39>`)
+ (`#39 <https://github.com/zopefoundation/DateTime/issues/39>`_)
4.5 (2022-07-04)
diff --git a/src/DateTime/DateTime.py b/src/DateTime/DateTime.py
index f52e2f2..94f3903 100644
--- a/src/DateTime/DateTime.py
+++ b/src/DateTime/DateTime.py
@@ -864,7 +864,7 @@ class DateTime(object):
# self._micros is the time since the epoch
# in long integer microseconds.
if microsecs is None:
- microsecs = long(math.floor(t * 1000000.0))
+ microsecs = long(round(t * 1000000.0))
self._micros = microsecs
def localZone(self, ltm=None):
@@ -1760,7 +1760,7 @@ class DateTime(object):
x = _calcDependentSecond(tz, t)
yr, mo, dy, hr, mn, sc = _calcYMDHMS(x, ms)
return self.__class__(yr, mo, dy, hr, mn, sc, self._tz,
- t, d, s, None, self.timezoneNaive())
+ t, d, s, tmicros, self.timezoneNaive())
__radd__ = __add__
| zopefoundation/DateTime | 09b3d6355b6b44d93922e995b0098dbed22f75ef | diff --git a/src/DateTime/tests/test_datetime.py b/src/DateTime/tests/test_datetime.py
index ead77b5..07d575a 100644
--- a/src/DateTime/tests/test_datetime.py
+++ b/src/DateTime/tests/test_datetime.py
@@ -103,6 +103,16 @@ class DateTimeTests(unittest.TestCase):
dt = DateTime()
self.assertEqual(str(dt + 0.10 + 3.14 + 6.76 - 10), str(dt),
dt)
+ # checks problem reported in
+ # https://github.com/zopefoundation/DateTime/issues/41
+ dt = DateTime(2038, 10, 7, 8, 52, 44.959840, "UTC")
+ self.assertEqual(str(dt + 0.10 + 3.14 + 6.76 - 10), str(dt),
+ dt)
+
+ def testConsistentSecondMicroRounding(self):
+ dt = DateTime(2038, 10, 7, 8, 52, 44.9598398, "UTC")
+ self.assertEqual(int(dt.second() * 1000000),
+ dt.micros() % 60000000)
def testConstructor3(self):
# Constructor from date/time string
| tests fail after 2038-01-10
## BUG/PROBLEM REPORT (OR OTHER COMMON ISSUE)
### What I did:
run tests on 2038-01-10
on openSUSE, I do
```bash
osc co openSUSE:Factory/python-DateTime && cd $_
osc build --vm-type=kvm --noservice --clean --build-opt=--vm-custom-opt="-rtc base=2038-01-10T00:00:00" --alternative-project=home:bmwiedemann:reproducible openSUSE_Tumbleweed
```
### What I expect to happen:
tests should continue to pass in future
### What actually happened:
3 tests failed:
```
def testAddPrecision(self):
# Precision of serial additions
dt = DateTime()
> self.assertEqual(str(dt + 0.10 + 3.14 + 6.76 - 10), str(dt),
dt)
E AssertionError: '2038/10/07 08:52:44.959838 UTC' != '2038/10/07 08:52:44.959840 UTC'
E - 2038/10/07 08:52:44.959838 UTC
E ? ^^
E + 2038/10/07 08:52:44.959840 UTC
E ? ^^
E : 2038/10/07 08:52:44.959840 UTC
FAILED src/DateTime/tests/test_datetime.py::DateTimeTests::testAddPrecision
FAILED src/DateTime/tests/test_datetime.py::DateTimeTests::testConstructor4
FAILED src/DateTime/tests/test_datetime.py::DateTimeTests::testSubtraction - ...
```
### What version of Python and Zope/Addons I am using:
openSUSE-Tumbleweed 20220907
python-3.8
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/DateTime/tests/test_datetime.py::DateTimeTests::testAddPrecision"
] | [
"src/DateTime/tests/test_datetime.py::DateTimeTests::testBasicTZ",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testBug1203",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConsistentSecondMicroRounding",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConstructor3",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConstructor4",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConstructor5",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConstructor6",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConstructor7",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConversions",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testCopyConstructor",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testCopyConstructorPreservesTimezone",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testDSTInEffect",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testDSTNotInEffect",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testDayOfWeek",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testEDTTimezone",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testISO8601",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testInternationalDateformat",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testJulianWeek",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testOldDate",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testParseISO8601",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testRFC822",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testStrftimeFarDates",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testStrftimeTZhandling",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testStrftimeUnicode",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testSubtraction",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testTZ1add",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testTZ1diff",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testTZ1sub",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testTZ2",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testTZDiffDaylight",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testTimezoneNaiveHandling",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testY10KDate",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testZoneInFarDates",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_calcTimezoneName",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_compare_methods",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_compare_methods_none",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_format",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_interface",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_intl_format_hyphen",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle_old",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle_old_without_micros",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle_with_micros",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle_with_numerical_tz",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle_with_tz",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_security",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_tzoffset",
"src/DateTime/tests/test_datetime.py::test_suite"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2022-09-13T07:39:50Z" | zpl-2.1 |
|
zopefoundation__DateTime-61 | diff --git a/CHANGES.rst b/CHANGES.rst
index 3ee820c..082d109 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -7,6 +7,9 @@ Changelog
- Fix ``UnknownTimeZoneError`` when unpickling ``DateTime.DateTime().asdatetime()``.
(`#58 <https://github.com/zopefoundation/DateTime/issues/58>`_)
+- Repair equality comparison between DateTime instances and other types.
+ (`#60 <https://github.com/zopefoundation/DateTime/issues/60>`_)
+
5.3 (2023-11-14)
----------------
diff --git a/src/DateTime/DateTime.py b/src/DateTime/DateTime.py
index 1835705..8e1ec6d 100644
--- a/src/DateTime/DateTime.py
+++ b/src/DateTime/DateTime.py
@@ -1250,8 +1250,10 @@ class DateTime:
return True
if isinstance(t, (float, int)):
return self._micros > long(t * 1000000)
- else:
+ try:
return self._micros > t._micros
+ except AttributeError:
+ return self._micros > t
__gt__ = greaterThan
@@ -1271,8 +1273,10 @@ class DateTime:
return True
if isinstance(t, (float, int)):
return self._micros >= long(t * 1000000)
- else:
+ try:
return self._micros >= t._micros
+ except AttributeError:
+ return self._micros >= t
__ge__ = greaterThanEqualTo
@@ -1291,8 +1295,10 @@ class DateTime:
return False
if isinstance(t, (float, int)):
return self._micros == long(t * 1000000)
- else:
+ try:
return self._micros == t._micros
+ except AttributeError:
+ return self._micros == t
def notEqualTo(self, t):
"""Compare this DateTime object to another DateTime object
@@ -1336,8 +1342,10 @@ class DateTime:
return False
if isinstance(t, (float, int)):
return self._micros < long(t * 1000000)
- else:
+ try:
return self._micros < t._micros
+ except AttributeError:
+ return self._micros < t
__lt__ = lessThan
@@ -1356,8 +1364,10 @@ class DateTime:
return False
if isinstance(t, (float, int)):
return self._micros <= long(t * 1000000)
- else:
+ try:
return self._micros <= t._micros
+ except AttributeError:
+ return self._micros <= t
__le__ = lessThanEqualTo
| zopefoundation/DateTime | 955f3b920b2020c2407e7d9f4aa24e6ef7d20d9d | diff --git a/src/DateTime/tests/test_datetime.py b/src/DateTime/tests/test_datetime.py
index 827d002..ae67d45 100644
--- a/src/DateTime/tests/test_datetime.py
+++ b/src/DateTime/tests/test_datetime.py
@@ -219,6 +219,8 @@ class DateTimeTests(unittest.TestCase):
self.assertFalse(dt.equalTo(dt1))
# Compare a date to float
dt = DateTime(1.0)
+ self.assertTrue(dt == DateTime(1.0)) # testing __eq__
+ self.assertFalse(dt != DateTime(1.0)) # testing __ne__
self.assertFalse(dt.greaterThan(1.0))
self.assertTrue(dt.greaterThanEqualTo(1.0))
self.assertFalse(dt.lessThan(1.0))
@@ -228,12 +230,26 @@ class DateTimeTests(unittest.TestCase):
# Compare a date to int
dt = DateTime(1)
self.assertEqual(dt, DateTime(1.0))
+ self.assertTrue(dt == DateTime(1)) # testing __eq__
+ self.assertFalse(dt != DateTime(1)) # testing __ne__
self.assertFalse(dt.greaterThan(1))
self.assertTrue(dt.greaterThanEqualTo(1))
self.assertFalse(dt.lessThan(1))
self.assertTrue(dt.lessThanEqualTo(1))
self.assertFalse(dt.notEqualTo(1))
self.assertTrue(dt.equalTo(1))
+ # Compare a date to string; there is no implicit type conversion
+ # but behavior if consistent as when comparing, for example, an int
+ # and a string.
+ dt = DateTime("2023")
+ self.assertFalse(dt == "2023") # testing __eq__
+ self.assertTrue(dt != "2023") # testing __ne__
+ self.assertRaises(TypeError, dt.greaterThan, "2023")
+ self.assertRaises(TypeError, dt.greaterThanEqualTo, "2023")
+ self.assertRaises(TypeError, dt.lessThan, "2023")
+ self.assertRaises(TypeError, dt.lessThanEqualTo, "2023")
+ self.assertTrue(dt.notEqualTo("2023"))
+ self.assertFalse(dt.equalTo("2023"))
def test_compare_methods_none(self):
# Compare a date to None
| `DateTime.DateTime.equalTo` now breaks with string argument
## BUG/PROBLEM REPORT / FEATURE REQUEST
Since DateTime 5.2, using `DateTime.DateTime.equalTo` with something else than a `DateTime` or a number throws `AttributeError`. This is a regression from https://github.com/zopefoundation/DateTime/pull/54 ( cc @fdiary )
### What I did:
```
>>> import DateTime
>>> DateTime.DateTime() == ""
False
>>> DateTime.DateTime().equalTo("")
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "./DateTime/src/DateTime/DateTime.py", line 1295, in equalTo
return self._micros == t._micros
AttributeError: 'str' object has no attribute '_micros'
```
### What I expect to happen:
`DateTime.DateTime().equalTo("")` should be `False`
### What actually happened:
`AttributeError: 'str' object has no attribute '_micros'`
### What version of Python and Zope/Addons I am using:
This is current master branch 955f3b920b2020c2407e7d9f4aa24e6ef7d20d9d
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_compare_methods"
] | [
"src/DateTime/tests/test_datetime.py::DateTimeTests::testAddPrecision",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testBasicTZ",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testBug1203",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConsistentSecondMicroRounding",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConstructor3",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConstructor4",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConstructor5",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConstructor6",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConstructor7",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConversions",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testCopyConstructor",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testCopyConstructorPreservesTimezone",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testDSTInEffect",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testDSTNotInEffect",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testDayOfWeek",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testEDTTimezone",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testISO8601",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testInternationalDateformat",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testJulianWeek",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testOldDate",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testParseISO8601",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testRFC822",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testStrftimeFarDates",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testStrftimeStr",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testStrftimeTZhandling",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testSubtraction",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testTZ1add",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testTZ1diff",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testTZ1sub",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testTZ2",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testTZDiffDaylight",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testTimezoneNaiveHandling",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testY10KDate",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testZoneInFarDates",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_calcTimezoneName",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_compare_methods_none",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_format",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_interface",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_intl_format_hyphen",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle_asdatetime_with_tz",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle_old",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle_old_without_micros",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle_with_micros",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle_with_numerical_tz",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle_with_tz",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_security",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_tzoffset",
"src/DateTime/tests/test_datetime.py::test_suite"
] | {
"failed_lite_validators": [
"has_git_commit_hash",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2023-12-03T15:04:47Z" | zpl-2.1 |
|
zopefoundation__DateTime-62 | diff --git a/CHANGES.rst b/CHANGES.rst
index b483525..e9e31d1 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -6,6 +6,10 @@ Changelog
- Nothing changed yet.
+- Change pickle format to export the microseconds as an int, to
+ solve a problem with dates after 2038.
+ (`#56 <https://github.com/zopefoundation/DateTime/issues/56>`_)
+
5.4 (2023-12-15)
----------------
diff --git a/src/DateTime/DateTime.py b/src/DateTime/DateTime.py
index 8e1ec6d..fc289e6 100644
--- a/src/DateTime/DateTime.py
+++ b/src/DateTime/DateTime.py
@@ -446,17 +446,19 @@ class DateTime:
raise SyntaxError('Unable to parse {}, {}'.format(args, kw))
def __getstate__(self):
- # We store a float of _micros, instead of the _micros long, as we most
- # often don't have any sub-second resolution and can save those bytes
- return (self._micros / 1000000.0,
+ return (self._micros,
getattr(self, '_timezone_naive', False),
self._tz)
def __setstate__(self, value):
if isinstance(value, tuple):
- self._parse_args(value[0], value[2])
- self._micros = long(value[0] * 1000000)
- self._timezone_naive = value[1]
+ micros, tz_naive, tz = value
+ if isinstance(micros, float):
+ # BBB: support for pickle where micros was a float
+ micros = int(micros * 1000000)
+ self._parse_args(micros / 1000000., tz)
+ self._micros = micros
+ self._timezone_naive = tz_naive
else:
for k, v in value.items():
if k in self.__slots__:
| zopefoundation/DateTime | e892a9d360abba6e8abe1c4a7e48f52efa9c1e72 | diff --git a/src/DateTime/tests/test_datetime.py b/src/DateTime/tests/test_datetime.py
index ae67d45..f4c2644 100644
--- a/src/DateTime/tests/test_datetime.py
+++ b/src/DateTime/tests/test_datetime.py
@@ -338,6 +338,24 @@ class DateTimeTests(unittest.TestCase):
for key in DateTime.__slots__:
self.assertEqual(getattr(dt, key), getattr(new, key))
+ def test_pickle_dates_after_2038(self):
+ dt = DateTime('2039/09/02 07:07:6.235027 GMT+1')
+ data = pickle.dumps(dt, 1)
+ new = pickle.loads(data)
+ for key in DateTime.__slots__:
+ self.assertEqual(getattr(dt, key), getattr(new, key))
+
+ def test_pickle_old_with_micros_as_float(self):
+ dt = DateTime('2002/5/2 8:00am GMT+0')
+ data = (
+ 'ccopy_reg\n_reconstructor\nq\x00(cDateTime.DateTime\nDateTime'
+ '\nq\x01c__builtin__\nobject\nq\x02Ntq\x03Rq\x04(GA\xcehy\x00\x00'
+ '\x00\x00I00\nX\x05\x00\x00\x00GMT+0q\x05tq\x06b.')
+ data = data.encode('latin-1')
+ new = pickle.loads(data)
+ for key in DateTime.__slots__:
+ self.assertEqual(getattr(dt, key), getattr(new, key))
+
def testTZ2(self):
# Time zone manipulation test 2
dt = DateTime()
| tests fail in 2038
## BUG/PROBLEM REPORT / FEATURE REQUEST
<!--
Please do not report security-related issues here. Report them by email to [email protected]. The Security Team will contact the relevant maintainer if necessary.
Include tracebacks, screenshots, code of debugging sessions or code that reproduces the issue if possible.
The best reproductions are in plain Zope installations without addons or at least with minimal needed addons installed.
-->
### What I did:
<!-- Enter a reproducible description, including preconditions. -->
```
osc co openSUSE:Factory/python-DateTime && cd $_
osc build --vm-type=kvm --noservice --clean --build-opt=--vm-custom-opt="-rtc base=2039-09-02T06:07:00" --alternative-project=home:bmwiedemann:reproducible openSUSE_Tumbleweed
```
### What I expect to happen:
tests should keep working in the future (at least 16 years)
### What actually happened:
similar to issue #41 in that there is a rounding error in `DateTime-5.2` that can randomly break a test.
```
=================================== FAILURES ===================================
__________________________ DateTimeTests.test_pickle ___________________________
self = <DateTime.tests.test_datetime.DateTimeTests testMethod=test_pickle>
def test_pickle(self):
dt = DateTime()
data = pickle.dumps(dt, 1)
new = pickle.loads(data)
for key in DateTime.__slots__:
> self.assertEqual(getattr(dt, key), getattr(new, key))
E AssertionError: 2198556426235027 != 2198556426235026
src/DateTime/tests/test_datetime.py:253: AssertionError
=============================== warnings summary ===============================
```
### What version of Python and Zope/Addons I am using:
openSUSE-Tumbleweed-20230729 python3.10
<!-- Enter Operating system, Python and Zope versions you are using -->
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle_dates_after_2038"
] | [
"src/DateTime/tests/test_datetime.py::DateTimeTests::testAddPrecision",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testBasicTZ",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testBug1203",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConsistentSecondMicroRounding",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConstructor3",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConstructor4",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConstructor5",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConstructor6",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConstructor7",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testConversions",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testCopyConstructor",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testCopyConstructorPreservesTimezone",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testDSTInEffect",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testDSTNotInEffect",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testDayOfWeek",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testEDTTimezone",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testISO8601",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testInternationalDateformat",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testJulianWeek",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testOldDate",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testParseISO8601",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testRFC822",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testStrftimeFarDates",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testStrftimeStr",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testStrftimeTZhandling",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testSubtraction",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testTZ1add",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testTZ1diff",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testTZ1sub",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testTZ2",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testTZDiffDaylight",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testTimezoneNaiveHandling",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testY10KDate",
"src/DateTime/tests/test_datetime.py::DateTimeTests::testZoneInFarDates",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_calcTimezoneName",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_compare_methods",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_compare_methods_none",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_format",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_interface",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_intl_format_hyphen",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle_asdatetime_with_tz",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle_old",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle_old_with_micros_as_float",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle_old_without_micros",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle_with_micros",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle_with_numerical_tz",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_pickle_with_tz",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_security",
"src/DateTime/tests/test_datetime.py::DateTimeTests::test_tzoffset",
"src/DateTime/tests/test_datetime.py::test_suite"
] | {
"failed_lite_validators": [
"has_issue_reference",
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2024-03-20T14:45:08Z" | zpl-2.1 |
|
zopefoundation__DocumentTemplate-18 | diff --git a/CHANGES.rst b/CHANGES.rst
index 18c8924..209e47d 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -9,6 +9,8 @@ Changelog
- No longer use icons which got deleted in Zope 4.
+- Fix sorting in <dtml-in> for duplicate entries in Python 3.
+
3.0b2 (2017-11-03)
------------------
diff --git a/src/DocumentTemplate/DT_In.py b/src/DocumentTemplate/DT_In.py
index f9b8150..4c6872d 100644
--- a/src/DocumentTemplate/DT_In.py
+++ b/src/DocumentTemplate/DT_In.py
@@ -330,6 +330,7 @@
'''
+from operator import itemgetter
import sys
import re
@@ -837,7 +838,10 @@ class InClass(object):
by = SortBy(multsort, sf_list)
s.sort(by)
else:
- s.sort()
+ # In python 3 a key is required when tuples in the list have
+ # the same sort key to prevent attempting to compare the second
+ # item which is dict.
+ s.sort(key=itemgetter(0))
sequence = []
for k, client in s:
diff --git a/src/TreeDisplay/TreeTag.py b/src/TreeDisplay/TreeTag.py
index 69e28b8..414200c 100644
--- a/src/TreeDisplay/TreeTag.py
+++ b/src/TreeDisplay/TreeTag.py
@@ -395,10 +395,10 @@ def tpRenderTABLE(self, id, root_url, url, state, substate, diff, data,
if exp:
ptreeData['tree-item-expanded'] = 1
output('<a name="%s" href="%s?%stree-c=%s#%s">-</a>' %
- (id, root_url, param, s, id, script))
+ (id, root_url, param, s, id))
else:
output('<a name="%s" href="%s?%stree-e=%s#%s">+</a>' %
- (id, root_url, param, s, id, script))
+ (id, root_url, param, s, id))
output('</td>\n')
else:
| zopefoundation/DocumentTemplate | 6af41a0957407a40e02210926c63810d7bbe53ff | diff --git a/src/DocumentTemplate/tests/test_DT_In.py b/src/DocumentTemplate/tests/test_DT_In.py
new file mode 100644
index 0000000..ba517d2
--- /dev/null
+++ b/src/DocumentTemplate/tests/test_DT_In.py
@@ -0,0 +1,34 @@
+import unittest
+
+
+class DummySection(object):
+ blocks = ['dummy']
+
+
+class TestIn(unittest.TestCase):
+ """Testing ..DT_in.InClass."""
+
+ def _getTargetClass(self):
+ from DocumentTemplate.DT_In import InClass
+ return InClass
+
+ def _makeOne(self, *args):
+ blocks = [('in', ' '.join(args), DummySection())]
+ return self._getTargetClass()(blocks)
+
+ def test_sort_sequence(self):
+ """It does not break on duplicate sort keys at a list of dicts."""
+ stmt = self._makeOne('seq', 'mapping', 'sort=key')
+ seq = [
+ {'key': 'c', 'data': '3'},
+ {'key': 'a', 'data': '1'},
+ {'key': 'b', 'data': '2'},
+ {'key': 'a', 'data': '2'},
+ ]
+ result = stmt.sort_sequence(seq, 'key')
+ self.assertEqual([
+ {'key': 'a', 'data': '1'},
+ {'key': 'a', 'data': '2'},
+ {'key': 'b', 'data': '2'},
+ {'key': 'c', 'data': '3'},
+ ], result)
diff --git a/src/DocumentTemplate/tests/test_DT_Var.py b/src/DocumentTemplate/tests/test_DT_Var.py
index 3270824..c81051f 100644
--- a/src/DocumentTemplate/tests/test_DT_Var.py
+++ b/src/DocumentTemplate/tests/test_DT_Var.py
@@ -73,11 +73,11 @@ class TestUrlQuoting(unittest.TestCase):
utf8_value = unicode_value.encode('UTF-8')
quoted_utf8_value = b'G%C3%BCnther%20M%C3%BCller'
- self.assertEquals(url_quote(unicode_value), quoted_unicode_value)
- self.assertEquals(url_quote(utf8_value), quoted_utf8_value)
+ self.assertEqual(url_quote(unicode_value), quoted_unicode_value)
+ self.assertEqual(url_quote(utf8_value), quoted_utf8_value)
- self.assertEquals(url_unquote(quoted_unicode_value), unicode_value)
- self.assertEquals(url_unquote(quoted_utf8_value), utf8_value)
+ self.assertEqual(url_unquote(quoted_unicode_value), unicode_value)
+ self.assertEqual(url_unquote(quoted_utf8_value), utf8_value)
def test_url_quoting_plus(self):
from DocumentTemplate.DT_Var import url_quote_plus
@@ -87,10 +87,10 @@ class TestUrlQuoting(unittest.TestCase):
utf8_value = unicode_value.encode('UTF-8')
quoted_utf8_value = b'G%C3%BCnther+M%C3%BCller'
- self.assertEquals(url_quote_plus(unicode_value), quoted_unicode_value)
- self.assertEquals(url_quote_plus(utf8_value), quoted_utf8_value)
+ self.assertEqual(url_quote_plus(unicode_value), quoted_unicode_value)
+ self.assertEqual(url_quote_plus(utf8_value), quoted_utf8_value)
- self.assertEquals(
+ self.assertEqual(
url_unquote_plus(quoted_unicode_value), unicode_value)
- self.assertEquals(
+ self.assertEqual(
url_unquote_plus(quoted_utf8_value), utf8_value)
| <dtml-in list_of_dicts mapping sort=name> breaks for duplicate names
Scenario:
```python
list_of_dicts = [{'name': 'a'}, {'name': 'b'}, {'name': 'a'}]
```
In DTML call:
```
<dtml-in list_of_dicts mapping sort=name>
```
It breaks because internally `dtml-in` changes the list to
```python
[('a', {'name': 'a'}), ('b', {'name': 'b'}), ('a', {'name': 'a'})]
```
There is no problem as long as the list does not contain duplicates of the sort key. If there are duplicates, Python has to compare the dicts when sorting. This works fine on Python 2 but it is no loner defined on Python 3. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/DocumentTemplate/tests/test_DT_In.py::TestIn::test_sort_sequence"
] | [
"src/DocumentTemplate/tests/test_DT_Var.py::TestNewlineToBr::test_newline_to_br",
"src/DocumentTemplate/tests/test_DT_Var.py::TestNewlineToBr::test_newline_to_br_tainted",
"src/DocumentTemplate/tests/test_DT_Var.py::TestUrlQuoting::test_url_quoting",
"src/DocumentTemplate/tests/test_DT_Var.py::TestUrlQuoting::test_url_quoting_plus"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2018-03-22T18:38:05Z" | zpl-2.1 |
|
zopefoundation__DocumentTemplate-29 | diff --git a/CHANGES.rst b/CHANGES.rst
index 570eeab..86e2a22 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -4,10 +4,21 @@ Changelog
3.0b5 (unreleased)
------------------
+- Fix regression with exception handling in ``<dtml-except>`` with Python 2.
+ (`#25 <https://github.com/zopefoundation/DocumentTemplate/issues/25>`_)
+
- Stabilized TreeTag rendering for objects without ``_p_oid`` values.
+ (`#26 <https://github.com/zopefoundation/DocumentTemplate/issues/26>`_)
- Added support for Python 3.7.
+- Remove support for string exceptions in ``<dtml-except>``.
+ (`#29 <https://github.com/zopefoundation/DocumentTemplate/pull/29>`_)
+
+- Fix handling of parsing ``ParseError``s in Python 3.
+ (`#29 <https://github.com/zopefoundation/DocumentTemplate/pull/29>`_)
+
+
3.0b4 (2018-07-12)
------------------
diff --git a/src/DocumentTemplate/DT_String.py b/src/DocumentTemplate/DT_String.py
index 1b0589d..2a0a783 100644
--- a/src/DocumentTemplate/DT_String.py
+++ b/src/DocumentTemplate/DT_String.py
@@ -175,7 +175,7 @@ class String(object):
try:
tag, args, command, coname = self._parseTag(mo)
except ParseError as m:
- self.parse_error(m[0], m[1], text, l_)
+ self.parse_error(m.args[0], m.args[1], text, l_)
s = text[start:l_]
if s:
@@ -195,7 +195,7 @@ class String(object):
r = r.simple_form
result.append(r)
except ParseError as m:
- self.parse_error(m[0], tag, text, l_)
+ self.parse_error(m.args[0], tag, text, l_)
mo = tagre.search(text, start)
@@ -234,7 +234,7 @@ class String(object):
try:
tag, args, command, coname = self._parseTag(mo, scommand, sa)
except ParseError as m:
- self.parse_error(m[0], m[1], text, l_)
+ self.parse_error(m.args[0], m.args[1], text, l_)
if command:
start = l_ + len(tag)
@@ -264,7 +264,7 @@ class String(object):
r = r.simple_form
result.append(r)
except ParseError as m:
- self.parse_error(m[0], stag, text, l_)
+ self.parse_error(m.args[0], stag, text, l_)
return start
@@ -279,7 +279,7 @@ class String(object):
try:
tag, args, command, coname = self._parseTag(mo, scommand, sa)
except ParseError as m:
- self.parse_error(m[0], m[1], text, l_)
+ self.parse_error(m.args[0], m.args[1], text, l_)
start = l_ + len(tag)
if command:
diff --git a/src/DocumentTemplate/DT_Try.py b/src/DocumentTemplate/DT_Try.py
index 3a2bfbd..972eb56 100644
--- a/src/DocumentTemplate/DT_Try.py
+++ b/src/DocumentTemplate/DT_Try.py
@@ -14,7 +14,7 @@
import sys
import traceback
-from io import StringIO
+from six import StringIO
from DocumentTemplate.DT_Util import ParseError, parse_params, render_blocks
from DocumentTemplate.DT_Util import namespace, InstanceDict
from DocumentTemplate.DT_Return import DTReturn
@@ -154,10 +154,7 @@ class Try(object):
except Exception:
# but an error occurs.. save the info.
t, v = sys.exc_info()[:2]
- if isinstance(t, str):
- errname = t
- else:
- errname = t.__name__
+ errname = t.__name__
handler = self.find_handler(t)
@@ -196,12 +193,6 @@ class Try(object):
def find_handler(self, exception):
"recursively search for a handler for a given exception"
- if isinstance(exception, str):
- for e, h in self.handlers:
- if exception == e or e == '':
- return h
- else:
- return None
for e, h in self.handlers:
if (e == exception.__name__ or
e == '' or self.match_base(exception, e)):
diff --git a/tox.ini b/tox.ini
index 573cf02..d3f6891 100644
--- a/tox.ini
+++ b/tox.ini
@@ -30,7 +30,7 @@ commands =
coverage combine
coverage html
coverage xml
- coverage report --fail-under=67
+ coverage report --fail-under=71
[testenv:flake8]
basepython = python3.6
| zopefoundation/DocumentTemplate | 44015836dbbea9670ca44a2152d3f10a16512bfb | diff --git a/src/DocumentTemplate/tests/test_DT_Try.py b/src/DocumentTemplate/tests/test_DT_Try.py
new file mode 100644
index 0000000..8f5950d
--- /dev/null
+++ b/src/DocumentTemplate/tests/test_DT_Try.py
@@ -0,0 +1,230 @@
+import unittest
+
+from DocumentTemplate.DT_Util import ParseError
+from DocumentTemplate.DT_Raise import InvalidErrorTypeExpression
+
+
+class DT_Try_Tests(unittest.TestCase):
+ """Testing ..DT_Try.Try."""
+
+ def _get_doc_class(self):
+ from DocumentTemplate.DT_HTML import HTML
+ return HTML
+
+ doc_class = property(_get_doc_class,)
+
+ def test_DT_Try__Try____init__1(self):
+ """It allows only one else block."""
+ html = self.doc_class(
+ '<dtml-try>'
+ 'Variable "name": '
+ '<dtml-except>'
+ '<dtml-else>'
+ '<dtml-var expr="str(100)">'
+ '<dtml-else>'
+ '<dtml-var expr="str(110)">'
+ '</dtml-try>')
+ with self.assertRaisesRegexp(ParseError, '^No more than one else '):
+ html()
+
+ def test_DT_Try__Try____init__2(self):
+ """It allows the else block only in last position."""
+ html = self.doc_class(
+ '<dtml-try>'
+ 'Variable "name": '
+ '<dtml-else>'
+ '<dtml-var expr="str(100)">'
+ '<dtml-except>'
+ '</dtml-try>')
+ with self.assertRaisesRegexp(
+ ParseError, '^The else block should be the last '):
+ html()
+
+ def test_DT_Try__Try____init__3(self):
+ """It allows no except block with a finally block."""
+ html = self.doc_class(
+ '<dtml-try>'
+ 'Variable "name": '
+ '<dtml-except>'
+ '<dtml-finally>'
+ '<dtml-var expr="str(100)">'
+ '</dtml-try>')
+ with self.assertRaisesRegexp(
+ ParseError, '^A try..finally combination cannot '):
+ html()
+
+ def test_DT_Try__Try____init__4(self):
+ """It allows only one default exception handler."""
+ html = self.doc_class(
+ '<dtml-try>'
+ 'Variable "name": '
+ '<dtml-except>'
+ '<dtml-var expr="str(100)">'
+ '<dtml-except>'
+ '<dtml-var expr="str(110)">'
+ '</dtml-try>')
+ with self.assertRaisesRegexp(
+ ParseError, '^Only one default exception handler '):
+ html()
+
+ def test_DT_Try__Try__01(self):
+ """It renders a try block if no exception occurs."""
+ html = self.doc_class(
+ '<dtml-try>'
+ 'Variable "name": '
+ '<dtml-var expr="str(100)">'
+ '</dtml-try>')
+ res = html()
+ expected = 'Variable "name": 100'
+ self.assertEqual(res, expected)
+
+ def test_DT_Try__Try__02(self):
+ """It renders the except block if an exception occurs."""
+ html = self.doc_class(
+ '<dtml-try>'
+ 'Variable "name": '
+ '<dtml-var expr="not_defined">'
+ '<dtml-except>'
+ 'Exception variable: '
+ '<dtml-var expr="str(100)">'
+ '</dtml-try>')
+ res = html()
+ expected = 'Exception variable: 100'
+ self.assertEqual(res, expected)
+
+ def test_DT_Try__Try__03(self):
+ """It renders the else block if no exception occurs."""
+ html = self.doc_class(
+ '<dtml-try>'
+ 'Variable "name": '
+ '<dtml-var expr="str(100)"> '
+ '<dtml-except>'
+ 'Exception variable: '
+ '<dtml-var expr="str(110)"> '
+ '<dtml-else>'
+ 'Else variable: '
+ '<dtml-var expr="str(111)"> '
+ '</dtml-try>')
+ res = html()
+ expected = ('Variable "name": 100 '
+ 'Else variable: 111 ')
+ self.assertEqual(res, expected)
+
+ def test_DT_Try__Try__04(self):
+ """It executes the finally block if no exception occurs."""
+ html = self.doc_class(
+ '<dtml-call expr="dummy_list.append(110)">'
+ '<dtml-try>'
+ 'Variable "name": '
+ '<dtml-var expr="str(100)"> '
+ '<dtml-finally>'
+ 'Finally variable: '
+ '<dtml-var expr="str(111)"> '
+ '<dtml-call expr="dummy_list.pop(0)">'
+ '</dtml-try>')
+ dummy_list = [100]
+
+ res = html(dummy_list=dummy_list)
+ expected = ('Variable "name": 100 '
+ 'Finally variable: 111 ')
+ self.assertEqual(res, expected)
+ # 100 got removed in the finally block.
+ self.assertEqual(dummy_list, [110])
+
+ def test_DT_Try__Try__05(self):
+ """It executes the finally block if an exception occurs."""
+ html = self.doc_class(
+ '<dtml-call expr="dummy_list.append(110)">'
+ '<dtml-try>'
+ 'Variable "name": '
+ '<dtml-var expr="not_defined"> '
+ '<dtml-finally>'
+ 'Finally variable: '
+ '<dtml-call expr="dummy_list.pop(0)"> '
+ '</dtml-try>')
+ dummy_list = [100]
+
+ with self.assertRaises(NameError):
+ html(dummy_list=dummy_list)
+ # 100 got removed in the finally block.
+ self.assertEqual(dummy_list, [110])
+
+ def test_DT_Try__Try__06(self):
+ """It allows different exception handlers."""
+ html = self.doc_class(
+ '<dtml-try>'
+ 'Variable "name": '
+ '<dtml-var expr="not_defined">'
+ '<dtml-except KeyError>'
+ 'Exception variable: '
+ '<dtml-var expr="str(100)">'
+ '<dtml-except NameError>'
+ 'Exception variable: '
+ '<dtml-var expr="str(110)">'
+ '</dtml-try>')
+ res = html()
+ expected = 'Exception variable: 110'
+ self.assertEqual(res, expected)
+
+ def test_DT_Try__Try__07(self):
+ """It catches errors with handler for base exception."""
+ html = self.doc_class(
+ '<dtml-try>'
+ 'Variable "name": '
+ '<dtml-raise KeyError></dtml-raise>'
+ '<dtml-except NameError>'
+ 'Exception variable: '
+ '<dtml-var expr="str(100)">'
+ '<dtml-except LookupError>'
+ 'Exception variable: '
+ '<dtml-var expr="str(110)">'
+ '</dtml-try>')
+ res = html()
+ expected = 'Exception variable: 110'
+ self.assertEqual(res, expected)
+
+ def test_DT_Try__Try__08(self):
+ """It raises the occurred exception if no exception handler matches."""
+ html = self.doc_class(
+ '<dtml-try>'
+ 'Variable "name": '
+ '<dtml-var expr="not_defined">'
+ '<dtml-except KeyError>'
+ 'Exception variable: '
+ '<dtml-var expr="str(100)">'
+ '<dtml-except AttributeError>'
+ 'Exception variable: '
+ '<dtml-var expr="str(110)">'
+ '</dtml-try>')
+ with self.assertRaises(NameError):
+ html()
+
+ def test_DT_Try__Try__09(self):
+ """It returns a dtml-return immediately."""
+ html = self.doc_class(
+ '<dtml-try>'
+ 'Variable "name": '
+ '<dtml-return ret>'
+ '<dtml-raise KeyError></dtml-raise>'
+ '<dtml-except LookupError>'
+ 'Exception variable: '
+ '<dtml-var expr="str(110)">'
+ '</dtml-try>')
+ res = html(ret='Return variable: 101')
+ expected = 'Return variable: 101'
+ self.assertEqual(res, expected)
+
+ def test_DT_Try__Try__10(self):
+ """It does not break with strings as exceptions but raises a well
+
+ defined exception in that case."""
+ html = self.doc_class(
+ '<dtml-try>'
+ 'Variable "name": '
+ '<dtml-raise "FakeError"></dtml-raise>'
+ '<dtml-except NameError>'
+ 'Exception variable: '
+ '<dtml-var expr="str(110)">'
+ '</dtml-try>')
+ with self.assertRaises(InvalidErrorTypeExpression):
+ html()
| <dtml-except> breaks on Python 2
Traceback:
```python
src/Zope/src/App/special_dtml.py:203: in _exec
result = render_blocks(self._v_blocks, ns)
.../DocumentTemplate-3.0b4-py2.7.egg/DocumentTemplate/_DocumentTemplate.py:148: in render_blocks
render_blocks_(blocks, rendered, md)
.../DocumentTemplate-3.0b4-py2.7.egg/DocumentTemplate/_DocumentTemplate.py:249: in render_blocks_
block = block(md)
.../DocumentTemplate-3.0b4-py2.7.egg/DocumentTemplate/DT_Try.py:142: in render
return self.render_try_except(md)
.../DocumentTemplate-3.0b4-py2.7.egg/DocumentTemplate/DT_Try.py:171: in render_try_except
traceback.print_exc(100, f)
/usr/lib64/python2.7/traceback.py:233: in print_exc
print_exception(etype, value, tb, limit, file)
/usr/lib64/python2.7/traceback.py:124: in print_exception
_print(file, 'Traceback (most recent call last):')
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
file = <_io.StringIO object at 0x7f8ef106e150>, str = 'Traceback (most recent call last):', terminator = '\n'
def _print(file, str='', terminator='\n'):
> file.write(str+terminator)
E TypeError: unicode argument expected, got 'str'
```
Reason: The used `io.StringIO` in `DT_Try.py` expects `unicode` to be written to it, but `traceback.py` from standard lib insists to write `str`.
Possible solution: Use `cStringIO.StringIO` as it was before version 3.0a3 but only on Python 2. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/DocumentTemplate/tests/test_DT_Try.py::DT_Try_Tests::test_DT_Try__Try____init__1",
"src/DocumentTemplate/tests/test_DT_Try.py::DT_Try_Tests::test_DT_Try__Try____init__2",
"src/DocumentTemplate/tests/test_DT_Try.py::DT_Try_Tests::test_DT_Try__Try____init__3",
"src/DocumentTemplate/tests/test_DT_Try.py::DT_Try_Tests::test_DT_Try__Try____init__4"
] | [
"src/DocumentTemplate/tests/test_DT_Try.py::DT_Try_Tests::test_DT_Try__Try__01",
"src/DocumentTemplate/tests/test_DT_Try.py::DT_Try_Tests::test_DT_Try__Try__02",
"src/DocumentTemplate/tests/test_DT_Try.py::DT_Try_Tests::test_DT_Try__Try__03",
"src/DocumentTemplate/tests/test_DT_Try.py::DT_Try_Tests::test_DT_Try__Try__04",
"src/DocumentTemplate/tests/test_DT_Try.py::DT_Try_Tests::test_DT_Try__Try__05",
"src/DocumentTemplate/tests/test_DT_Try.py::DT_Try_Tests::test_DT_Try__Try__06",
"src/DocumentTemplate/tests/test_DT_Try.py::DT_Try_Tests::test_DT_Try__Try__07",
"src/DocumentTemplate/tests/test_DT_Try.py::DT_Try_Tests::test_DT_Try__Try__08",
"src/DocumentTemplate/tests/test_DT_Try.py::DT_Try_Tests::test_DT_Try__Try__09",
"src/DocumentTemplate/tests/test_DT_Try.py::DT_Try_Tests::test_DT_Try__Try__10"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2018-10-02T16:59:26Z" | zpl-2.1 |
|
zopefoundation__DocumentTemplate-40 | diff --git a/CHANGES.rst b/CHANGES.rst
index 9bd0e39..5845a28 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -4,7 +4,9 @@ Changelog
3.0b6 (unreleased)
------------------
-- Nothing changed yet.
+- Fix regression in ``.DT_Util.InstanceDict`` which broke the acquisition
+ chain of the item it wraps.
+ (`#38 <https://github.com/zopefoundation/DocumentTemplate/issues/38>`_)
3.0b5 (2018-10-05)
diff --git a/src/DocumentTemplate/_DocumentTemplate.py b/src/DocumentTemplate/_DocumentTemplate.py
index 950cb61..e985a6e 100644
--- a/src/DocumentTemplate/_DocumentTemplate.py
+++ b/src/DocumentTemplate/_DocumentTemplate.py
@@ -108,7 +108,6 @@ import sys
import types
from Acquisition import aq_base
-from Acquisition import aq_inner
from ExtensionClass import Base
from DocumentTemplate.html_quote import html_quote
@@ -267,7 +266,7 @@ def safe_callable(ob):
return callable(ob)
-class InstanceDict(Base):
+class InstanceDict(object):
""""""
guarded_getattr = None
@@ -306,7 +305,7 @@ class InstanceDict(Base):
get = getattr
try:
- result = get(aq_inner(self.inst), key)
+ result = get(self.inst, key)
except AttributeError:
raise KeyError(key)
| zopefoundation/DocumentTemplate | 4ff3d6e91d933794306a915ef6088ed7d724989b | diff --git a/src/DocumentTemplate/tests/test_DocumentTemplate.py b/src/DocumentTemplate/tests/test_DocumentTemplate.py
index 585f522..a58fc5f 100644
--- a/src/DocumentTemplate/tests/test_DocumentTemplate.py
+++ b/src/DocumentTemplate/tests/test_DocumentTemplate.py
@@ -1,4 +1,18 @@
import unittest
+import Acquisition
+
+
+class Item(Acquisition.Implicit):
+ """Class modelling the here necessary parts of OFS.SimpleItem."""
+
+ def __init__(self, id):
+ self.id = id
+
+ def __repr__(self):
+ return '<Item id={0.id!r}>'.format(self)
+
+ def method1(self):
+ pass
class InstanceDictTests(unittest.TestCase):
@@ -12,22 +26,23 @@ class InstanceDictTests(unittest.TestCase):
# https://github.com/zopefoundation/Zope/issues/292
from DocumentTemplate.DT_Util import InstanceDict
- import Acquisition
-
- class Item(Acquisition.Implicit):
- """Class modelling the here necessary parts of OFS.SimpleItem."""
-
- def __init__(self, id):
- self.id = id
-
- def __repr__(self):
- return '<Item id={0.id!r}>'.format(self)
-
- def method1(self):
- pass
inst = Item('a').__of__(Item('b'))
i_dict = InstanceDict(inst, {}, getattr)
for element in Acquisition.aq_chain(i_dict['method1'].__self__):
self.assertNotIsInstance(element, InstanceDict)
+
+ def test_getitem_2(self):
+ # It does not break the acquisition chain of stored objects.
+
+ from DocumentTemplate.DT_Util import InstanceDict
+
+ main = Item('main')
+ main.sub = Item('sub')
+ side = Item('side')
+ side.here = Item('here')
+
+ path = side.here.__of__(main)
+ i_dict = InstanceDict(path, {}, getattr)
+ self.assertEqual(main.sub, i_dict['sub'])
| Changed behavior in acquisition
When trying to port a Zope installation from Zope2 to Zope4, I encountered an error where I am not sure if the behavior is intended and was broken in Zope2 or if it is a regression.
I could reproduce the problematic behavior with DTML Method, DTML Document as well as Z SQL Methods.
The minimal setup looks like this:
/
/main/
/main/test (DTML Method containing <dtml-var included>)
/side/
/side/included (p.e., Python Script returning 1)
Expected behavior, working with Zope2:
Either by calling `/side/main/test` or `/main/side/test`, the content or result of `included` is found in the acquisition context and included in `test`.
Found behavior in Zope4:
Only `/main/side/test` gives the expected result, `/side/main/test` gives the attached `KeyError`
[traceback.txt](https://github.com/zopefoundation/DocumentTemplate/files/2705889/traceback.txt)
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/DocumentTemplate/tests/test_DocumentTemplate.py::InstanceDictTests::test_getitem_2"
] | [
"src/DocumentTemplate/tests/test_DocumentTemplate.py::InstanceDictTests::test_getitem"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2019-02-28T10:29:36Z" | zpl-2.1 |
|
zopefoundation__DocumentTemplate-49 | diff --git a/CHANGES.rst b/CHANGES.rst
index f596197..78d0a26 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -4,7 +4,11 @@ Changelog
3.2 (unreleased)
----------------
+- no longer escape double quotes in ``sql_quote`` - that breaks PostgreSQL
+ (`#48 <https://github.com/zopefoundation/DocumentTemplate/issues/48>`_)
+
- Added `DeprecationWarnings` for all deprecated files and names
+ (`#42 <https://github.com/zopefoundation/DocumentTemplate/issues/42>`)
- Import sorting done like Zope itself
diff --git a/src/DocumentTemplate/DT_Var.py b/src/DocumentTemplate/DT_Var.py
index 13b84e3..878f76f 100644
--- a/src/DocumentTemplate/DT_Var.py
+++ b/src/DocumentTemplate/DT_Var.py
@@ -524,8 +524,6 @@ REMOVE_BYTES = (b'\x00', b'\x1a', b'\r')
REMOVE_TEXT = (u'\x00', u'\x1a', u'\r')
DOUBLE_BYTES = (b"'", b'\\')
DOUBLE_TEXT = (u"'", u'\\')
-ESCAPE_BYTES = (b'"',)
-ESCAPE_TEXT = (u'"',)
def bytes_sql_quote(v):
@@ -536,9 +534,6 @@ def bytes_sql_quote(v):
# Double untrusted characters to make them harmless.
for char in DOUBLE_BYTES:
v = v.replace(char, char * 2)
- # Backslash-escape untrusted characters to make them harmless.
- for char in ESCAPE_BYTES:
- v = v.replace(char, b'\\%s' % char)
return v
@@ -550,9 +545,6 @@ def text_sql_quote(v):
# Double untrusted characters to make them harmless.
for char in DOUBLE_TEXT:
v = v.replace(char, char * 2)
- # Backslash-escape untrusted characters to make them harmless.
- for char in ESCAPE_TEXT:
- v = v.replace(char, u'\\%s' % char)
return v
| zopefoundation/DocumentTemplate | 0982d86726ae3a39949f0565059e93ea697e8fd9 | diff --git a/src/DocumentTemplate/tests/test_DT_Var.py b/src/DocumentTemplate/tests/test_DT_Var.py
index afa753a..8067364 100644
--- a/src/DocumentTemplate/tests/test_DT_Var.py
+++ b/src/DocumentTemplate/tests/test_DT_Var.py
@@ -108,7 +108,7 @@ class TestUrlQuoting(unittest.TestCase):
self.assertEqual(bytes_sql_quote(br"Can\ I?"), b"Can\\\\ I?")
self.assertEqual(
- bytes_sql_quote(b'Just say "Hello"'), b'Just say \\"Hello\\"')
+ bytes_sql_quote(b'Just say "Hello"'), b'Just say "Hello"')
self.assertEqual(
bytes_sql_quote(b'Hello\x00World'), b'HelloWorld')
@@ -135,7 +135,7 @@ class TestUrlQuoting(unittest.TestCase):
# self.assertEqual(text_sql_quote(ur"Can\ I?"), u"Can\\\\ I?")
self.assertEqual(
- text_sql_quote(u'Just say "Hello"'), u'Just say \\"Hello\\"')
+ text_sql_quote(u'Just say "Hello"'), u'Just say "Hello"')
self.assertEqual(
text_sql_quote(u'Hello\x00World'), u'HelloWorld')
@@ -163,7 +163,7 @@ class TestUrlQuoting(unittest.TestCase):
# self.assertEqual(sql_quote(ur"Can\ I?"), u"Can\\\\ I?")
self.assertEqual(
- sql_quote(u'Just say "Hello"'), u'Just say \\"Hello\\"')
+ sql_quote(u'Just say "Hello"'), u'Just say "Hello"')
self.assertEqual(
sql_quote(u'Hello\x00World'), u'HelloWorld')
| Error in ZSQLMethod with json fields
In latest version of DocumentTemplate and ZSQLMethod symbol '"' is escaping in dtml-sqlvar statement. And it produce errors in ZSQLMethod with json string in <dtml-sqlvar ... type=string> as a value for field type json.
For example, create ZSQLMethod with one argument named "arg" and body:
select <dtml-sqlvar arg type=string>::json
Then click "Test", type {"a": "1", "b": "2"} in field "arg" and submit. Will be an error
invalid input syntax for type json СТРОКА 1: select '{\"a\": \"1\", \"b\": \"2\"}'::json
There was no such error in the previous version of DocumentTemplate and ZSQLMethod. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/DocumentTemplate/tests/test_DT_Var.py::TestUrlQuoting::test_bytes_sql_quote",
"src/DocumentTemplate/tests/test_DT_Var.py::TestUrlQuoting::test_sql_quote",
"src/DocumentTemplate/tests/test_DT_Var.py::TestUrlQuoting::test_text_sql_quote"
] | [
"src/DocumentTemplate/tests/test_DT_Var.py::TestNewlineToBr::test_newline_to_br",
"src/DocumentTemplate/tests/test_DT_Var.py::TestNewlineToBr::test_newline_to_br_tainted",
"src/DocumentTemplate/tests/test_DT_Var.py::TestUrlQuoting::test_url_quoting",
"src/DocumentTemplate/tests/test_DT_Var.py::TestUrlQuoting::test_url_quoting_plus"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2020-02-03T15:00:59Z" | zpl-2.1 |
|
zopefoundation__DocumentTemplate-55 | diff --git a/CHANGES.rst b/CHANGES.rst
index d7ab0d5..4646d49 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -4,6 +4,9 @@ Changelog
3.3 (unreleased)
----------------
+- Restore ``sql_quote`` behavior of always returning native strings
+ (`#54 <https://github.com/zopefoundation/DocumentTemplate/issues/54>`_)
+
3.2.3 (2020-05-28)
------------------
diff --git a/src/DocumentTemplate/DT_Var.py b/src/DocumentTemplate/DT_Var.py
index feaab92..32d535e 100644
--- a/src/DocumentTemplate/DT_Var.py
+++ b/src/DocumentTemplate/DT_Var.py
@@ -518,45 +518,26 @@ def structured_text(v, name='(Unknown name)', md={}):
return HTML()(doc, level, header=False)
-# Searching and replacing a byte in text, or text in bytes,
-# may give various errors on Python 2 or 3. So we make separate functions
-REMOVE_BYTES = (b'\x00', b'\x1a', b'\r')
-REMOVE_TEXT = (u'\x00', u'\x1a', u'\r')
-DOUBLE_BYTES = (b"'",)
-DOUBLE_TEXT = (u"'",)
-
-
-def bytes_sql_quote(v):
- # Helper function for sql_quote, handling only bytes.
- # Remove bad characters.
- for char in REMOVE_BYTES:
- v = v.replace(char, b'')
- # Double untrusted characters to make them harmless.
- for char in DOUBLE_BYTES:
- v = v.replace(char, char * 2)
- return v
-
-
-def text_sql_quote(v):
- # Helper function for sql_quote, handling only text.
- # Remove bad characters.
- for char in REMOVE_TEXT:
- v = v.replace(char, u'')
- # Double untrusted characters to make them harmless.
- for char in DOUBLE_TEXT:
- v = v.replace(char, char * 2)
- return v
-
-
def sql_quote(v, name='(Unknown name)', md={}):
"""Quote single quotes in a string by doubling them.
This is needed to securely insert values into sql
string literals in templates that generate sql.
"""
- if isinstance(v, bytes):
- return bytes_sql_quote(v)
- return text_sql_quote(v)
+ if six.PY3 and isinstance(v, bytes):
+ v = v.decode('UTF-8')
+ elif six.PY2 and not isinstance(v, bytes):
+ v = v.encode('UTF-8')
+
+ # Remove bad characters
+ for char in ('\x00', '\x1a', '\r'):
+ v = v.replace(char, '')
+
+ # Double untrusted characters to make them harmless.
+ for char in ("'",):
+ v = v.replace(char, char * 2)
+
+ return v
special_formats = {
| zopefoundation/DocumentTemplate | 03bac32bfffd599bb2d6344163365fa20ff8284f | diff --git a/src/DocumentTemplate/tests/testDTML.py b/src/DocumentTemplate/tests/testDTML.py
index eea5877..ce516c4 100644
--- a/src/DocumentTemplate/tests/testDTML.py
+++ b/src/DocumentTemplate/tests/testDTML.py
@@ -15,6 +15,8 @@
import unittest
+import six
+
from ..html_quote import html_quote
@@ -268,6 +270,26 @@ class DTMLTests(unittest.TestCase):
self.assertEqual(html1(), expected)
self.assertEqual(html2(), expected)
+ def test_sql_quote(self):
+ html = self.doc_class('<dtml-var x sql_quote>')
+ special = u'\xae'
+
+ self.assertEqual(html(x=u'x'), u'x')
+ self.assertEqual(html(x=b'x'), u'x')
+ self.assertEqual(html(x=u"Moe's Bar"), u"Moe''s Bar")
+ self.assertEqual(html(x=b"Moe's Bar"), u"Moe''s Bar")
+
+ if six.PY3:
+ self.assertEqual(html(x=u"Moe's B%sr" % special),
+ u"Moe''s B%sr" % special)
+ self.assertEqual(html(x=b"Moe's B%sr" % special.encode('UTF-8')),
+ u"Moe''s B%sr" % special)
+ else:
+ self.assertEqual(html(x=u"Moe's B%sr" % special),
+ "Moe''s B%sr" % special.encode('UTF-8'))
+ self.assertEqual(html(x=b"Moe's B%sr" % special.encode('UTF-8')),
+ b"Moe''s B%sr" % special.encode('UTF-8'))
+
def test_fmt(self):
html = self.doc_class(
"""
diff --git a/src/DocumentTemplate/tests/test_DT_Var.py b/src/DocumentTemplate/tests/test_DT_Var.py
index 45d7925..648af1b 100644
--- a/src/DocumentTemplate/tests/test_DT_Var.py
+++ b/src/DocumentTemplate/tests/test_DT_Var.py
@@ -15,6 +15,8 @@
import unittest
+import six
+
class TestNewlineToBr(unittest.TestCase):
@@ -95,63 +97,11 @@ class TestUrlQuoting(unittest.TestCase):
self.assertEqual(
url_unquote_plus(quoted_utf8_value), utf8_value)
- def test_bytes_sql_quote(self):
- from DocumentTemplate.DT_Var import bytes_sql_quote
- self.assertEqual(bytes_sql_quote(b""), b"")
- self.assertEqual(bytes_sql_quote(b"a"), b"a")
-
- self.assertEqual(bytes_sql_quote(b"Can't"), b"Can''t")
- self.assertEqual(bytes_sql_quote(b"Can\'t"), b"Can''t")
- self.assertEqual(bytes_sql_quote(br"Can\'t"), b"Can\\''t")
-
- self.assertEqual(bytes_sql_quote(b"Can\\ I?"), b"Can\\ I?")
- self.assertEqual(bytes_sql_quote(br"Can\ I?"), b"Can\\ I?")
-
- self.assertEqual(
- bytes_sql_quote(b'Just say "Hello"'), b'Just say "Hello"')
-
- self.assertEqual(
- bytes_sql_quote(b'Hello\x00World'), b'HelloWorld')
- self.assertEqual(
- bytes_sql_quote(b'\x00Hello\x00\x00World\x00'), b'HelloWorld')
-
- self.assertEqual(
- bytes_sql_quote(b"carriage\rreturn"), b"carriagereturn")
- self.assertEqual(bytes_sql_quote(b"line\nbreak"), b"line\nbreak")
- self.assertEqual(bytes_sql_quote(b"tab\t"), b"tab\t")
-
- def test_text_sql_quote(self):
- from DocumentTemplate.DT_Var import text_sql_quote
- self.assertEqual(text_sql_quote(u""), u"")
- self.assertEqual(text_sql_quote(u"a"), u"a")
-
- self.assertEqual(text_sql_quote(u"Can't"), u"Can''t")
- self.assertEqual(text_sql_quote(u"Can\'t"), u"Can''t")
- # SyntaxError on Python 3.
- # self.assertEqual(text_sql_quote(ur"Can\'t"), u"Can\\\\''t")
-
- self.assertEqual(text_sql_quote(u"Can\\ I?"), u"Can\\ I?")
- # SyntaxError on Python 3.
- # self.assertEqual(text_sql_quote(ur"Can\ I?"), u"Can\\\\ I?")
-
- self.assertEqual(
- text_sql_quote(u'Just say "Hello"'), u'Just say "Hello"')
-
- self.assertEqual(
- text_sql_quote(u'Hello\x00World'), u'HelloWorld')
- self.assertEqual(
- text_sql_quote(u'\x00Hello\x00\x00World\x00'), u'HelloWorld')
-
- self.assertEqual(
- text_sql_quote(u"carriage\rreturn"), u"carriagereturn")
- self.assertEqual(text_sql_quote(u"line\nbreak"), u"line\nbreak")
- self.assertEqual(text_sql_quote(u"tab\t"), u"tab\t")
-
def test_sql_quote(self):
from DocumentTemplate.DT_Var import sql_quote
self.assertEqual(sql_quote(u""), u"")
self.assertEqual(sql_quote(u"a"), u"a")
- self.assertEqual(sql_quote(b"a"), b"a")
+ self.assertEqual(sql_quote(b"a"), u"a")
self.assertEqual(sql_quote(u"Can't"), u"Can''t")
self.assertEqual(sql_quote(u"Can\'t"), u"Can''t")
@@ -174,11 +124,15 @@ class TestUrlQuoting(unittest.TestCase):
sql_quote(u'\x00Hello\x00\x00World\x00'), u'HelloWorld')
self.assertEqual(u"\xea".encode("utf-8"), b"\xc3\xaa")
- self.assertEqual(sql_quote(u"\xea'"), u"\xea''")
- self.assertEqual(sql_quote(b"\xc3\xaa'"), b"\xc3\xaa''")
+ if six.PY3:
+ self.assertEqual(sql_quote(b"\xc3\xaa'"), u"\xea''")
+ self.assertEqual(sql_quote(u"\xea'"), u"\xea''")
+ else:
+ self.assertEqual(sql_quote(b"\xc3\xaa'"), b"\xc3\xaa''")
+ self.assertEqual(sql_quote(u"\xea'"), b"\xc3\xaa''")
self.assertEqual(
- sql_quote(b"carriage\rreturn"), b"carriagereturn")
+ sql_quote(b"carriage\rreturn"), u"carriagereturn")
self.assertEqual(
sql_quote(u"carriage\rreturn"), u"carriagereturn")
self.assertEqual(sql_quote(u"line\nbreak"), u"line\nbreak")
| bytes_sql_quote() returns Bytes, although the content will be part of an SQL query String
In `DocumentTemplate/DT_Var.py`, the helper function `bytes_sql_quote()` is used to remove dangerous content from Bytes when used in SQL queries (edited after correction from @dataflake).
Because this escaped content is returned as Bytes, not String, it is impossible to correctly quote Bytes with `<dtml-sqlvar xy type="string">`, because the two cannot be concatenated.
This patch works for us:
*** zope4_orig/lib/python3.8/site-packages/DocumentTemplate/DT_Var.py 2020-06-24 08:48:39.767829123 +0200
--- zope4/lib/python3.8/site-packages/DocumentTemplate/DT_Var.py 2020-06-24 11:06:30.294957406 +0200
***************
*** 534,540 ****
# Double untrusted characters to make them harmless.
for char in DOUBLE_BYTES:
v = v.replace(char, char * 2)
! return v
def text_sql_quote(v):
--- 534,544 ----
# Double untrusted characters to make them harmless.
for char in DOUBLE_BYTES:
v = v.replace(char, char * 2)
! # We return a string because the quoted material will be
! # concatenated with other strings to form the query.
! # If the eighth bit is set, we interpret as UTF-8, just
! # because that encoding is to amazingly popular...
! return v.decode('utf-8')
def text_sql_quote(v): | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/DocumentTemplate/tests/testDTML.py::DTMLTests::test_sql_quote",
"src/DocumentTemplate/tests/testDTML.py::RESTTests::test_sql_quote",
"src/DocumentTemplate/tests/test_DT_Var.py::TestUrlQuoting::test_sql_quote"
] | [
"src/DocumentTemplate/tests/testDTML.py::DTMLTests::testBasicHTMLIn",
"src/DocumentTemplate/tests/testDTML.py::DTMLTests::testBasicHTMLIn2",
"src/DocumentTemplate/tests/testDTML.py::DTMLTests::testBasicHTMLIn3",
"src/DocumentTemplate/tests/testDTML.py::DTMLTests::testBasicStringIn",
"src/DocumentTemplate/tests/testDTML.py::DTMLTests::testBatchingEtc",
"src/DocumentTemplate/tests/testDTML.py::DTMLTests::testDTMLDateFormatting",
"src/DocumentTemplate/tests/testDTML.py::DTMLTests::testHTMLInElse",
"src/DocumentTemplate/tests/testDTML.py::DTMLTests::testNoItemPush",
"src/DocumentTemplate/tests/testDTML.py::DTMLTests::testNull",
"src/DocumentTemplate/tests/testDTML.py::DTMLTests::testPropogatedError",
"src/DocumentTemplate/tests/testDTML.py::DTMLTests::testRaise",
"src/DocumentTemplate/tests/testDTML.py::DTMLTests::testRenderCallable",
"src/DocumentTemplate/tests/testDTML.py::DTMLTests::testSequence1",
"src/DocumentTemplate/tests/testDTML.py::DTMLTests::testSequence2",
"src/DocumentTemplate/tests/testDTML.py::DTMLTests::testSequenceSummaries",
"src/DocumentTemplate/tests/testDTML.py::DTMLTests::testSimpleString",
"src/DocumentTemplate/tests/testDTML.py::DTMLTests::testSkipQuote",
"src/DocumentTemplate/tests/testDTML.py::DTMLTests::testStringDateFormatting",
"src/DocumentTemplate/tests/testDTML.py::DTMLTests::testSyntaxErrorHandling",
"src/DocumentTemplate/tests/testDTML.py::DTMLTests::testUrlUnquote",
"src/DocumentTemplate/tests/testDTML.py::DTMLTests::testWith",
"src/DocumentTemplate/tests/testDTML.py::DTMLTests::test_fmt",
"src/DocumentTemplate/tests/testDTML.py::RESTTests::testBasicHTMLIn",
"src/DocumentTemplate/tests/testDTML.py::RESTTests::testBasicHTMLIn2",
"src/DocumentTemplate/tests/testDTML.py::RESTTests::testBasicHTMLIn3",
"src/DocumentTemplate/tests/testDTML.py::RESTTests::testBasicStringIn",
"src/DocumentTemplate/tests/testDTML.py::RESTTests::testBatchingEtc",
"src/DocumentTemplate/tests/testDTML.py::RESTTests::testDTMLDateFormatting",
"src/DocumentTemplate/tests/testDTML.py::RESTTests::testHTMLInElse",
"src/DocumentTemplate/tests/testDTML.py::RESTTests::testNoItemPush",
"src/DocumentTemplate/tests/testDTML.py::RESTTests::testNull",
"src/DocumentTemplate/tests/testDTML.py::RESTTests::testPropogatedError",
"src/DocumentTemplate/tests/testDTML.py::RESTTests::testRaise",
"src/DocumentTemplate/tests/testDTML.py::RESTTests::testRenderCallable",
"src/DocumentTemplate/tests/testDTML.py::RESTTests::testSequence1",
"src/DocumentTemplate/tests/testDTML.py::RESTTests::testSequence2",
"src/DocumentTemplate/tests/testDTML.py::RESTTests::testSequenceSummaries",
"src/DocumentTemplate/tests/testDTML.py::RESTTests::testSimpleString",
"src/DocumentTemplate/tests/testDTML.py::RESTTests::testSkipQuote",
"src/DocumentTemplate/tests/testDTML.py::RESTTests::testStringDateFormatting",
"src/DocumentTemplate/tests/testDTML.py::RESTTests::testSyntaxErrorHandling",
"src/DocumentTemplate/tests/testDTML.py::RESTTests::testUrlUnquote",
"src/DocumentTemplate/tests/testDTML.py::RESTTests::testWith",
"src/DocumentTemplate/tests/testDTML.py::RESTTests::test_fmt",
"src/DocumentTemplate/tests/testDTML.py::test_suite",
"src/DocumentTemplate/tests/test_DT_Var.py::TestNewlineToBr::test_newline_to_br",
"src/DocumentTemplate/tests/test_DT_Var.py::TestNewlineToBr::test_newline_to_br_tainted",
"src/DocumentTemplate/tests/test_DT_Var.py::TestUrlQuoting::test_url_quoting",
"src/DocumentTemplate/tests/test_DT_Var.py::TestUrlQuoting::test_url_quoting_plus"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2020-06-30T10:42:22Z" | zpl-2.1 |
|
zopefoundation__RestrictedPython-135 | diff --git a/src/RestrictedPython/Utilities.py b/src/RestrictedPython/Utilities.py
index ad6a1eb..2abb2db 100644
--- a/src/RestrictedPython/Utilities.py
+++ b/src/RestrictedPython/Utilities.py
@@ -37,8 +37,8 @@ def same_type(arg1, *args):
t = getattr(arg1, '__class__', type(arg1))
for arg in args:
if getattr(arg, '__class__', type(arg)) is not t:
- return 0
- return 1
+ return False
+ return True
utility_builtins['same_type'] = same_type
| zopefoundation/RestrictedPython | ecf62c5116663990c78795ab8b0969874e1bdb3c | diff --git a/tests/builtins/test_utilities.py b/tests/builtins/test_utilities.py
index d6b0426..e35d1a6 100644
--- a/tests/builtins/test_utilities.py
+++ b/tests/builtins/test_utilities.py
@@ -76,7 +76,7 @@ def test_sametype_only_two_args_different():
class Foo(object):
pass
- assert same_type(object(), Foo()) is 0
+ assert same_type(object(), Foo()) is False
def test_sametype_only_multiple_args_same():
@@ -89,7 +89,7 @@ def test_sametype_only_multipe_args_one_different():
class Foo(object):
pass
- assert same_type(object(), object(), Foo()) is 0
+ assert same_type(object(), object(), Foo()) is False
def test_test_single_value_true():
| `same_type` should return True resp. False
There is no need to return `1` resp. `0` since Python 2.3 we have `True` and `False`. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/builtins/test_utilities.py::test_sametype_only_two_args_different",
"tests/builtins/test_utilities.py::test_sametype_only_multipe_args_one_different"
] | [
"tests/builtins/test_utilities.py::test_string_in_utility_builtins",
"tests/builtins/test_utilities.py::test_math_in_utility_builtins",
"tests/builtins/test_utilities.py::test_whrandom_in_utility_builtins",
"tests/builtins/test_utilities.py::test_random_in_utility_builtins",
"tests/builtins/test_utilities.py::test_set_in_utility_builtins",
"tests/builtins/test_utilities.py::test_frozenset_in_utility_builtins",
"tests/builtins/test_utilities.py::test_DateTime_in_utility_builtins_if_importable",
"tests/builtins/test_utilities.py::test_same_type_in_utility_builtins",
"tests/builtins/test_utilities.py::test_test_in_utility_builtins",
"tests/builtins/test_utilities.py::test_reorder_in_utility_builtins",
"tests/builtins/test_utilities.py::test_sametype_only_one_arg",
"tests/builtins/test_utilities.py::test_sametype_only_two_args_same",
"tests/builtins/test_utilities.py::test_sametype_only_multiple_args_same",
"tests/builtins/test_utilities.py::test_test_single_value_true",
"tests/builtins/test_utilities.py::test_test_single_value_False",
"tests/builtins/test_utilities.py::test_test_even_values_first_true",
"tests/builtins/test_utilities.py::test_test_even_values_not_first_true",
"tests/builtins/test_utilities.py::test_test_odd_values_first_true",
"tests/builtins/test_utilities.py::test_test_odd_values_not_first_true",
"tests/builtins/test_utilities.py::test_test_odd_values_last_true",
"tests/builtins/test_utilities.py::test_test_odd_values_last_false",
"tests/builtins/test_utilities.py::test_reorder_with__None",
"tests/builtins/test_utilities.py::test_reorder_with__not_None"
] | {
"failed_lite_validators": [
"has_short_problem_statement"
],
"has_test_patch": true,
"is_lite": false
} | "2018-10-02T17:59:09Z" | zpl-2.1 |
|
zopefoundation__RestrictedPython-198 | diff --git a/docs/CHANGES.rst b/docs/CHANGES.rst
index 49d2d9d..7bb5c5d 100644
--- a/docs/CHANGES.rst
+++ b/docs/CHANGES.rst
@@ -4,6 +4,9 @@ Changes
5.1a0 (unreleased)
------------------
+- Add support for the ``bytes`` and ``sorted`` builtins
+ (`#186 <https://github.com/zopefoundation/RestrictedPython/issues/186>`_)
+
- Drop install dependency on ``setuptools``.
(`#189 <https://github.com/zopefoundation/RestrictedPython/issues/189>`_)
diff --git a/src/RestrictedPython/Guards.py b/src/RestrictedPython/Guards.py
index 0f2c8fc..e7ed96e 100644
--- a/src/RestrictedPython/Guards.py
+++ b/src/RestrictedPython/Guards.py
@@ -33,6 +33,7 @@ _safe_names = [
'True',
'abs',
'bool',
+ 'bytes',
'callable',
'chr',
'complex',
@@ -52,6 +53,7 @@ _safe_names = [
'repr',
'round',
'slice',
+ 'sorted',
'str',
'tuple',
'zip'
@@ -174,7 +176,6 @@ for name in _safe_exceptions:
# one should care.
# buffer
-# bytes
# bytearray
# classmethod
# coerce
| zopefoundation/RestrictedPython | a31c5572de8a0e6c4f41ea5a977fc27459917c8e | diff --git a/tests/test_Guards.py b/tests/test_Guards.py
index fe6b2e0..40bd6f0 100644
--- a/tests/test_Guards.py
+++ b/tests/test_Guards.py
@@ -15,6 +15,16 @@ def _write_(x):
return x
+def test_Guards_bytes():
+ """It contains bytes"""
+ assert restricted_eval('bytes(1)') == bytes(1)
+
+
+def test_Guards_sorted():
+ """It contains sorted"""
+ assert restricted_eval('sorted([5, 2, 8, 1])') == sorted([5, 2, 8, 1])
+
+
def test_Guards__safe_builtins__1():
"""It contains `slice()`."""
assert restricted_eval('slice(1)') == slice(1)
| Adding "bytes" to allowed builtin names
Having `bytes` would allow a sane way of getting at `OFS.Image.File` data in restricted code under Python 3. `str` is inappropriate because it wants to decode the file content using the default UTF-8 encoding that may not match the actual encoding used by file contents.
Calling this a Zope 4 bugfix because having only `str` for those cases is a recipe for problems.
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_Guards.py::test_Guards_bytes",
"tests/test_Guards.py::test_Guards_sorted"
] | [
"tests/test_Guards.py::test_Guards__safe_builtins__1",
"tests/test_Guards.py::test_Guards__safe_builtins__2",
"tests/test_Guards.py::test_Guards__guarded_setattr__1",
"tests/test_Guards.py::test_Guards__write_wrapper__1",
"tests/test_Guards.py::test_Guards__write_wrapper__2",
"tests/test_Guards.py::test_Guards__guarded_unpack_sequence__1",
"tests/test_Guards.py::test_Guards__safer_getattr__1",
"tests/test_Guards.py::test_Guards__safer_getattr__2",
"tests/test_Guards.py::test_Guards__safer_getattr__3",
"tests/test_Guards.py::test_call_py3_builtins",
"tests/test_Guards.py::test_safer_getattr__underscore_name"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2020-07-10T10:28:05Z" | zpl-2.1 |
|
zopefoundation__RestrictedPython-272 | diff --git a/CHANGES.rst b/CHANGES.rst
index 24ed32f..6018a60 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -6,6 +6,7 @@ Changes
- Allow to use the package with Python 3.13 -- Caution: No security
audit has been done so far.
+- Add support for single mode statements / execution.
7.1 (2024-03-14)
diff --git a/docs/usage/basic_usage.rst b/docs/usage/basic_usage.rst
index 13218b3..085432e 100644
--- a/docs/usage/basic_usage.rst
+++ b/docs/usage/basic_usage.rst
@@ -94,6 +94,62 @@ One common advanced usage would be to define an own restricted builtin dictionar
There is a shortcut for ``{'__builtins__': safe_builtins}`` named ``safe_globals`` which can be imported from ``RestrictedPython``.
+Other Usages
+------------
+
+RestrictedPython has similar to normal Python multiple modes:
+
+* exec
+* eval
+* single
+* function
+
+you can use it by:
+
+.. testcode::
+
+ from RestrictedPython import compile_restricted
+
+ source_code = """
+ def do_something():
+ pass
+ """
+
+ byte_code = compile_restricted(
+ source_code,
+ filename='<inline code>',
+ mode='exec'
+ )
+ exec(byte_code)
+ do_something()
+
+.. testcode::
+
+ from RestrictedPython import compile_restricted
+
+ byte_code = compile_restricted(
+ "2 + 2",
+ filename='<inline code>',
+ mode='eval'
+ )
+ eval(byte_code)
+
+
+.. testcode:: single
+
+ from RestrictedPython import compile_restricted
+
+ byte_code = compile_restricted(
+ "2 + 2",
+ filename='<inline code>',
+ mode='single'
+ )
+ exec(byte_code)
+
+.. testoutput:: single
+
+ 4
+
Necessary setup
---------------
diff --git a/src/RestrictedPython/transformer.py b/src/RestrictedPython/transformer.py
index 66ae50f..9a205cc 100644
--- a/src/RestrictedPython/transformer.py
+++ b/src/RestrictedPython/transformer.py
@@ -593,6 +593,10 @@ class RestrictingNodeTransformer(ast.NodeTransformer):
"""
return self.node_contents_visit(node)
+ def visit_Interactive(self, node):
+ """Allow single mode without restrictions."""
+ return self.node_contents_visit(node)
+
def visit_List(self, node):
"""Allow list literals without restrictions."""
return self.node_contents_visit(node)
| zopefoundation/RestrictedPython | 67f3c1bcb4fad913505d2c34ce7a6835869ff77b | diff --git a/tests/test_compile.py b/tests/test_compile.py
index 3dacd73..603ad84 100644
--- a/tests/test_compile.py
+++ b/tests/test_compile.py
@@ -160,13 +160,24 @@ def test_compile__compile_restricted_eval__used_names():
assert result.used_names == {'a': True, 'b': True, 'x': True, 'func': True}
-def test_compile__compile_restricted_csingle():
+def test_compile__compile_restricted_single__1():
"""It compiles code as an Interactive."""
- result = compile_restricted_single('4 * 6')
- assert result.code is None
- assert result.errors == (
- 'Line None: Interactive statements are not allowed.',
- )
+ result = compile_restricted_single('x = 4 * 6')
+
+ assert result.errors == ()
+ assert result.warnings == []
+ assert result.code is not None
+ locals = {}
+ exec(result.code, {}, locals)
+ assert locals["x"] == 24
+
+
+def test_compile__compile_restricted__2():
+ """It compiles code as an Interactive."""
+ code = compile_restricted('x = 4 * 6', filename="<string>", mode="single")
+ locals = {}
+ exec(code, {}, locals)
+ assert locals["x"] == 24
PRINT_EXAMPLE = """
| Unable to compile single expressions
## PROBLEM REPORT
Attempted a simple `compile_restricted` using `single`.
```python
x = 50
code = compile_restricted('x + 25', '<string>', 'single')
```
### What I did:
Attempted a simple comparison with `compile()`. Also, compared it with `exec`.
```python
x = 50
code = compile('x + 25', '<string>', 'single')
exec(code)
assert x == 75
```
### What I expect to happen:
Should be able to compile a single expression and execute with the associated side-effects similar to `compile()`.
### What actually happened:
```
SyntaxError: ('Line None: Interactive statements are not allowed.',)
```
### What version of Python and Zope/Addons I am using:
Python 3.11.8
RestrictedPython 7.0 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_compile.py::test_compile__compile_restricted_single__1",
"tests/test_compile.py::test_compile__compile_restricted__2"
] | [
"tests/test_compile.py::test_compile__compile_restricted_invalid_code_input",
"tests/test_compile.py::test_compile__compile_restricted_invalid_policy_input",
"tests/test_compile.py::test_compile__compile_restricted_invalid_mode_input",
"tests/test_compile.py::test_compile__invalid_syntax",
"tests/test_compile.py::test_compile__compile_restricted_exec__1",
"tests/test_compile.py::test_compile__compile_restricted_exec__2",
"tests/test_compile.py::test_compile__compile_restricted_exec__3",
"tests/test_compile.py::test_compile__compile_restricted_exec__4",
"tests/test_compile.py::test_compile__compile_restricted_exec__5",
"tests/test_compile.py::test_compile__compile_restricted_exec__10",
"tests/test_compile.py::test_compile__compile_restricted_eval__1",
"tests/test_compile.py::test_compile__compile_restricted_eval__2",
"tests/test_compile.py::test_compile__compile_restricted_eval__used_names",
"tests/test_compile.py::test_compile_restricted",
"tests/test_compile.py::test_compile_restricted_eval",
"tests/test_compile.py::test_compile___compile_restricted_mode__1"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2024-02-29T15:52:59Z" | zpl-2.1 |
|
zopefoundation__RestrictedPython-97 | diff --git a/docs/CHANGES.rst b/docs/CHANGES.rst
index 91bc291..9af2e61 100644
--- a/docs/CHANGES.rst
+++ b/docs/CHANGES.rst
@@ -7,6 +7,9 @@ Changes
- Warn when using another Python implementation than CPython as it is not safe to use RestrictedPython with other versions than CPyton.
See https://bitbucket.org/pypy/pypy/issues/2653 for PyPy.
+- Allow to use list comprehensions in the default implementation of
+ ``RestrictionCapableEval.eval()``.
+
4.0b2 (2017-09-15)
------------------
@@ -62,7 +65,7 @@ Changes
- Mostly complete rewrite based on Python AST module.
[loechel (Alexander Loechel), icemac (Michael Howitz), stephan-hof (Stephan Hofmockel), tlotze (Thomas Lotze)]
-
+
- Support Python versions 3.4 up to 3.6.
- switch to pytest
diff --git a/src/RestrictedPython/Eval.py b/src/RestrictedPython/Eval.py
index 836ea5e..221cd2d 100644
--- a/src/RestrictedPython/Eval.py
+++ b/src/RestrictedPython/Eval.py
@@ -35,6 +35,11 @@ def default_guarded_getitem(ob, index):
return ob[index]
+def default_guarded_getiter(ob):
+ # No restrictions.
+ return ob
+
+
class RestrictionCapableEval(object):
"""A base class for restricted code."""
@@ -99,7 +104,8 @@ class RestrictionCapableEval(object):
global_scope = {
'_getattr_': default_guarded_getattr,
- '_getitem_': default_guarded_getitem
+ '_getitem_': default_guarded_getitem,
+ '_getiter_': default_guarded_getiter,
}
global_scope.update(self.globals)
| zopefoundation/RestrictedPython | a63f5c3b600b00cb5bbe779b31e75e94413f8390 | diff --git a/tests/test_eval.py b/tests/test_eval.py
index 0499a04..d1acf10 100644
--- a/tests/test_eval.py
+++ b/tests/test_eval.py
@@ -95,3 +95,10 @@ def test_Eval__RestictionCapableEval__eval_1():
ob.globals['c'] = 8
result = ob.eval(dict(a=1, b=2, c=4))
assert result == 11
+
+
+def test_Eval__RestictionCapableEval__eval__2():
+ """It allows to use list comprehensions."""
+ ob = RestrictionCapableEval("[item for item in (1, 2)]")
+ result = ob.eval({})
+ assert result == [1, 2]
| list comprehension expression raises "TypeError: 'NoneType' object is not subscriptable"
Tested with Python 3.6.1 with RestrictedPython 4.0b2:
```
(Pdb) RestrictionCapableEval('[item for item in [1,2]]').eval(context)
*** TypeError: 'NoneType' object is not subscriptable
(Pdb) [item for item in [1,2]]
[1, 2]
```
where context is:
```
(Pdb) context
{'variables': {'test_run_identifier': 'QA-240dc1b5-f6bd-11e7-888e-080027edbcd8-skin1', 'skin': 'skin1', 'datetime': '2018-01-11T11:49:48.439194', 'base_url': 'http://'}, 'len': <built-in function len>, 'list': <class 'list'>, 'match': <function match at 0x7f2b3c55bd90>}
```
Any suggestion?
Thanks in advance | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/test_eval.py::test_Eval__RestictionCapableEval__eval__2"
] | [
"tests/test_eval.py::test_init",
"tests/test_eval.py::test_init_with_syntax_error",
"tests/test_eval.py::test_Eval__RestrictionCapableEval_1",
"tests/test_eval.py::test_Eval__RestrictionCapableEval__2",
"tests/test_eval.py::test_Eval__RestictionCapableEval__prepUnrestrictedCode_1",
"tests/test_eval.py::test_Eval__RestictionCapableEval__prepUnrestrictedCode_2",
"tests/test_eval.py::test_Eval__RestictionCapableEval__prepRestrictedCode_1",
"tests/test_eval.py::test_Eval__RestictionCapableEval__eval_1"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2018-01-25T11:29:02Z" | zpl-2.1 |
|
zopefoundation__ZConfig-51 | diff --git a/CHANGES.rst b/CHANGES.rst
index 0802c08..4fb65de 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -2,10 +2,13 @@
Change History for ZConfig
==========================
-3.3.1 (unreleased)
+3.4.0 (unreleased)
------------------
-- Nothing changed yet.
+- The ``logfile`` section type defined by the ``ZConfig.components.logger``
+ package supports the optional ``delay`` and ``encoding`` parameters.
+ These can only be used for regular files, not the special ``STDOUT``
+ and ``STDERR`` streams.
3.3.0 (2018-10-04)
diff --git a/ZConfig/components/logger/handlers.py b/ZConfig/components/logger/handlers.py
index 4b9c2e8..f436749 100644
--- a/ZConfig/components/logger/handlers.py
+++ b/ZConfig/components/logger/handlers.py
@@ -110,13 +110,22 @@ class FileHandlerFactory(HandlerFactory):
old_files = self.section.old_files
when = self.section.when
interval = self.section.interval
- if path == "STDERR":
+ encoding = self.section.encoding
+ delay = self.section.delay
+
+ def check_std_stream():
if max_bytes or old_files:
- raise ValueError("cannot rotate STDERR")
+ raise ValueError("cannot rotate " + path)
+ if delay:
+ raise ValueError("cannot delay opening " + path)
+ if encoding:
+ raise ValueError("cannot specify encoding for " + path)
+
+ if path == "STDERR":
+ check_std_stream()
handler = loghandler.StreamHandler(sys.stderr)
elif path == "STDOUT":
- if max_bytes or old_files:
- raise ValueError("cannot rotate STDOUT")
+ check_std_stream()
handler = loghandler.StreamHandler(sys.stdout)
elif when or max_bytes or old_files or interval:
if not old_files:
@@ -128,15 +137,17 @@ class FileHandlerFactory(HandlerFactory):
interval = 1
handler = loghandler.TimedRotatingFileHandler(
path, when=when, interval=interval,
- backupCount=old_files)
+ backupCount=old_files, encoding=encoding, delay=delay)
elif max_bytes:
handler = loghandler.RotatingFileHandler(
- path, maxBytes=max_bytes, backupCount=old_files)
+ path, maxBytes=max_bytes, backupCount=old_files,
+ encoding=encoding, delay=delay)
else:
raise ValueError(
"max-bytes or when must be set for log rotation")
else:
- handler = loghandler.FileHandler(path)
+ handler = loghandler.FileHandler(
+ path, encoding=encoding, delay=delay)
return handler
diff --git a/ZConfig/components/logger/handlers.xml b/ZConfig/components/logger/handlers.xml
index 39491e1..d0d1425 100644
--- a/ZConfig/components/logger/handlers.xml
+++ b/ZConfig/components/logger/handlers.xml
@@ -44,6 +44,26 @@
<key name="format"
default="------\n%(asctime)s %(levelname)s %(name)s %(message)s"
datatype=".log_format"/>
+ <key name="encoding" required="no" datatype="string">
+ <description>
+ Encoding for the underlying file.
+
+ If not specified, Python's default encoding handling is used.
+
+ This cannot be specified for STDOUT or STDERR destinations, and
+ must be omitted in such cases.
+ </description>
+ </key>
+ <key name="delay" required="no" default="false" datatype="boolean">
+ <description>
+ If true, opening of the log file will be delayed until a message
+ is emitted. This avoids creating logfiles that may only be
+ written to rarely or under special conditions.
+
+ This cannot be specified for STDOUT or STDERR destinations, and
+ must be omitted in such cases.
+ </description>
+ </key>
</sectiontype>
<sectiontype name="syslog"
diff --git a/ZConfig/components/logger/loghandler.py b/ZConfig/components/logger/loghandler.py
index 2652b28..ddd042b 100644
--- a/ZConfig/components/logger/loghandler.py
+++ b/ZConfig/components/logger/loghandler.py
@@ -61,29 +61,26 @@ def _remove_from_reopenable(wr):
pass
-class FileHandler(logging.StreamHandler):
+class FileHandler(logging.FileHandler):
"""File handler which supports reopening of logs.
Re-opening should be used instead of the 'rollover' feature of
the FileHandler from the standard library's logging package.
"""
- def __init__(self, filename, mode="a"):
- filename = os.path.abspath(filename)
- logging.StreamHandler.__init__(self, open(filename, mode))
- self.baseFilename = filename
- self.mode = mode
+ def __init__(self, filename, mode="a", encoding=None, delay=False):
+ logging.FileHandler.__init__(self, filename,
+ mode=mode, encoding=encoding, delay=delay)
self._wr = weakref.ref(self, _remove_from_reopenable)
_reopenable_handlers.append(self._wr)
def close(self):
- self.stream.close()
# This can raise a KeyError if the handler has already been
# removed, but a later error can be raised if
# StreamHandler.close() isn't called. This seems the best
# compromise. :-(
try:
- logging.StreamHandler.close(self)
+ logging.FileHandler.close(self)
except KeyError: # pragma: no cover
pass
_remove_from_reopenable(self._wr)
@@ -91,8 +88,12 @@ class FileHandler(logging.StreamHandler):
def reopen(self):
self.acquire()
try:
- self.stream.close()
- self.stream = open(self.baseFilename, self.mode)
+ if self.stream is not None:
+ self.stream.close()
+ if self.delay:
+ self.stream = None
+ else:
+ self.stream = self._open()
finally:
self.release()
@@ -113,7 +114,10 @@ class Win32FileHandler(FileHandler):
except OSError:
pass
- self.stream = open(self.baseFilename, self.mode)
+ if self.delay:
+ self.stream = None
+ else:
+ self.stream = self._open()
if os.name == "nt":
@@ -152,15 +156,9 @@ class TimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
self.doRollover()
-class NullHandler(logging.Handler):
+class NullHandler(logging.NullHandler):
"""Handler that does nothing."""
- def emit(self, record):
- pass
-
- def handle(self, record):
- pass
-
class StartupHandler(logging.handlers.BufferingHandler):
"""Handler which stores messages in a buffer until later.
diff --git a/ZConfig/info.py b/ZConfig/info.py
index 525d12b..33f8dfb 100644
--- a/ZConfig/info.py
+++ b/ZConfig/info.py
@@ -35,7 +35,7 @@ class UnboundedThing(object):
def __eq__(self, other):
return isinstance(other, self.__class__)
- def __repr__(self): # pragma: no cover
+ def __repr__(self):
return "<Unbounded>"
diff --git a/setup.py b/setup.py
index a837214..35d87ca 100644
--- a/setup.py
+++ b/setup.py
@@ -18,7 +18,7 @@ tests_require = [
options = dict(
name="ZConfig",
- version='3.3.1.dev0',
+ version='3.4.0.dev0',
author="Fred L. Drake, Jr.",
author_email="[email protected]",
maintainer="Zope Foundation and Contributors",
diff --git a/tox.ini b/tox.ini
index fdec36b..7a9860b 100644
--- a/tox.ini
+++ b/tox.ini
@@ -23,3 +23,14 @@ commands =
coverage combine
coverage html
coverage report -m --fail-under 99
+
+[testenv:docs]
+# basepython not specified; we want to be sure it's something available
+# on the current system.
+deps =
+ sphinx
+ sphinxcontrib-programoutput
+commands =
+ make -C doc html
+whitelist_externals =
+ make
| zopefoundation/ZConfig | ce8ad23032399376a972df8a69591bc717258ff5 | diff --git a/ZConfig/components/logger/tests/test_logger.py b/ZConfig/components/logger/tests/test_logger.py
index ced3b66..30b5441 100644
--- a/ZConfig/components/logger/tests/test_logger.py
+++ b/ZConfig/components/logger/tests/test_logger.py
@@ -170,6 +170,45 @@ class TestConfig(LoggingTestHelper, unittest.TestCase):
logfile = logger.handlers[0]
self.assertEqual(logfile.level, logging.DEBUG)
self.assertTrue(isinstance(logfile, loghandler.FileHandler))
+ self.assertFalse(logfile.delay)
+ self.assertIsNotNone(logfile.stream)
+ logger.removeHandler(logfile)
+ logfile.close()
+
+ def test_with_encoded(self):
+ fn = self.mktemp()
+ logger = self.check_simple_logger("<eventlog>\n"
+ " <logfile>\n"
+ " path %s\n"
+ " level debug\n"
+ " encoding shift-jis\n"
+ " </logfile>\n"
+ "</eventlog>" % fn)
+ logfile = logger.handlers[0]
+ self.assertEqual(logfile.level, logging.DEBUG)
+ self.assertTrue(isinstance(logfile, loghandler.FileHandler))
+ self.assertFalse(logfile.delay)
+ self.assertIsNotNone(logfile.stream)
+ self.assertEqual(logfile.stream.encoding, "shift-jis")
+ logger.removeHandler(logfile)
+ logfile.close()
+
+ def test_with_logfile_delayed(self):
+ fn = self.mktemp()
+ logger = self.check_simple_logger("<eventlog>\n"
+ " <logfile>\n"
+ " path %s\n"
+ " level debug\n"
+ " delay true\n"
+ " </logfile>\n"
+ "</eventlog>" % fn)
+ logfile = logger.handlers[0]
+ self.assertEqual(logfile.level, logging.DEBUG)
+ self.assertTrue(isinstance(logfile, loghandler.FileHandler))
+ self.assertTrue(logfile.delay)
+ self.assertIsNone(logfile.stream)
+ logger.info("this is a test")
+ self.assertIsNotNone(logfile.stream)
logger.removeHandler(logfile)
logfile.close()
@@ -179,6 +218,18 @@ class TestConfig(LoggingTestHelper, unittest.TestCase):
def test_with_stdout(self):
self.check_standard_stream("stdout")
+ def test_delayed_stderr(self):
+ self.check_standard_stream_cannot_delay("stderr")
+
+ def test_delayed_stdout(self):
+ self.check_standard_stream_cannot_delay("stdout")
+
+ def test_encoded_stderr(self):
+ self.check_standard_stream_cannot_encode("stderr")
+
+ def test_encoded_stdout(self):
+ self.check_standard_stream_cannot_encode("stdout")
+
def test_with_rotating_logfile(self):
fn = self.mktemp()
logger = self.check_simple_logger("<eventlog>\n"
@@ -296,6 +347,50 @@ class TestConfig(LoggingTestHelper, unittest.TestCase):
logger.warning("woohoo!")
self.assertTrue(sio.getvalue().find("woohoo!") >= 0)
+ def check_standard_stream_cannot_delay(self, name):
+ old_stream = getattr(sys, name)
+ conf = self.get_config("""
+ <eventlog>
+ <logfile>
+ level info
+ path %s
+ delay true
+ </logfile>
+ </eventlog>
+ """ % name.upper())
+ self.assertTrue(conf.eventlog is not None)
+ sio = StringIO()
+ setattr(sys, name, sio)
+ try:
+ with self.assertRaises(ValueError) as cm:
+ conf.eventlog()
+ self.assertIn("cannot delay opening %s" % name.upper(),
+ str(cm.exception))
+ finally:
+ setattr(sys, name, old_stream)
+
+ def check_standard_stream_cannot_encode(self, name):
+ old_stream = getattr(sys, name)
+ conf = self.get_config("""
+ <eventlog>
+ <logfile>
+ level info
+ path %s
+ encoding utf-8
+ </logfile>
+ </eventlog>
+ """ % name.upper())
+ self.assertTrue(conf.eventlog is not None)
+ sio = StringIO()
+ setattr(sys, name, sio)
+ try:
+ with self.assertRaises(ValueError) as cm:
+ conf.eventlog()
+ self.assertIn("cannot specify encoding for %s" % name.upper(),
+ str(cm.exception))
+ finally:
+ setattr(sys, name, old_stream)
+
def test_custom_formatter(self):
old_stream = sys.stdout
conf = self.get_config("""
@@ -680,9 +775,43 @@ class TestReopeningLogfiles(TestReopeningRotatingLogfiles):
h.release = lambda: calls.append("release")
h.reopen()
+ self.assertEqual(calls, ["acquire", "release"])
+ del calls[:]
+
+ # FileHandler.close() does acquire/release, and invokes
+ # StreamHandler.flush(), which does the same. Since the lock is
+ # recursive, that's ok.
+ #
h.close()
+ self.assertEqual(calls, ["acquire", "acquire", "release", "release"])
- self.assertEqual(calls, ["acquire", "release"])
+ def test_with_logfile_delayed_reopened(self):
+ fn = self.mktemp()
+ conf = self.get_config("<logger>\n"
+ " <logfile>\n"
+ " path %s\n"
+ " level debug\n"
+ " delay true\n"
+ " encoding shift-jis\n"
+ " </logfile>\n"
+ "</logger>" % fn)
+ logger = conf.loggers[0]()
+ logfile = logger.handlers[0]
+ self.assertTrue(logfile.delay)
+ self.assertIsNone(logfile.stream)
+ logger.info("this is a test")
+ self.assertIsNotNone(logfile.stream)
+ self.assertEqual(logfile.stream.encoding, "shift-jis")
+
+ # After reopening, we expect the stream to be reset, to be
+ # opened at the next event to be logged:
+ logfile.reopen()
+ self.assertIsNone(logfile.stream)
+ logger.info("this is another test")
+ self.assertIsNotNone(logfile.stream)
+ self.assertEqual(logfile.stream.encoding, "shift-jis")
+ logger.removeHandler(logfile)
+ logfile.close()
class TestFunctions(TestHelper, unittest.TestCase):
diff --git a/ZConfig/tests/test_info.py b/ZConfig/tests/test_info.py
index dda2d77..145379e 100644
--- a/ZConfig/tests/test_info.py
+++ b/ZConfig/tests/test_info.py
@@ -36,6 +36,9 @@ class UnboundTestCase(unittest.TestCase):
self.assertFalse(Unbounded > Unbounded)
self.assertEqual(Unbounded, Unbounded)
+ def test_repr(self):
+ self.assertEqual(repr(Unbounded), '<Unbounded>')
+
class InfoMixin(TestHelper):
| Support delay parameter for file-based handlers
The *delay* parameter was added for all the file-based handlers from the ``logging`` package in Python 2.6, but ``ZConfig`` was not updated to support that.
We don't need to worry about pre-*delay* versions at this point, and it would be useful to have support for this. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"ZConfig/components/logger/tests/test_logger.py::TestConfig::test_delayed_stderr",
"ZConfig/components/logger/tests/test_logger.py::TestConfig::test_delayed_stdout",
"ZConfig/components/logger/tests/test_logger.py::TestConfig::test_encoded_stderr",
"ZConfig/components/logger/tests/test_logger.py::TestConfig::test_encoded_stdout",
"ZConfig/components/logger/tests/test_logger.py::TestConfig::test_with_encoded",
"ZConfig/components/logger/tests/test_logger.py::TestConfig::test_with_logfile",
"ZConfig/components/logger/tests/test_logger.py::TestConfig::test_with_logfile_delayed",
"ZConfig/components/logger/tests/test_logger.py::TestConfig::test_with_rotating_logfile",
"ZConfig/components/logger/tests/test_logger.py::TestConfig::test_with_rotating_logfile_and_STD_should_fail",
"ZConfig/components/logger/tests/test_logger.py::TestConfig::test_with_stderr",
"ZConfig/components/logger/tests/test_logger.py::TestReopeningLogfiles::test_filehandler_reopen_thread_safety",
"ZConfig/components/logger/tests/test_logger.py::TestReopeningLogfiles::test_with_logfile_delayed_reopened"
] | [
"ZConfig/components/logger/tests/test_logger.py::TestConfig::test_config_without_handlers",
"ZConfig/components/logger/tests/test_logger.py::TestConfig::test_config_without_logger",
"ZConfig/components/logger/tests/test_logger.py::TestConfig::test_custom_formatter",
"ZConfig/components/logger/tests/test_logger.py::TestConfig::test_factory_without_stream",
"ZConfig/components/logger/tests/test_logger.py::TestConfig::test_with_email_notifier",
"ZConfig/components/logger/tests/test_logger.py::TestConfig::test_with_email_notifier_with_credentials",
"ZConfig/components/logger/tests/test_logger.py::TestConfig::test_with_email_notifier_with_invalid_credentials",
"ZConfig/components/logger/tests/test_logger.py::TestConfig::test_with_http_logger_localhost",
"ZConfig/components/logger/tests/test_logger.py::TestConfig::test_with_http_logger_remote_host",
"ZConfig/components/logger/tests/test_logger.py::TestConfig::test_with_stdout",
"ZConfig/components/logger/tests/test_logger.py::TestConfig::test_with_syslog",
"ZConfig/components/logger/tests/test_logger.py::TestConfig::test_with_timed_rotating_logfile",
"ZConfig/components/logger/tests/test_logger.py::TestConfig::test_with_timed_rotating_logfile_and_size_should_fail",
"ZConfig/components/logger/tests/test_logger.py::TestReopeningRotatingLogfiles::test_filehandler_reopen",
"ZConfig/components/logger/tests/test_logger.py::TestReopeningRotatingLogfiles::test_logfile_reopening",
"ZConfig/components/logger/tests/test_logger.py::TestReopeningLogfiles::test_filehandler_reopen",
"ZConfig/components/logger/tests/test_logger.py::TestReopeningLogfiles::test_logfile_reopening",
"ZConfig/components/logger/tests/test_logger.py::TestFunctions::test_close_files",
"ZConfig/components/logger/tests/test_logger.py::TestFunctions::test_http_handler_url",
"ZConfig/components/logger/tests/test_logger.py::TestFunctions::test_http_method",
"ZConfig/components/logger/tests/test_logger.py::TestFunctions::test_log_format_bad",
"ZConfig/components/logger/tests/test_logger.py::TestFunctions::test_logging_level",
"ZConfig/components/logger/tests/test_logger.py::TestFunctions::test_reopen_files_missing_wref",
"ZConfig/components/logger/tests/test_logger.py::TestFunctions::test_resolve_deep",
"ZConfig/components/logger/tests/test_logger.py::TestFunctions::test_syslog_facility",
"ZConfig/components/logger/tests/test_logger.py::TestStartupHandler::test_buffer",
"ZConfig/components/logger/tests/test_logger.py::test_logger_convenience_function_and_ommiting_name_to_get_root_logger",
"ZConfig/components/logger/tests/test_logger.py::test_suite",
"ZConfig/tests/test_info.py::UnboundTestCase::test_order",
"ZConfig/tests/test_info.py::UnboundTestCase::test_repr",
"ZConfig/tests/test_info.py::BaseInfoTestCase::test_constructor_error",
"ZConfig/tests/test_info.py::BaseInfoTestCase::test_repr",
"ZConfig/tests/test_info.py::BaseKeyInfoTestCase::test_adddefaultc",
"ZConfig/tests/test_info.py::BaseKeyInfoTestCase::test_cant_instantiate",
"ZConfig/tests/test_info.py::BaseKeyInfoTestCase::test_finish",
"ZConfig/tests/test_info.py::KeyInfoTestCase::test_add_with_default",
"ZConfig/tests/test_info.py::SectionInfoTestCase::test_constructor_error",
"ZConfig/tests/test_info.py::SectionInfoTestCase::test_misc",
"ZConfig/tests/test_info.py::AbstractTypeTestCase::test_subtypes",
"ZConfig/tests/test_info.py::SectionTypeTestCase::test_getinfo_no_key",
"ZConfig/tests/test_info.py::SectionTypeTestCase::test_getsectioninfo",
"ZConfig/tests/test_info.py::SectionTypeTestCase::test_required_types_with_name",
"ZConfig/tests/test_info.py::SchemaTypeTestCase::test_various"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2018-12-04T01:47:49Z" | zpl-2.1 |
|
zopefoundation__ZConfig-70 | diff --git a/.travis.yml b/.travis.yml
index 9dd3331..f46558a 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -7,6 +7,7 @@ python:
- 3.5
- 3.6
- 3.7
+ - 3.8-dev
- pypy
- pypy3
diff --git a/CHANGES.rst b/CHANGES.rst
index 030e368..731807f 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -5,7 +5,10 @@
3.5.1 (unreleased)
==================
-- Nothing changed yet.
+- Added support for Python 3.8. This primarily involves avoiding the
+ new-in-3.8 validation of the format string when using the
+ 'safe-template' format style, since that's not supported in the Python
+ standard library.
3.5.0 (2019-06-24)
diff --git a/ZConfig/components/logger/formatter.py b/ZConfig/components/logger/formatter.py
index 512f5da..009630d 100644
--- a/ZConfig/components/logger/formatter.py
+++ b/ZConfig/components/logger/formatter.py
@@ -248,8 +248,17 @@ class FormatterFactory(object):
else:
# A formatter class that supports style, but our style is
# non-standard, so we reach under the covers a bit.
+ #
+ # Python 3.8 adds a validate option, defaulting to True,
+ # which causes the format string to be checked. Since
+ # safe-template is not a standard style, we want to
+ # suppress this.
+ #
+ kwargs = dict()
+ if sys.version_info >= (3, 8):
+ kwargs['validate'] = False
formatter = self.factory(self.format, self.dateformat,
- style='$')
+ style='$', **kwargs)
assert formatter._style._fmt == self.format
formatter._style = stylist
else:
diff --git a/setup.py b/setup.py
index f16aabe..2bb70ed 100644
--- a/setup.py
+++ b/setup.py
@@ -64,6 +64,7 @@ options = dict(
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
+ 'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Operating System :: OS Independent',
diff --git a/tox.ini b/tox.ini
index 7a9860b..4c7f8cd 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,5 +1,5 @@
[tox]
-envlist = py27,py34,py35,py36,py37,pypy,coverage-report
+envlist = py27,py34,py35,py36,py37,py38,pypy,coverage-report
skip_missing_interpreters = true
[testenv]
| zopefoundation/ZConfig | 4be3fd06147637e0efd190da0df54ccf229c2aca | diff --git a/ZConfig/components/logger/tests/test_formatter.py b/ZConfig/components/logger/tests/test_formatter.py
index 81c7235..3a04a5f 100644
--- a/ZConfig/components/logger/tests/test_formatter.py
+++ b/ZConfig/components/logger/tests/test_formatter.py
@@ -25,6 +25,17 @@ import ZConfig.components.logger.formatter
import ZConfig.components.logger.tests.support
+# In Python 3.8, a KeyError raised by string interpolation is re-written
+# into a ValueError reporting a reference to an undefined field. We're
+# not masking the exception, but we want to check for the right one in
+# the tests below (without catching anything else).
+#
+if sys.version_info >= (3, 8):
+ MissingFieldError = ValueError
+else:
+ MissingFieldError = KeyError
+
+
class LogFormatStyleTestCase(unittest.TestCase):
def setUp(self):
@@ -314,7 +325,10 @@ class CustomFormatterFactoryWithoutStyleParamTestCase(
class StylelessFormatter(logging.Formatter):
def __init__(self, fmt=None, datefmt=None):
- logging.Formatter.__init__(self, fmt=fmt, datefmt=datefmt)
+ kwargs = dict()
+ if sys.version_info >= (3, 8):
+ kwargs['validate'] = False
+ logging.Formatter.__init__(self, fmt=fmt, datefmt=datefmt, **kwargs)
def styleless_formatter(fmt=None, datefmt=None):
@@ -552,9 +566,9 @@ class ArbitraryFieldsTestCase(StyledFormatterTestHelper, unittest.TestCase):
arbitrary_fields=True)
# The formatter still breaks when it references an undefined field:
- with self.assertRaises(KeyError) as cm:
+ with self.assertRaises(MissingFieldError) as cm:
formatter.format(self.record)
- self.assertEqual(str(cm.exception), "'undefined_field'")
+ self.assertIn("'undefined_field'", str(cm.exception))
def test_classic_arbitrary_field_present(self):
formatter = self.get_formatter(
@@ -574,9 +588,9 @@ class ArbitraryFieldsTestCase(StyledFormatterTestHelper, unittest.TestCase):
arbitrary_fields=True)
# The formatter still breaks when it references an undefined field:
- with self.assertRaises(KeyError) as cm:
+ with self.assertRaises(MissingFieldError) as cm:
formatter.format(self.record)
- self.assertEqual(str(cm.exception), "'undefined_field'")
+ self.assertIn("'undefined_field'", str(cm.exception))
def test_format_arbitrary_field_present(self):
formatter = self.get_formatter(
@@ -596,9 +610,9 @@ class ArbitraryFieldsTestCase(StyledFormatterTestHelper, unittest.TestCase):
arbitrary_fields=True)
# The formatter still breaks when it references an undefined field:
- with self.assertRaises(KeyError) as cm:
+ with self.assertRaises(MissingFieldError) as cm:
formatter.format(self.record)
- self.assertEqual(str(cm.exception), "'undefined_field'")
+ self.assertIn("'undefined_field'", str(cm.exception))
def test_template_arbitrary_field_present(self):
formatter = self.get_formatter(
| tests break with Python 3.8
Introduction of formatting string validation in ``logging.Formatter`` breaks several of our formatting control tests. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"ZConfig/components/logger/tests/test_formatter.py::LoggerStyledFormatterTestCase::test_safe_template_with_junk",
"ZConfig/components/logger/tests/test_formatter.py::ZopeExceptionsFormatterTestCase::test_safe_template_with_junk"
] | [
"ZConfig/components/logger/tests/test_formatter.py::LogFormatStyleTestCase::test_bad_values",
"ZConfig/components/logger/tests/test_formatter.py::LogFormatStyleTestCase::test_classic",
"ZConfig/components/logger/tests/test_formatter.py::LogFormatStyleTestCase::test_format",
"ZConfig/components/logger/tests/test_formatter.py::LogFormatStyleTestCase::test_safe_template",
"ZConfig/components/logger/tests/test_formatter.py::LogFormatStyleTestCase::test_template",
"ZConfig/components/logger/tests/test_formatter.py::LoggerStyledFormatterTestCase::test_classic_explicit",
"ZConfig/components/logger/tests/test_formatter.py::LoggerStyledFormatterTestCase::test_classic_implicit",
"ZConfig/components/logger/tests/test_formatter.py::LoggerStyledFormatterTestCase::test_format",
"ZConfig/components/logger/tests/test_formatter.py::LoggerStyledFormatterTestCase::test_format_with_anonymous_placeholders",
"ZConfig/components/logger/tests/test_formatter.py::LoggerStyledFormatterTestCase::test_format_with_positional_placeholders",
"ZConfig/components/logger/tests/test_formatter.py::LoggerStyledFormatterTestCase::test_safe_template_with_braces",
"ZConfig/components/logger/tests/test_formatter.py::LoggerStyledFormatterTestCase::test_safe_template_without_braces",
"ZConfig/components/logger/tests/test_formatter.py::LoggerStyledFormatterTestCase::test_template_with_braces",
"ZConfig/components/logger/tests/test_formatter.py::LoggerStyledFormatterTestCase::test_template_with_junk",
"ZConfig/components/logger/tests/test_formatter.py::LoggerStyledFormatterTestCase::test_template_without_braces",
"ZConfig/components/logger/tests/test_formatter.py::ZopeExceptionsFormatterTestCase::test_classic_explicit",
"ZConfig/components/logger/tests/test_formatter.py::ZopeExceptionsFormatterTestCase::test_classic_implicit",
"ZConfig/components/logger/tests/test_formatter.py::ZopeExceptionsFormatterTestCase::test_format",
"ZConfig/components/logger/tests/test_formatter.py::ZopeExceptionsFormatterTestCase::test_format_with_anonymous_placeholders",
"ZConfig/components/logger/tests/test_formatter.py::ZopeExceptionsFormatterTestCase::test_format_with_positional_placeholders",
"ZConfig/components/logger/tests/test_formatter.py::ZopeExceptionsFormatterTestCase::test_format_with_traceback_info",
"ZConfig/components/logger/tests/test_formatter.py::ZopeExceptionsFormatterTestCase::test_safe_template_with_braces",
"ZConfig/components/logger/tests/test_formatter.py::ZopeExceptionsFormatterTestCase::test_safe_template_without_braces",
"ZConfig/components/logger/tests/test_formatter.py::ZopeExceptionsFormatterTestCase::test_template_with_braces",
"ZConfig/components/logger/tests/test_formatter.py::ZopeExceptionsFormatterTestCase::test_template_with_junk",
"ZConfig/components/logger/tests/test_formatter.py::ZopeExceptionsFormatterTestCase::test_template_without_braces",
"ZConfig/components/logger/tests/test_formatter.py::CustomFormatterClassWithoutStyleParamTestCase::test_classic_explicit",
"ZConfig/components/logger/tests/test_formatter.py::CustomFormatterClassWithoutStyleParamTestCase::test_classic_implicit",
"ZConfig/components/logger/tests/test_formatter.py::CustomFormatterClassWithoutStyleParamTestCase::test_format",
"ZConfig/components/logger/tests/test_formatter.py::CustomFormatterClassWithoutStyleParamTestCase::test_format_with_anonymous_placeholders",
"ZConfig/components/logger/tests/test_formatter.py::CustomFormatterClassWithoutStyleParamTestCase::test_format_with_positional_placeholders",
"ZConfig/components/logger/tests/test_formatter.py::CustomFormatterClassWithoutStyleParamTestCase::test_safe_template_with_braces",
"ZConfig/components/logger/tests/test_formatter.py::CustomFormatterClassWithoutStyleParamTestCase::test_safe_template_with_junk",
"ZConfig/components/logger/tests/test_formatter.py::CustomFormatterClassWithoutStyleParamTestCase::test_safe_template_without_braces",
"ZConfig/components/logger/tests/test_formatter.py::CustomFormatterClassWithoutStyleParamTestCase::test_template_with_braces",
"ZConfig/components/logger/tests/test_formatter.py::CustomFormatterClassWithoutStyleParamTestCase::test_template_with_junk",
"ZConfig/components/logger/tests/test_formatter.py::CustomFormatterClassWithoutStyleParamTestCase::test_template_without_braces",
"ZConfig/components/logger/tests/test_formatter.py::CustomFormatterFactoryWithoutStyleParamTestCase::test_classic_explicit",
"ZConfig/components/logger/tests/test_formatter.py::CustomFormatterFactoryWithoutStyleParamTestCase::test_classic_implicit",
"ZConfig/components/logger/tests/test_formatter.py::CustomFormatterFactoryWithoutStyleParamTestCase::test_format",
"ZConfig/components/logger/tests/test_formatter.py::CustomFormatterFactoryWithoutStyleParamTestCase::test_format_with_anonymous_placeholders",
"ZConfig/components/logger/tests/test_formatter.py::CustomFormatterFactoryWithoutStyleParamTestCase::test_format_with_positional_placeholders",
"ZConfig/components/logger/tests/test_formatter.py::CustomFormatterFactoryWithoutStyleParamTestCase::test_safe_template_with_braces",
"ZConfig/components/logger/tests/test_formatter.py::CustomFormatterFactoryWithoutStyleParamTestCase::test_safe_template_with_junk",
"ZConfig/components/logger/tests/test_formatter.py::CustomFormatterFactoryWithoutStyleParamTestCase::test_safe_template_without_braces",
"ZConfig/components/logger/tests/test_formatter.py::CustomFormatterFactoryWithoutStyleParamTestCase::test_template_with_braces",
"ZConfig/components/logger/tests/test_formatter.py::CustomFormatterFactoryWithoutStyleParamTestCase::test_template_with_junk",
"ZConfig/components/logger/tests/test_formatter.py::CustomFormatterFactoryWithoutStyleParamTestCase::test_template_without_braces",
"ZConfig/components/logger/tests/test_formatter.py::FieldTypesTestCase::test_func_name_classic",
"ZConfig/components/logger/tests/test_formatter.py::FieldTypesTestCase::test_func_name_format",
"ZConfig/components/logger/tests/test_formatter.py::FieldTypesTestCase::test_func_name_template",
"ZConfig/components/logger/tests/test_formatter.py::FieldTypesTestCase::test_levelno_integer_classic",
"ZConfig/components/logger/tests/test_formatter.py::FieldTypesTestCase::test_levelno_integer_format",
"ZConfig/components/logger/tests/test_formatter.py::FieldTypesTestCase::test_msecs_float_classic",
"ZConfig/components/logger/tests/test_formatter.py::FieldTypesTestCase::test_msecs_float_format",
"ZConfig/components/logger/tests/test_formatter.py::FieldTypesTestCase::test_relative_created_float_classic",
"ZConfig/components/logger/tests/test_formatter.py::FieldTypesTestCase::test_relative_created_float_format",
"ZConfig/components/logger/tests/test_formatter.py::ArbitraryFieldsTestCase::test_classic_arbitrary_field_disallowed_by_default",
"ZConfig/components/logger/tests/test_formatter.py::ArbitraryFieldsTestCase::test_classic_arbitrary_field_missing",
"ZConfig/components/logger/tests/test_formatter.py::ArbitraryFieldsTestCase::test_classic_arbitrary_field_present",
"ZConfig/components/logger/tests/test_formatter.py::ArbitraryFieldsTestCase::test_format_arbitrary_field_disallowed_by_default",
"ZConfig/components/logger/tests/test_formatter.py::ArbitraryFieldsTestCase::test_format_arbitrary_field_missing",
"ZConfig/components/logger/tests/test_formatter.py::ArbitraryFieldsTestCase::test_format_arbitrary_field_present",
"ZConfig/components/logger/tests/test_formatter.py::ArbitraryFieldsTestCase::test_safe_template_arbitrary_field_missing",
"ZConfig/components/logger/tests/test_formatter.py::ArbitraryFieldsTestCase::test_safe_template_arbitrary_field_present",
"ZConfig/components/logger/tests/test_formatter.py::ArbitraryFieldsTestCase::test_template_arbitrary_field_disallowed_by_default",
"ZConfig/components/logger/tests/test_formatter.py::ArbitraryFieldsTestCase::test_template_arbitrary_field_missing",
"ZConfig/components/logger/tests/test_formatter.py::ArbitraryFieldsTestCase::test_template_arbitrary_field_present"
] | {
"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
} | "2019-09-17T23:32:25Z" | zpl-2.1 |
|
zopefoundation__ZODB-170 | diff --git a/CHANGES.rst b/CHANGES.rst
index 039cc6ec..f3f7d1cd 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -9,6 +9,8 @@
- Drop support for Python 3.3.
+- Ensure that the ``HistoricalStorageAdapter`` forwards the ``release`` method to
+ its base instance. See `issue 78 <https://github.com/zopefoundation/ZODB/issues/788>`_.
5.2.4 (2017-05-17)
==================
diff --git a/src/ZODB/mvccadapter.py b/src/ZODB/mvccadapter.py
index cacb6584..121e579b 100644
--- a/src/ZODB/mvccadapter.py
+++ b/src/ZODB/mvccadapter.py
@@ -27,10 +27,9 @@ class Base(object):
def __getattr__(self, name):
if name in self._copy_methods:
- if hasattr(self._storage, name):
- m = getattr(self._storage, name)
- setattr(self, name, m)
- return m
+ m = getattr(self._storage, name)
+ setattr(self, name, m)
+ return m
raise AttributeError(name)
@@ -204,7 +203,12 @@ class HistoricalStorageAdapter(Base):
return False
def release(self):
- pass
+ try:
+ release = self._storage.release
+ except AttributeError:
+ pass
+ else:
+ release()
close = release
| zopefoundation/ZODB | 5056d49e79bc06f6d343973d71c3c3185e18975e | diff --git a/src/ZODB/tests/test_mvccadapter.py b/src/ZODB/tests/test_mvccadapter.py
new file mode 100644
index 00000000..9b1f28cf
--- /dev/null
+++ b/src/ZODB/tests/test_mvccadapter.py
@@ -0,0 +1,60 @@
+##############################################################################
+#
+# Copyright (c) 2017 Zope Foundation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+
+import unittest
+
+from ZODB import mvccadapter
+
+
+class TestBase(unittest.TestCase):
+
+ def test_getattr_does_not_hide_exceptions(self):
+ class TheException(Exception):
+ pass
+
+ class RaisesOnAccess(object):
+
+ @property
+ def thing(self):
+ raise TheException()
+
+ base = mvccadapter.Base(RaisesOnAccess())
+ base._copy_methods = ('thing',)
+
+ with self.assertRaises(TheException):
+ getattr(base, 'thing')
+
+ def test_getattr_raises_if_missing(self):
+ base = mvccadapter.Base(self)
+ base._copy_methods = ('thing',)
+
+ with self.assertRaises(AttributeError):
+ getattr(base, 'thing')
+
+
+class TestHistoricalStorageAdapter(unittest.TestCase):
+
+ def test_forwards_release(self):
+ class Base(object):
+ released = False
+
+ def release(self):
+ self.released = True
+
+ base = Base()
+ adapter = mvccadapter.HistoricalStorageAdapter(base, None)
+
+ adapter.release()
+
+ self.assertTrue(base.released)
| HistoricalStorageAdapter does not forward release to its base
This causes a connection leak on RelStorage.
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/ZODB/tests/test_mvccadapter.py::TestHistoricalStorageAdapter::test_forwards_release"
] | [
"src/ZODB/tests/test_mvccadapter.py::TestBase::test_getattr_does_not_hide_exceptions",
"src/ZODB/tests/test_mvccadapter.py::TestBase::test_getattr_raises_if_missing"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2017-07-24T17:15:54Z" | zpl-2.1 |
|
zopefoundation__ZODB-260 | diff --git a/src/ZODB/scripts/repozo.py b/src/ZODB/scripts/repozo.py
index d9422ad2..70d323f5 100755
--- a/src/ZODB/scripts/repozo.py
+++ b/src/ZODB/scripts/repozo.py
@@ -251,6 +251,8 @@ def parseargs(argv):
if options.withverify is not None:
log('--with-verify option is ignored in backup mode')
options.withverify = None
+ if not options.file:
+ usage(1, '--file is required in backup mode')
elif options.mode == RECOVER:
if options.file is not None:
log('--file option is ignored in recover mode')
| zopefoundation/ZODB | 334282c34cac6f3dabceb560940d7e881dd6b853 | diff --git a/src/ZODB/scripts/tests/test_repozo.py b/src/ZODB/scripts/tests/test_repozo.py
index 785069f4..f9076092 100644
--- a/src/ZODB/scripts/tests/test_repozo.py
+++ b/src/ZODB/scripts/tests/test_repozo.py
@@ -150,7 +150,8 @@ class Test_parseargs(unittest.TestCase):
def test_mode_selection(self):
from ZODB.scripts import repozo
- options = repozo.parseargs(['-B', '-r', '/tmp/nosuchdir'])
+ options = repozo.parseargs([
+ '-B', '-f', '/tmp/Data.fs', '-r', '/tmp/nosuchdir'])
self.assertEqual(options.mode, repozo.BACKUP)
options = repozo.parseargs(['-R', '-r', '/tmp/nosuchdir'])
self.assertEqual(options.mode, repozo.RECOVER)
@@ -173,9 +174,11 @@ class Test_parseargs(unittest.TestCase):
def test_misc_flags(self):
from ZODB.scripts import repozo
- options = repozo.parseargs(['-B', '-r', '/tmp/nosuchdir', '-F'])
+ options = repozo.parseargs([
+ '-B', '-f', '/tmp/Data.fs', '-r', '/tmp/nosuchdir', '-F'])
self.assertTrue(options.full)
- options = repozo.parseargs(['-B', '-r', '/tmp/nosuchdir', '-k'])
+ options = repozo.parseargs([
+ '-B', '-f', '/tmp/Data.fs', '-r', '/tmp/nosuchdir', '-k'])
self.assertTrue(options.killold)
def test_repo_is_required(self):
@@ -186,6 +189,7 @@ class Test_parseargs(unittest.TestCase):
def test_backup_ignored_args(self):
from ZODB.scripts import repozo
options = repozo.parseargs(['-B', '-r', '/tmp/nosuchdir', '-v',
+ '-f', '/tmp/Data.fs',
'-o', '/tmp/ignored.fs',
'-D', '2011-12-13'])
self.assertEqual(options.date, None)
@@ -195,6 +199,12 @@ class Test_parseargs(unittest.TestCase):
self.assertIn('--output option is ignored in backup mode',
sys.stderr.getvalue())
+ def test_backup_required_args(self):
+ from ZODB.scripts import repozo
+ self.assertRaises(SystemExit, repozo.parseargs,
+ ['-B', '-r', '/tmp/nosuchdir'])
+ self.assertIn('--file is required', sys.stderr.getvalue())
+
def test_recover_ignored_args(self):
from ZODB.scripts import repozo
options = repozo.parseargs(['-R', '-r', '/tmp/nosuchdir', '-v',
| Repozo/Filestorage: TypeError: expected str, bytes or os.PathLike object, not NoneType
Plone 5.2RC1, ZODB 5.5.1, Python 3.6:
```
dgho@server:~/onkopedia_buildout$ bin/repozo --backup --repository /tmp/foo
Traceback (most recent call last):
File "bin/repozo", line 20, in <module>
sys.exit(ZODB.scripts.repozo.main())
File "/home/dgho/onkopedia_buildout/eggs/ZODB-5.5.1-py3.6.egg/ZODB/scripts/repozo.py", line 730, in main
do_backup(options)
File "/home/dgho/onkopedia_buildout/eggs/ZODB-5.5.1-py3.6.egg/ZODB/scripts/repozo.py", line 565, in do_backup
do_full_backup(options)
File "/home/dgho/onkopedia_buildout/eggs/ZODB-5.5.1-py3.6.egg/ZODB/scripts/repozo.py", line 500, in do_full_backup
fs = FileStorage(options.file, read_only=True)
File "/home/dgho/onkopedia_buildout/eggs/ZODB-5.5.1-py3.6.egg/ZODB/FileStorage/FileStorage.py", line 248, in __init__
self._file_name = os.path.abspath(file_name)
File "/usr/lib/python3.6/posixpath.py", line 371, in abspath
path = os.fspath(path)
TypeError: expected str, bytes or os.PathLike object, not NoneType
dgho@server:~/onkopedia_buildout$ bin/python
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
``` | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/ZODB/scripts/tests/test_repozo.py::Test_parseargs::test_backup_required_args"
] | [
"src/ZODB/scripts/tests/test_repozo.py::Test_parseargs::test_backup_ignored_args",
"src/ZODB/scripts/tests/test_repozo.py::Test_parseargs::test_bad_argument",
"src/ZODB/scripts/tests/test_repozo.py::Test_parseargs::test_bad_option",
"src/ZODB/scripts/tests/test_repozo.py::Test_parseargs::test_help",
"src/ZODB/scripts/tests/test_repozo.py::Test_parseargs::test_long",
"src/ZODB/scripts/tests/test_repozo.py::Test_parseargs::test_misc_flags",
"src/ZODB/scripts/tests/test_repozo.py::Test_parseargs::test_mode_selection",
"src/ZODB/scripts/tests/test_repozo.py::Test_parseargs::test_mode_selection_is_mutually_exclusive",
"src/ZODB/scripts/tests/test_repozo.py::Test_parseargs::test_mode_selection_required",
"src/ZODB/scripts/tests/test_repozo.py::Test_parseargs::test_recover_ignored_args",
"src/ZODB/scripts/tests/test_repozo.py::Test_parseargs::test_repo_is_required",
"src/ZODB/scripts/tests/test_repozo.py::Test_parseargs::test_short",
"src/ZODB/scripts/tests/test_repozo.py::Test_parseargs::test_verify_ignored_args",
"src/ZODB/scripts/tests/test_repozo.py::Test_dofile::test_empty_read_all",
"src/ZODB/scripts/tests/test_repozo.py::Test_dofile::test_empty_read_count",
"src/ZODB/scripts/tests/test_repozo.py::Test_dofile::test_nonempty_read_all",
"src/ZODB/scripts/tests/test_repozo.py::Test_dofile::test_nonempty_read_count",
"src/ZODB/scripts/tests/test_repozo.py::Test_checksum::test_empty_read_all",
"src/ZODB/scripts/tests/test_repozo.py::Test_checksum::test_empty_read_count",
"src/ZODB/scripts/tests/test_repozo.py::Test_checksum::test_nonempty_read_all",
"src/ZODB/scripts/tests/test_repozo.py::Test_checksum::test_nonempty_read_count",
"src/ZODB/scripts/tests/test_repozo.py::Test_copyfile::test_no_gzip",
"src/ZODB/scripts/tests/test_repozo.py::Test_copyfile::test_w_gzip",
"src/ZODB/scripts/tests/test_repozo.py::Test_concat::test_empty_list_no_ofp",
"src/ZODB/scripts/tests/test_repozo.py::Test_concat::test_w_gzipped_files_no_ofp",
"src/ZODB/scripts/tests/test_repozo.py::Test_concat::test_w_ofp",
"src/ZODB/scripts/tests/test_repozo.py::Test_concat::test_w_plain_files_no_ofp",
"src/ZODB/scripts/tests/test_repozo.py::Test_gen_filename::test_explicit_ext",
"src/ZODB/scripts/tests/test_repozo.py::Test_gen_filename::test_full_no_gzip",
"src/ZODB/scripts/tests/test_repozo.py::Test_gen_filename::test_full_w_gzip",
"src/ZODB/scripts/tests/test_repozo.py::Test_gen_filename::test_incr_no_gzip",
"src/ZODB/scripts/tests/test_repozo.py::Test_gen_filename::test_incr_w_gzip",
"src/ZODB/scripts/tests/test_repozo.py::Test_find_files::test_explicit_date",
"src/ZODB/scripts/tests/test_repozo.py::Test_find_files::test_no_files",
"src/ZODB/scripts/tests/test_repozo.py::Test_find_files::test_using_gen_filename",
"src/ZODB/scripts/tests/test_repozo.py::Test_scandat::test_empty_dat_file",
"src/ZODB/scripts/tests/test_repozo.py::Test_scandat::test_multiple_lines",
"src/ZODB/scripts/tests/test_repozo.py::Test_scandat::test_no_dat_file",
"src/ZODB/scripts/tests/test_repozo.py::Test_scandat::test_single_line",
"src/ZODB/scripts/tests/test_repozo.py::Test_delete_old_backups::test_doesnt_remove_current_repozo_files",
"src/ZODB/scripts/tests/test_repozo.py::Test_delete_old_backups::test_empty_dir_doesnt_raise",
"src/ZODB/scripts/tests/test_repozo.py::Test_delete_old_backups::test_no_repozo_files_doesnt_raise",
"src/ZODB/scripts/tests/test_repozo.py::Test_delete_old_backups::test_removes_older_repozo_files",
"src/ZODB/scripts/tests/test_repozo.py::Test_delete_old_backups::test_removes_older_repozo_files_zipped",
"src/ZODB/scripts/tests/test_repozo.py::Test_do_full_backup::test_dont_overwrite_existing_file",
"src/ZODB/scripts/tests/test_repozo.py::Test_do_full_backup::test_empty",
"src/ZODB/scripts/tests/test_repozo.py::Test_do_incremental_backup::test_dont_overwrite_existing_file",
"src/ZODB/scripts/tests/test_repozo.py::Test_do_incremental_backup::test_no_changes",
"src/ZODB/scripts/tests/test_repozo.py::Test_do_incremental_backup::test_w_changes",
"src/ZODB/scripts/tests/test_repozo.py::Test_do_recover::test_no_files",
"src/ZODB/scripts/tests/test_repozo.py::Test_do_recover::test_no_files_before_explicit_date",
"src/ZODB/scripts/tests/test_repozo.py::Test_do_recover::test_w_full_backup_latest_index",
"src/ZODB/scripts/tests/test_repozo.py::Test_do_recover::test_w_full_backup_latest_no_index",
"src/ZODB/scripts/tests/test_repozo.py::Test_do_recover::test_w_incr_backup_latest_index",
"src/ZODB/scripts/tests/test_repozo.py::Test_do_recover::test_w_incr_backup_latest_no_index",
"src/ZODB/scripts/tests/test_repozo.py::Test_do_recover::test_w_incr_backup_with_verify_all_is_fine",
"src/ZODB/scripts/tests/test_repozo.py::Test_do_recover::test_w_incr_backup_with_verify_size_inconsistent",
"src/ZODB/scripts/tests/test_repozo.py::Test_do_recover::test_w_incr_backup_with_verify_sum_inconsistent",
"src/ZODB/scripts/tests/test_repozo.py::Test_do_verify::test_all_is_fine",
"src/ZODB/scripts/tests/test_repozo.py::Test_do_verify::test_all_is_fine_gzip",
"src/ZODB/scripts/tests/test_repozo.py::Test_do_verify::test_bad_checksum",
"src/ZODB/scripts/tests/test_repozo.py::Test_do_verify::test_bad_checksum_gzip",
"src/ZODB/scripts/tests/test_repozo.py::Test_do_verify::test_bad_size",
"src/ZODB/scripts/tests/test_repozo.py::Test_do_verify::test_bad_size_gzip",
"src/ZODB/scripts/tests/test_repozo.py::Test_do_verify::test_missing_file",
"src/ZODB/scripts/tests/test_repozo.py::Test_do_verify::test_missing_file_gzip",
"src/ZODB/scripts/tests/test_repozo.py::Test_do_verify::test_no_files",
"src/ZODB/scripts/tests/test_repozo.py::Test_do_verify::test_quick_ignores_checksums",
"src/ZODB/scripts/tests/test_repozo.py::Test_do_verify::test_quick_ignores_checksums_gzip",
"src/ZODB/scripts/tests/test_repozo.py::MonteCarloTests::test_via_monte_carlo",
"src/ZODB/scripts/tests/test_repozo.py::test_suite"
] | {
"failed_lite_validators": [
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2019-03-18T11:50:11Z" | zpl-2.1 |
|
zopefoundation__ZODB-269 | diff --git a/CHANGES.rst b/CHANGES.rst
index a8968eb9..3331176d 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -13,12 +13,17 @@
- Drop support for Python 3.4.
+- Fix ``DB.undo()`` and ``DB.undoMultiple()`` to close the storage
+ they open behind the scenes when the transaction is committed or
+ rolled back. See `issue 268
+ <https://github.com/zopefoundation/ZODB/issues/268>`_.
+
5.5.1 (2018-10-25)
==================
- Fix KeyError on releasing resources of a Connection when closing the DB.
- This requires at least version 2.4 of the `transaction` package.
- See `issue 208 <https://github.com/zopefoundation/ZODB/issues/208>`.
+ This requires at least version 2.4 of the ``transaction`` package.
+ See `issue 208 <https://github.com/zopefoundation/ZODB/issues/208>`_.
5.5.0 (2018-10-13)
==================
diff --git a/src/ZODB/DB.py b/src/ZODB/DB.py
index 6a5af7c1..38a9edb6 100644
--- a/src/ZODB/DB.py
+++ b/src/ZODB/DB.py
@@ -14,32 +14,29 @@
"""Database objects
"""
from __future__ import print_function
+
import sys
import logging
import datetime
import time
import warnings
-from . import utils
-
-from ZODB.broken import find_global
-from ZODB.utils import z64
-from ZODB.Connection import Connection, TransactionMetaData, noop
-from ZODB._compat import Pickler, _protocol, BytesIO
-import ZODB.serialize
+from persistent.TimeStamp import TimeStamp
+import six
+import transaction
import transaction.weakset
from zope.interface import implementer
+
+from ZODB import utils
from ZODB.interfaces import IDatabase
from ZODB.interfaces import IMVCCStorage
-
-import transaction
-
-from persistent.TimeStamp import TimeStamp
-import six
-
-from . import POSException, valuedoc
+from ZODB.broken import find_global
+from ZODB.utils import z64
+from ZODB.Connection import Connection, TransactionMetaData, noop
+import ZODB.serialize
+from ZODB import valuedoc
logger = logging.getLogger('ZODB.DB')
@@ -1056,19 +1053,43 @@ class TransactionalUndo(object):
def __init__(self, db, tids):
self._db = db
- self._storage = getattr(
- db._mvcc_storage, 'undo_instance', db._mvcc_storage.new_instance)()
self._tids = tids
+ self._storage = None
def abort(self, transaction):
pass
+ def close(self):
+ if self._storage is not None:
+ # We actually want to release the storage we've created,
+ # not close it. releasing it frees external resources
+ # dedicated to this instance, closing might make permanent
+ # changes that affect other instances.
+ self._storage.release()
+ self._storage = None
+
def tpc_begin(self, transaction):
+ assert self._storage is None, "Already in an active transaction"
+
tdata = TransactionMetaData(
transaction.user,
transaction.description,
transaction.extension)
transaction.set_data(self, tdata)
+ # `undo_instance` is not part of any IStorage interface;
+ # it is defined in our MVCCAdapter. Regardless, we're opening
+ # a new storage instance, and so we must close it to be sure
+ # to reclaim resources in a timely manner.
+ #
+ # Once the tpc_begin method has been called, the transaction manager will
+ # guarantee to call either `tpc_finish` or `tpc_abort`, so those are the only
+ # methods we need to be concerned about calling close() from.
+ db_mvcc_storage = self._db._mvcc_storage
+ self._storage = getattr(
+ db_mvcc_storage,
+ 'undo_instance',
+ db_mvcc_storage.new_instance)()
+
self._storage.tpc_begin(tdata)
def commit(self, transaction):
@@ -1081,15 +1102,27 @@ class TransactionalUndo(object):
self._storage.tpc_vote(transaction)
def tpc_finish(self, transaction):
- transaction = transaction.data(self)
- self._storage.tpc_finish(transaction)
+ try:
+ transaction = transaction.data(self)
+ self._storage.tpc_finish(transaction)
+ finally:
+ self.close()
def tpc_abort(self, transaction):
- transaction = transaction.data(self)
- self._storage.tpc_abort(transaction)
+ try:
+ transaction = transaction.data(self)
+ self._storage.tpc_abort(transaction)
+ finally:
+ self.close()
def sortKey(self):
- return "%s:%s" % (self._storage.sortKey(), id(self))
+ # The transaction sorts data managers first before it calls
+ # `tpc_begin`, so we can't use our own storage because it's
+ # not open yet. Fortunately new_instances of a storage are
+ # supposed to return the same sort key as the original storage
+ # did.
+ return "%s:%s" % (self._db._mvcc_storage.sortKey(), id(self))
+
def connection(*args, **kw):
"""Create a database :class:`connection <ZODB.Connection.Connection>`.
| zopefoundation/ZODB | 79fe4737e3df5916bd4ce48d49b65caf26000cd4 | diff --git a/src/ZODB/tests/testDB.py b/src/ZODB/tests/testDB.py
index f19a6fca..7d24d864 100644
--- a/src/ZODB/tests/testDB.py
+++ b/src/ZODB/tests/testDB.py
@@ -110,6 +110,117 @@ class DBTests(ZODB.tests.util.TestCase):
check(db.undoLog(0, 3) , True)
check(db.undoInfo(0, 3) , True)
+
+class TransactionalUndoTests(unittest.TestCase):
+
+ def _makeOne(self):
+ from ZODB.DB import TransactionalUndo
+
+ class MockStorage(object):
+ instance_count = 0
+ close_count = 0
+ release_count = 0
+ begin_count = 0
+ abort_count = 0
+
+ def new_instance(self):
+ self.instance_count += 1
+ return self
+
+ def tpc_begin(self, tx):
+ self.begin_count += 1
+
+ def close(self):
+ self.close_count += 1
+
+ def release(self):
+ self.release_count += 1
+
+ def sortKey(self):
+ return 'MockStorage'
+
+ class MockDB(object):
+
+ def __init__(self):
+ self.storage = self._mvcc_storage = MockStorage()
+
+ return TransactionalUndo(MockDB(), [1])
+
+ def test_only_new_instance_on_begin(self):
+ undo = self._makeOne()
+ self.assertIsNone(undo._storage)
+ self.assertEqual(0, undo._db.storage.instance_count)
+
+ undo.tpc_begin(transaction.get())
+ self.assertIsNotNone(undo._storage)
+ self.assertEqual(1, undo._db.storage.instance_count)
+ self.assertEqual(1, undo._db.storage.begin_count)
+ self.assertIsNotNone(undo._storage)
+
+ # And we can't begin again
+ with self.assertRaises(AssertionError):
+ undo.tpc_begin(transaction.get())
+
+ def test_close_many(self):
+ undo = self._makeOne()
+ self.assertIsNone(undo._storage)
+ self.assertEqual(0, undo._db.storage.instance_count)
+
+ undo.close()
+ # Not open, didn't go through
+ self.assertEqual(0, undo._db.storage.close_count)
+ self.assertEqual(0, undo._db.storage.release_count)
+
+ undo.tpc_begin(transaction.get())
+ undo.close()
+ undo.close()
+ self.assertEqual(0, undo._db.storage.close_count)
+ self.assertEqual(1, undo._db.storage.release_count)
+ self.assertIsNone(undo._storage)
+
+ def test_sortKey(self):
+ # We get the same key whether or not we're open
+ undo = self._makeOne()
+ key = undo.sortKey()
+ self.assertIn('MockStorage', key)
+
+ undo.tpc_begin(transaction.get())
+ key2 = undo.sortKey()
+ self.assertEqual(key, key2)
+
+ def test_tpc_abort_closes(self):
+ undo = self._makeOne()
+ undo.tpc_begin(transaction.get())
+ undo._db.storage.tpc_abort = lambda tx: None
+ undo.tpc_abort(transaction.get())
+ self.assertEqual(0, undo._db.storage.close_count)
+ self.assertEqual(1, undo._db.storage.release_count)
+
+ def test_tpc_abort_closes_on_exception(self):
+ undo = self._makeOne()
+ undo.tpc_begin(transaction.get())
+ with self.assertRaises(AttributeError):
+ undo.tpc_abort(transaction.get())
+ self.assertEqual(0, undo._db.storage.close_count)
+ self.assertEqual(1, undo._db.storage.release_count)
+
+ def test_tpc_finish_closes(self):
+ undo = self._makeOne()
+ undo.tpc_begin(transaction.get())
+ undo._db.storage.tpc_finish = lambda tx: None
+ undo.tpc_finish(transaction.get())
+ self.assertEqual(0, undo._db.storage.close_count)
+ self.assertEqual(1, undo._db.storage.release_count)
+
+ def test_tpc_finish_closes_on_exception(self):
+ undo = self._makeOne()
+ undo.tpc_begin(transaction.get())
+ with self.assertRaises(AttributeError):
+ undo.tpc_finish(transaction.get())
+ self.assertEqual(0, undo._db.storage.close_count)
+ self.assertEqual(1, undo._db.storage.release_count)
+
+
def test_invalidateCache():
"""The invalidateCache method invalidates a connection caches for all of
the connections attached to a database::
@@ -423,7 +534,7 @@ def cleanup_on_close():
"""
def test_suite():
- s = unittest.makeSuite(DBTests)
+ s = unittest.defaultTestLoader.loadTestsFromName(__name__)
s.addTest(doctest.DocTestSuite(
setUp=ZODB.tests.util.setUp, tearDown=ZODB.tests.util.tearDown,
checker=checker
| DB.undo() leaks MVCC storages
I see this [in the relstorage tests](https://github.com/zodb/relstorage/issues/225). That means the underlying database connections leak.
Here's where a storage is allocated by calling `new_instance()`:
```Python traceback
File "//relstorage/src/relstorage/tests/blob/testblob.py", line 146, in testUndoWithoutPreviousVersion
database.undo(database.undoLog(0, 1)[0]['id'])
File "//lib/python3.7/site-packages/ZODB/DB.py", line 997, in undo
self.undoMultiple([id], txn)
File "//lib/python3.7/site-packages/ZODB/DB.py", line 978, in undoMultiple
txn.join(TransactionalUndo(self, ids))
File "//lib/python3.7/site-packages/ZODB/DB.py", line 1060, in __init__
db._mvcc_storage, 'undo_instance', db._mvcc_storage.new_instance)()
```
The `TransactionalUndo` object never closes the new storage.
RelStorage could potentially work around this (e.g., implement a 'undo_instance' method that returns a special storage wrapper that closes itself in `tpc_finish` and `tpc_abort`), but it seems like the more general solution would be for `TransactionalUndo` to close the storage it opened in its implementation of those methods. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/ZODB/tests/testDB.py::TransactionalUndoTests::test_close_many",
"src/ZODB/tests/testDB.py::TransactionalUndoTests::test_only_new_instance_on_begin",
"src/ZODB/tests/testDB.py::TransactionalUndoTests::test_tpc_abort_closes",
"src/ZODB/tests/testDB.py::TransactionalUndoTests::test_tpc_abort_closes_on_exception",
"src/ZODB/tests/testDB.py::TransactionalUndoTests::test_tpc_finish_closes",
"src/ZODB/tests/testDB.py::TransactionalUndoTests::test_tpc_finish_closes_on_exception"
] | [
"src/ZODB/tests/testDB.py::DBTests::testSets",
"src/ZODB/tests/testDB.py::DBTests::test_history_and_undo_meta_data_text_handlinf",
"src/ZODB/tests/testDB.py::DBTests::test_references",
"src/ZODB/tests/testDB.py::TransactionalUndoTests::test_sortKey",
"src/ZODB/tests/testDB.py::test_invalidateCache",
"src/ZODB/tests/testDB.py::test_suite"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2019-05-14T15:09:05Z" | zpl-2.1 |
|
zopefoundation__ZODB-291 | diff --git a/CHANGES.rst b/CHANGES.rst
index 218116b6..43d58729 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -5,6 +5,11 @@
5.6.0 (unreleased)
==================
+- Fix race with invalidations when starting a new transaction. The bug
+ affected Storage implementations that rely on mvccadapter, and could result
+ in data corruption (oid loaded at wrong serial after a concurrent commit).
+ See `issue 290 <https://github.com/zopefoundation/ZODB/issues/290>`_.
+
- Improve volatile attribute ``_v_`` documentation.
- Make repozo's recover mode atomic by recovering the backup in a
diff --git a/src/ZODB/mvccadapter.py b/src/ZODB/mvccadapter.py
index 121e579b..c625c141 100644
--- a/src/ZODB/mvccadapter.py
+++ b/src/ZODB/mvccadapter.py
@@ -49,6 +49,7 @@ class MVCCAdapter(Base):
instance = MVCCAdapterInstance(self)
with self._lock:
self._instances.add(instance)
+ instance._lastTransaction()
return instance
def before_instance(self, before=None):
@@ -77,13 +78,13 @@ class MVCCAdapter(Base):
def invalidate(self, transaction_id, oids):
with self._lock:
for instance in self._instances:
- instance._invalidate(oids)
+ instance._invalidate(transaction_id, oids)
- def _invalidate_finish(self, oids, committing_instance):
+ def _invalidate_finish(self, tid, oids, committing_instance):
with self._lock:
for instance in self._instances:
if instance is not committing_instance:
- instance._invalidate(oids)
+ instance._invalidate(tid, oids)
references = serialize.referencesf
transform_record_data = untransform_record_data = lambda self, data: data
@@ -98,14 +99,26 @@ class MVCCAdapterInstance(Base):
'checkCurrentSerialInTransaction', 'tpc_abort',
)
+ _start = None # Transaction start time
+ _ltid = None # Last storage transaction id
+
def __init__(self, base):
self._base = base
Base.__init__(self, base._storage)
self._lock = Lock()
self._invalidations = set()
- self._start = None # Transaction start time
self._sync = getattr(self._storage, 'sync', lambda : None)
+ def _lastTransaction(self):
+ ltid = self._storage.lastTransaction()
+ # At this precise moment, a transaction may be
+ # committed and we have already received the new tid.
+ with self._lock:
+ # So make sure we won't override with a smaller value.
+ if self._ltid is None:
+ # Calling lastTransaction() here could result in a deadlock.
+ self._ltid = ltid
+
def release(self):
self._base._release(self)
@@ -115,8 +128,9 @@ class MVCCAdapterInstance(Base):
with self._lock:
self._invalidations = None
- def _invalidate(self, oids):
+ def _invalidate(self, tid, oids):
with self._lock:
+ self._ltid = tid
try:
self._invalidations.update(oids)
except AttributeError:
@@ -128,8 +142,8 @@ class MVCCAdapterInstance(Base):
self._sync()
def poll_invalidations(self):
- self._start = p64(u64(self._storage.lastTransaction()) + 1)
with self._lock:
+ self._start = p64(u64(self._ltid) + 1)
if self._invalidations is None:
self._invalidations = set()
return None
@@ -175,7 +189,8 @@ class MVCCAdapterInstance(Base):
self._modified = None
def invalidate_finish(tid):
- self._base._invalidate_finish(modified, self)
+ self._base._invalidate_finish(tid, modified, self)
+ self._ltid = tid
func(tid)
return self._storage.tpc_finish(transaction, invalidate_finish)
@@ -260,7 +275,7 @@ class UndoAdapterInstance(Base):
def tpc_finish(self, transaction, func = lambda tid: None):
def invalidate_finish(tid):
- self._base._invalidate_finish(self._undone, None)
+ self._base._invalidate_finish(tid, self._undone, None)
func(tid)
self._storage.tpc_finish(transaction, invalidate_finish)
| zopefoundation/ZODB | 12b52a71b4739aeec728603a60298118a2d4e2bc | diff --git a/src/ZODB/FileStorage/tests.py b/src/ZODB/FileStorage/tests.py
index 64d08287..fb564d41 100644
--- a/src/ZODB/FileStorage/tests.py
+++ b/src/ZODB/FileStorage/tests.py
@@ -113,15 +113,15 @@ def pack_with_repeated_blob_records():
fixed by the time you read this, but there might still be
transactions in the wild that have duplicate records.
- >>> fs = ZODB.FileStorage.FileStorage('t', blob_dir='bobs')
- >>> db = ZODB.DB(fs)
+ >>> db = ZODB.DB(ZODB.FileStorage.FileStorage('t', blob_dir='bobs'))
>>> conn = db.open()
>>> conn.root()[1] = ZODB.blob.Blob()
>>> transaction.commit()
>>> tm = transaction.TransactionManager()
>>> oid = conn.root()[1]._p_oid
- >>> from ZODB.utils import load_current
- >>> blob_record, oldserial = load_current(fs, oid)
+ >>> fs = db._mvcc_storage.new_instance()
+ >>> _ = fs.poll_invalidations()
+ >>> blob_record, oldserial = fs.load(oid)
Now, create a transaction with multiple saves:
diff --git a/src/ZODB/tests/testConnection.py b/src/ZODB/tests/testConnection.py
index 88276b9c..2fe003eb 100644
--- a/src/ZODB/tests/testConnection.py
+++ b/src/ZODB/tests/testConnection.py
@@ -14,6 +14,7 @@
"""Unit tests for the Connection class."""
from __future__ import print_function
+from contextlib import contextmanager
import doctest
import re
import six
@@ -535,13 +536,13 @@ class InvalidationTests(unittest.TestCase):
>>> mvcc_storage.invalidate(p64(1), {p1._p_oid: 1})
- Transaction start times are based on storage's last
- transaction. (Previousely, they were based on the first
- invalidation seen in a transaction.)
+ Transaction start times are based on storage's last transaction,
+ which is known from invalidations. (Previousely, they were
+ based on the first invalidation seen in a transaction.)
>>> mvcc_instance.poll_invalidations() == [p1._p_oid]
True
- >>> mvcc_instance._start == p64(u64(db.storage.lastTransaction()) + 1)
+ >>> mvcc_instance._start == p64(2)
True
>>> mvcc_storage.invalidate(p64(10), {p2._p_oid: 1, p64(76): 1})
@@ -570,6 +571,36 @@ class InvalidationTests(unittest.TestCase):
>>> db.close()
"""
+ def test_mvccadapterNewTransactionVsInvalidations(self):
+ """
+ Check that polled invalidations are consistent with the TID at which
+ the transaction operates. Otherwise, it's like we miss invalidations.
+ """
+ db = databaseFromString("<zodb>\n<mappingstorage/>\n</zodb>")
+ try:
+ t1 = transaction.TransactionManager()
+ c1 = db.open(t1)
+ r1 = c1.root()
+ r1['a'] = 1
+ t1.commit()
+ t2 = transaction.TransactionManager()
+ c2 = db.open(t2)
+ c2.root()['b'] = 1
+ s1 = c1._storage
+ l1 = s1._lock
+ @contextmanager
+ def beforeLock1():
+ s1._lock = l1
+ t2.commit()
+ with l1:
+ yield
+ s1._lock = beforeLock1()
+ t1.begin()
+ self.assertIs(s1._lock, l1)
+ self.assertIn('b', r1)
+ finally:
+ db.close()
+
def doctest_invalidateCache():
"""The invalidateCache method invalidates a connection's cache.
@@ -1395,4 +1426,5 @@ def test_suite():
s.addTest(doctest.DocTestSuite(checker=checker))
s.addTest(unittest.makeSuite(TestConnection))
s.addTest(unittest.makeSuite(EstimatedSizeTests))
+ s.addTest(unittest.makeSuite(InvalidationTests))
return s
diff --git a/src/ZODB/tests/testmvcc.py b/src/ZODB/tests/testmvcc.py
index ff52af5c..4316e0e5 100644
--- a/src/ZODB/tests/testmvcc.py
+++ b/src/ZODB/tests/testmvcc.py
@@ -85,13 +85,14 @@ storage has seen.
>>> cn = db.open()
->>> cn._storage._start == p64(u64(st.lastTransaction()) + 1)
+>>> ltid = u64(st.lastTransaction())
+>>> cn._storage._start == p64(ltid + 1)
True
->>> cn.db()._mvcc_storage.invalidate(100, dict.fromkeys([1, 2]))
->>> cn._storage._start == p64(u64(st.lastTransaction()) + 1)
+>>> cn.db()._mvcc_storage.invalidate(p64(ltid+100), dict.fromkeys([1, 2]))
+>>> cn._storage._start == p64(ltid + 1)
True
->>> cn.db()._mvcc_storage.invalidate(200, dict.fromkeys([1, 2]))
->>> cn._storage._start == p64(u64(st.lastTransaction()) + 1)
+>>> cn.db()._mvcc_storage.invalidate(p64(ltid+200), dict.fromkeys([1, 2]))
+>>> cn._storage._start == p64(ltid + 1)
True
A connection's high-water mark is set to the transaction id taken from
@@ -105,7 +106,7 @@ but that doesn't work unless an object is modified. sync() will abort
a transaction and process invalidations.
>>> cn.sync()
->>> cn._storage._start == p64(u64(st.lastTransaction()) + 1)
+>>> cn._storage._start == p64(ltid + 201)
True
Basic functionality
| Race in Connection.open() vs invalidations -> corrupt data
Hello up there,
For wendelin.core v2 I need a way to know at which particular database state application-level ZODB connection is viewing the database. I was looking for that in `Connection.open` / `MVCCAdapter` code and noticed concurrency bug that leads to wrong data returned by ZODB to application:
---- 8< ---- ([zopenrace.py](https://lab.nexedi.com/kirr/wendelin.core/blob/5fb60c76/zopenrace.py))
```py
#!/usr/bin/env python
"""Program zopenrace.py demonstrates concurrency bug in ZODB Connection.open()
that leads to stale live cache and wrong data provided by database to users.
The bug is that when a connection is opened, it syncs to storage and processes
invalidations received from the storage in two _separate_ steps, potentially
leading to situation where invalidations for transactions _past_ opened
connection's view of the database are included into opened connection's cache
invalidation. This leads to stale connection cache and old data provided by
ZODB.Connection when it is reopened next time.
That in turn can lead to loose of Consistency of the database if mix of current
and old data is used to process a transaction. A classic example would be bank
accounts A, B and C with A<-B and A<-C transfer transactions. If transaction
that handles A<-C sees stale data for A when starting its processing, it
results in A loosing what it should have received from B.
Below is timing diagram on how the bug happens on ZODB5:
Client1 or Thread1 Client2 or Thread2
# T1 begins transaction and opens zodb connection
newTransaction():
# implementation in Connection.py[1]
._storage.sync()
invalidated = ._storage.poll_invalidations():
# implementation in MVCCAdapterInstance [2]
# T1 settles on as of which particular database state it will be
# viewing the database.
._storage._start = ._storage._storage.lastTrasaction() + 1:
s = ._storage._storage
s._lock.acquire()
head = s._ltid
s._lock.release()
return head
# T2 commits here.
# Time goes by and storage server sends
# corresponding invalidation message to T1,
# which T1 queues in its _storage._invalidations
# T1 retrieves queued invalidations which _includes_
# invalidation for transaction that T2 just has committed past @head.
._storage._lock.acquire()
r = _storage._invalidations
._storage._lock.release()
return r
# T1 processes invalidations for [... head] _and_ invalidations for past-@head transaction.
# T1 thus will _not_ process invalidations for that next transaction when
# opening zconn _next_ time. The next opened zconn will thus see _stale_ data.
._cache.invalidate(invalidated)
The program simulates two clients: one (T2) constantly modifies two integer
objects preserving invariant that their values stay equal. The other client
(T1) constantly opens the database and verifies the invariant. T1 forces access
to one of the object to always go through loading from the database, and this
way if live cache becomes stale the bug is observed as invariant breakage.
Here is example failure:
$ taskset -c 1,2 ./zopenrace.py
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "./zopenrace.py", line 136, in T1
t1()
File "./zopenrace.py", line 130, in t1
raise AssertionError("t1: obj1.i (%d) != obj2.i (%d)" % (i1, i2))
AssertionError: t1: obj1.i (147) != obj2.i (146)
Traceback (most recent call last):
File "./zopenrace.py", line 179, in <module>
main()
File "./zopenrace.py", line 174, in main
raise AssertionError('FAIL')
AssertionError: FAIL
NOTE ZODB4 and ZODB3 do not have this particular open vs invalidation race.
[1] https://github.com/zopefoundation/ZODB/blob/5.5.1-29-g0b3db5aee/src/ZODB/Connection.py#L734-L742
[2] https://github.com/zopefoundation/ZODB/blob/5.5.1-29-g0b3db5aee/src/ZODB/mvccadapter.py#L130-L139
"""
from __future__ import print_function
from ZODB import DB
from ZODB.MappingStorage import MappingStorage
import transaction
from persistent import Persistent
# don't depend on pygolang
# ( but it is more easy and structured with sync.WorkGroup
# https://pypi.org/project/pygolang/#concurrency )
#from golang import sync, context
import threading
def go(f, *argv, **kw):
t = threading.Thread(target=f, args=argv, kwargs=kw)
t.start()
return t
# PInt is persistent integer.
class PInt(Persistent):
def __init__(self, i):
self.i = i
def main():
zstor = MappingStorage()
db = DB(zstor)
# init initializes the database with two integer objects - obj1/obj2 that are set to 0.
def init():
transaction.begin()
zconn = db.open()
root = zconn.root()
root['obj1'] = PInt(0)
root['obj2'] = PInt(0)
transaction.commit()
zconn.close()
okv = [False, False]
# T1 accesses obj1/obj2 in a loop and verifies that obj1.i == obj2.i
#
# access to obj1 is organized to always trigger loading from zstor.
# access to obj2 goes through zconn cache and so verifies whether the cache is not stale.
def T1(N):
def t1():
transaction.begin()
zconn = db.open()
root = zconn.root()
obj1 = root['obj1']
obj2 = root['obj2']
# obj1 - reload it from zstor
# obj2 - get it from zconn cache
obj1._p_invalidate()
# both objects must have the same values
i1 = obj1.i
i2 = obj2.i
if i1 != i2:
raise AssertionError("T1: obj1.i (%d) != obj2.i (%d)" % (i1, i2))
transaction.abort() # we did not changed anything; also fails with commit
zconn.close()
for i in range(N):
#print('T1.%d' % i)
t1()
okv[0] = True
# T2 changes obj1/obj2 in a loop by doing `objX.i += 1`.
#
# Since both objects start from 0, the invariant that `obj1.i == obj2.i` is always preserved.
def T2(N):
def t2():
transaction.begin()
zconn = db.open()
root = zconn.root()
obj1 = root['obj1']
obj2 = root['obj2']
obj1.i += 1
obj2.i += 1
assert obj1.i == obj2.i
transaction.commit()
zconn.close()
for i in range(N):
#print('T2.%d' % i)
t2()
okv[1] = True
# run T1 and T2 concurrently. As of 20191210, due to race condition in
# Connection.open, it triggers the bug where T1 sees stale obj2 with obj1.i != obj2.i
init()
N = 1000
t1 = go(T1, N)
t2 = go(T2, N)
t1.join()
t2.join()
if not all(okv):
raise AssertionError('FAIL')
print('OK')
if __name__ == '__main__':
main()
```
Thanks beforehand,
Kirill
/cc @jimfulton
P.S. It would be nice to provide `ZODB.Connection.at()` explicitly similarly to https://godoc.org/lab.nexedi.com/kirr/neo/go/zodb#Connection | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/ZODB/tests/testConnection.py::InvalidationTests::test_mvccadapterNewTransactionVsInvalidations"
] | [
"src/ZODB/FileStorage/tests.py::test_suite",
"src/ZODB/tests/testConnection.py::ConnectionDotAdd::testCommit",
"src/ZODB/tests/testConnection.py::ConnectionDotAdd::testModifyOnGetstate",
"src/ZODB/tests/testConnection.py::ConnectionDotAdd::testResetOnAbort",
"src/ZODB/tests/testConnection.py::ConnectionDotAdd::testResetOnTpcAbort",
"src/ZODB/tests/testConnection.py::ConnectionDotAdd::testTpcAbortAfterCommit",
"src/ZODB/tests/testConnection.py::ConnectionDotAdd::testUnusedAddWorks",
"src/ZODB/tests/testConnection.py::ConnectionDotAdd::test__resetCacheResetsReader",
"src/ZODB/tests/testConnection.py::ConnectionDotAdd::test_add",
"src/ZODB/tests/testConnection.py::SetstateErrorLoggingTests::test_closed_connection_wont_setstate",
"src/ZODB/tests/testConnection.py::EstimatedSizeTests::test_cache_garbage_collection",
"src/ZODB/tests/testConnection.py::EstimatedSizeTests::test_cache_garbage_collection_shrinking_object",
"src/ZODB/tests/testConnection.py::EstimatedSizeTests::test_configuration",
"src/ZODB/tests/testConnection.py::EstimatedSizeTests::test_size_set_on_load",
"src/ZODB/tests/testConnection.py::EstimatedSizeTests::test_size_set_on_write_commit",
"src/ZODB/tests/testConnection.py::EstimatedSizeTests::test_size_set_on_write_savepoint",
"src/ZODB/tests/testConnection.py::TestConnection::test_connection_interface",
"src/ZODB/tests/testConnection.py::TestConnection::test_explicit_transactions_no_newTransactuon_on_afterCompletion",
"src/ZODB/tests/testConnection.py::TestConnection::test_storage_afterCompletionCalled",
"src/ZODB/tests/testConnection.py::test_suite",
"src/ZODB/tests/testmvcc.py::test_suite"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2019-12-13T19:48:13Z" | zpl-2.1 |
|
zopefoundation__ZODB-355 | diff --git a/CHANGES.rst b/CHANGES.rst
index f833ad5e..99fb8070 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -5,6 +5,12 @@
5.6.1 (unreleased)
==================
+- Readd transaction size information to ``fsdump`` output;
+ adapt `fsstats` to ``fsdump``'s exchanged order for ``size`` and ``class``
+ information in data records;
+ (fixes `#354 <https://github.com/zopefoundation/ZODB/issues/354>_).
+ Make ``fsdump`` callable via Python's ``-m`` command line option.
+
- Fix UnboundLocalError when running fsoids.py script.
See `issue 285 <https://github.com/zopefoundation/ZODB/issues/285>`_.
diff --git a/src/ZODB/FileStorage/fsdump.py b/src/ZODB/FileStorage/fsdump.py
index fe7b7868..853b730d 100644
--- a/src/ZODB/FileStorage/fsdump.py
+++ b/src/ZODB/FileStorage/fsdump.py
@@ -23,12 +23,14 @@ from ZODB.utils import u64, get_pickle_metadata
def fsdump(path, file=None, with_offset=1):
iter = FileIterator(path)
for i, trans in enumerate(iter):
+ size = trans._tend - trans._tpos
if with_offset:
- print(("Trans #%05d tid=%016x time=%s offset=%d" %
- (i, u64(trans.tid), TimeStamp(trans.tid), trans._pos)), file=file)
+ print(("Trans #%05d tid=%016x size=%d time=%s offset=%d" %
+ (i, u64(trans.tid), size,
+ TimeStamp(trans.tid), trans._pos)), file=file)
else:
- print(("Trans #%05d tid=%016x time=%s" %
- (i, u64(trans.tid), TimeStamp(trans.tid))), file=file)
+ print(("Trans #%05d tid=%016x size=%d time=%s" %
+ (i, u64(trans.tid), size, TimeStamp(trans.tid))), file=file)
print((" status=%r user=%r description=%r" %
(trans.status, trans.user, trans.description)), file=file)
@@ -122,3 +124,7 @@ class Dumper(object):
def main():
import sys
fsdump(sys.argv[1])
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/ZODB/scripts/fsstats.py b/src/ZODB/scripts/fsstats.py
index 4c767a66..00379477 100755
--- a/src/ZODB/scripts/fsstats.py
+++ b/src/ZODB/scripts/fsstats.py
@@ -7,7 +7,7 @@ import six
from six.moves import filter
rx_txn = re.compile("tid=([0-9a-f]+).*size=(\d+)")
-rx_data = re.compile("oid=([0-9a-f]+) class=(\S+) size=(\d+)")
+rx_data = re.compile("oid=([0-9a-f]+) size=(\d+) class=(\S+)")
def sort_byhsize(seq, reverse=False):
L = [(v.size(), k, v) for k, v in seq]
@@ -31,8 +31,7 @@ class Histogram(dict):
def median(self):
# close enough?
n = self.size() / 2
- L = self.keys()
- L.sort()
+ L = sorted(self.keys())
L.reverse()
while 1:
k = L.pop()
@@ -50,11 +49,14 @@ class Histogram(dict):
return mode
def make_bins(self, binsize):
- maxkey = max(six.iterkeys(self))
+ try:
+ maxkey = max(six.iterkeys(self))
+ except ValueError:
+ maxkey = 0
self.binsize = binsize
- self.bins = [0] * (1 + maxkey / binsize)
+ self.bins = [0] * (1 + maxkey // binsize)
for k, v in six.iteritems(self):
- b = k / binsize
+ b = k // binsize
self.bins[b] += v
def report(self, name, binsize=50, usebins=False, gaps=True, skip=True):
@@ -88,7 +90,7 @@ class Histogram(dict):
cum += n
pc = 100 * cum / tot
print("%6d %6d %3d%% %3d%% %s" % (
- i * binsize, n, p, pc, "*" * (n / dot)))
+ i * binsize, n, p, pc, "*" * (n // dot)))
print()
def class_detail(class_size):
@@ -104,7 +106,7 @@ def class_detail(class_size):
# per class details
for klass, h in sort_byhsize(six.iteritems(class_size), reverse=True):
h.make_bins(50)
- if len(filter(None, h.bins)) == 1:
+ if len(tuple(filter(None, h.bins))) == 1:
continue
h.report("Object size for %s" % klass, usebins=True)
@@ -138,7 +140,7 @@ def main(path=None):
objects = 0
tid = None
- f = open(path, "rb")
+ f = open(path, "r")
for i, line in enumerate(f):
if MAX and i > MAX:
break
@@ -146,7 +148,7 @@ def main(path=None):
m = rx_data.search(line)
if not m:
continue
- oid, klass, size = m.groups()
+ oid, size, klass = m.groups()
size = int(size)
obj_size.add(size)
@@ -178,6 +180,8 @@ def main(path=None):
objects = 0
txn_bytes.add(size)
+ if objects:
+ txn_objects.add(objects)
f.close()
print("Summary: %d txns, %d objects, %d revisions" % (
| zopefoundation/ZODB | 1fb097b41cae4ca863c8a3664414c9ec0e204393 | diff --git a/src/ZODB/scripts/tests/test_fsdump_fsstats.py b/src/ZODB/scripts/tests/test_fsdump_fsstats.py
new file mode 100644
index 00000000..daeee43a
--- /dev/null
+++ b/src/ZODB/scripts/tests/test_fsdump_fsstats.py
@@ -0,0 +1,62 @@
+##############################################################################
+#
+# Copyright (c) 2021 Zope Foundation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+
+from ZODB import DB
+from ZODB.scripts.fsstats import rx_data
+from ZODB.scripts.fsstats import rx_txn
+from ZODB.tests.util import TestCase
+from ZODB.tests.util import run_module_as_script
+
+
+class FsdumpFsstatsTests(TestCase):
+ def setUp(self):
+ super(FsdumpFsstatsTests, self).setUp()
+ # create (empty) storage ``data.fs``
+ DB("data.fs").close()
+
+ def test_fsdump(self):
+ run_module_as_script("ZODB.FileStorage.fsdump", ["data.fs"])
+ # verify that ``fsstats`` will understand the output
+ with open("stdout") as f:
+ tno = obno = 0
+ for li in f:
+ if li.startswith(" data"):
+ m = rx_data.search(li)
+ if m is None:
+ continue
+ oid, size, klass = m.groups()
+ int(size)
+ obno += 1
+ elif li.startswith("Trans"):
+ m = rx_txn.search(li)
+ if not m:
+ continue
+ tid, size = m.groups()
+ size = int(size)
+ tno += 1
+ self.assertEqual(tno, 1)
+ self.assertEqual(obno, 1)
+
+ def test_fsstats(self):
+ # The ``fsstats`` output is complex
+ # currently, we just check the first (summary) line
+ run_module_as_script("ZODB.FileStorage.fsdump", ["data.fs"],
+ "data.dmp")
+ run_module_as_script("ZODB.scripts.fsstats", ["data.dmp"])
+ with open("stdout") as f:
+ self.assertEqual(f.readline().strip(),
+ "Summary: 1 txns, 1 objects, 1 revisions")
+
+
+
diff --git a/src/ZODB/tests/util.py b/src/ZODB/tests/util.py
index f03e0079..99c35d08 100644
--- a/src/ZODB/tests/util.py
+++ b/src/ZODB/tests/util.py
@@ -16,9 +16,12 @@
from ZODB.MappingStorage import DB
import atexit
+import doctest
import os
+import pdb
import persistent
import re
+import runpy
import sys
import tempfile
import time
@@ -377,3 +380,28 @@ def with_high_concurrency(f):
restore()
return _
+
+
+def run_module_as_script(mod, args, stdout="stdout", stderr="stderr"):
+ """run module *mod* as script with arguments *arg*.
+
+ stdout and stderr are redirected to files given by the
+ correcponding parameters.
+
+ The function is usually called in a ``setUp/tearDown`` frame
+ which will remove the created files.
+ """
+ sargv, sout, serr = sys.argv, sys.stdout, sys.stderr
+ s_set_trace = pdb.set_trace
+ try:
+ sys.argv = [sargv[0]] + args
+ sys.stdout = open(stdout, "w")
+ sys.stderr = open(stderr, "w")
+ # to allow debugging
+ pdb.set_trace = doctest._OutputRedirectingPdb(sout)
+ runpy.run_module(mod, run_name="__main__", alter_sys=True)
+ finally:
+ sys.stdout.close()
+ sys.stderr.close()
+ pdb.set_trace = s_set_trace
+ sys.argv, sys.stdout, sys.stderr = sargv, sout, serr
| `fsstats` no longer matches output of `fsdump`
ZODB==5.6.0
`scripts.fsstats` is supposed to derive statistics from the output of `FileStorage.fsdump`. However, it no longer understands this output.
Transaction records produced by `fsdump` look like
```
Trans #00000 tid=038e1d5f01b145cc time=2011-05-05 07:59:00.396673 offset=70
status='p' user='' description='Created Zope Application\n\nAdded temp_folder'
```
and data records like
```
data #00000 oid=0000000000000006 size=141 class=Products.ZODBMountPoint.MountedObject.MountedObject
```
but `fsstats` tries to match transaction records with re `"tid=([0-9a-f]+).*size=(\d+)"` (i.e. it expects `size` information after `tid`) and data records with re `"oid=([0-9a-f]+) class=(\S+) size=(\d+)"` (i.e. it expects `size` and `class` interchanged).
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/ZODB/scripts/tests/test_fsdump_fsstats.py::FsdumpFsstatsTests::test_fsdump",
"src/ZODB/scripts/tests/test_fsdump_fsstats.py::FsdumpFsstatsTests::test_fsstats"
] | [
"src/ZODB/tests/util.py::AAAA_Test_Runner_Hack::testNothing"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2021-10-03T11:08:53Z" | zpl-2.1 |
|
zopefoundation__Zope-1003 | diff --git a/CHANGES.rst b/CHANGES.rst
index 89abf2fc4..4f9d5e270 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -11,6 +11,9 @@ https://github.com/zopefoundation/Zope/blob/4.x/CHANGES.rst
5.4 (unreleased)
----------------
+- Enable WebDAV PUT factories to change a newly created object's ID
+ (`#997 <https://github.com/zopefoundation/Zope/issues/997>`_)
+
- Fix potential race condition in ``App.version_txt.getZopeVersion``
(`#999 <https://github.com/zopefoundation/Zope/issues/999>`_)
diff --git a/src/webdav/NullResource.py b/src/webdav/NullResource.py
index 97f53af06..331cddc80 100644
--- a/src/webdav/NullResource.py
+++ b/src/webdav/NullResource.py
@@ -184,6 +184,9 @@ class NullResource(Persistent, Implicit, Resource):
(ob.__class__, repr(parent), sys.exc_info()[1],)
raise Unauthorized(sMsg)
+ # A PUT factory may have changed the object's ID
+ name = ob.getId() or name
+
# Delegate actual PUT handling to the new object,
# SDS: But just *after* it has been stored.
self.__parent__._setObject(name, ob)
| zopefoundation/Zope | ba9f5ae81378f0eeeecb0463caf8434b1467ef27 | diff --git a/src/webdav/tests/testPUT_factory.py b/src/webdav/tests/testPUT_factory.py
index 36597f19e..79c824569 100644
--- a/src/webdav/tests/testPUT_factory.py
+++ b/src/webdav/tests/testPUT_factory.py
@@ -90,3 +90,20 @@ class TestPUTFactory(unittest.TestCase):
'PUT factory should not acquire content')
# check for the newly created file
self.assertEqual(str(self.app.A.B.a), 'bar')
+
+ def testPUT_factory_changes_name(self):
+ # A custom PUT factory may want to change the object ID,
+ # for example to remove file name extensions.
+ from OFS.Image import File
+
+ def custom_put_factory(name, typ, body):
+ new_name = 'newname'
+ if not isinstance(body, bytes):
+ body = body.encode('UTF-8')
+ return File(new_name, '', body, content_type=typ)
+ self.app.folder.PUT_factory = custom_put_factory
+
+ request = self.app.REQUEST
+ put = request.traverse('/folder/doc')
+ put(request, request.RESPONSE)
+ self.assertTrue('newname' in self.folder.objectIds())
| Webdav _default_PUT_factory not working as expected
### What I did:
After a Zope update (possibly to 5.3 but it could be an earlier one) certain files do not get converted to Zope objects as expected when uploaded via webdav.
### What I expect to happen:
- Files with the extensions 'html' or 'pt' should result in a Page Template object
- Image files (jpeg or png) should result in an Image object.
### What actually happened:
- files with the extension 'dtml' result in DTML Document objects
- all other files result in File objects.
### Where's the problem
When I upload a file, the type is always 'application/octet-stream'. So that is problably what's changed, hence the new, different behaviour.
As a DTML Document is recognized from its file extension, this one still works.
### Workaround
As a workaround other files could also be recognized from their file extension.
### What version of Python and Zope/Addons I am using:
- Operating Systems:
- MacOS Catalina
- FreeBSD 12.2
- Python 3.8.6
- Zope 5.3
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/webdav/tests/testPUT_factory.py::TestPUTFactory::testPUT_factory_changes_name"
] | [
"src/webdav/tests/testPUT_factory.py::TestPUTFactory::testCollector2261",
"src/webdav/tests/testPUT_factory.py::TestPUTFactory::testInsideOutVirtualHosting",
"src/webdav/tests/testPUT_factory.py::TestPUTFactory::testNoVirtualHosting",
"src/webdav/tests/testPUT_factory.py::TestPUTFactory::testSimpleVirtualHosting",
"src/webdav/tests/testPUT_factory.py::TestPUTFactory::testSubfolderInsideOutVirtualHosting",
"src/webdav/tests/testPUT_factory.py::TestPUTFactory::testSubfolderVirtualHosting"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2022-01-06T12:20:45Z" | zpl-2.1 |
|
zopefoundation__Zope-1135 | diff --git a/CHANGES.rst b/CHANGES.rst
index 5afe97abc..e99b7b40f 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -20,6 +20,15 @@ https://github.com/zopefoundation/Zope/blob/4.x/CHANGES.rst
- Update to newest compatible versions of dependencies.
+- Make ``mapply`` ``__signature__`` aware.
+ This allows to publish methods decorated via a decorator
+ which sets ``__signature__`` on the wrapper to specify
+ the signature to use.
+ For details, see
+ `#1134 <https://github.com/zopefoundation/Zope/issues/1134>`_.
+ Note: ``mapply`` still does not support keyword only, var positional
+ and var keyword parameters.
+
5.8.3 (2023-06-15)
------------------
diff --git a/src/ZPublisher/mapply.py b/src/ZPublisher/mapply.py
index 19deeacf4..d2259adce 100644
--- a/src/ZPublisher/mapply.py
+++ b/src/ZPublisher/mapply.py
@@ -12,6 +12,8 @@
##############################################################################
"""Provide an apply-like facility that works with any mapping object
"""
+from inspect import getfullargspec
+
import zope.publisher.publish
@@ -50,9 +52,20 @@ def mapply(object, positional=(), keyword={},
if maybe:
return object
raise
- code = f.__code__
- defaults = f.__defaults__
- names = code.co_varnames[count:code.co_argcount]
+ if hasattr(f, "__signature__"):
+ # The function has specified the signature to use
+ # (likely via a decorator)
+ # We use ``getfullargspec`` because it packages
+ # the signature information in the way we need it here.
+ # Should the function get deprecated, we could do the
+ # packaging ourselves
+ argspec = getfullargspec(f)
+ defaults = argspec.defaults
+ names = argspec.args[count:]
+ else:
+ code = f.__code__
+ defaults = f.__defaults__
+ names = code.co_varnames[count:code.co_argcount]
nargs = len(names)
if positional:
| zopefoundation/Zope | b0bb1084379c5c693f9277b3d0ce044cea849dda | diff --git a/src/ZPublisher/tests/test_mapply.py b/src/ZPublisher/tests/test_mapply.py
index d0cc4eee3..590df65db 100644
--- a/src/ZPublisher/tests/test_mapply.py
+++ b/src/ZPublisher/tests/test_mapply.py
@@ -90,3 +90,17 @@ class MapplyTests(unittest.TestCase):
ob = NoCallButAcquisition().__of__(Root())
self.assertRaises(TypeError, mapply, ob, (), {})
+
+ def testFunctionWithSignature(self):
+ from inspect import Parameter
+ from inspect import Signature
+
+ def f(*args, **kw):
+ return args, kw
+
+ f.__signature__ = Signature(
+ (Parameter("a", Parameter.POSITIONAL_OR_KEYWORD),
+ Parameter("b", Parameter.POSITIONAL_OR_KEYWORD, default="b")))
+
+ self.assertEqual(mapply(f, ("a",), {}), (("a", "b"), {}))
+ self.assertEqual(mapply(f, (), {"a": "A", "b": "B"}), (("A", "B"), {}))
| Feature request: support Python 3 style signature declarations in `ZPublisher.mapply.mapply`
Python 3 has introduced the `__signature__` attribute to inform a caller about the signature of a callable. This significantly simplifies the implementation of signature preserving decorators.
Unfortunately, `ZPublisher.mapply.mapply` does not yet support `__signature__`.
As a consequence, methods decorated via `decorator 5+` decorators cannot be published when they have parameters
(earlier `decorator` versions implement decorators in a much more complicated Python 2 and `mapply` compatible way).
Extend `Zpublisher.mapply.mapply` to support `__signature__`. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/ZPublisher/tests/test_mapply.py::MapplyTests::testFunctionWithSignature"
] | [
"src/ZPublisher/tests/test_mapply.py::MapplyTests::testClass",
"src/ZPublisher/tests/test_mapply.py::MapplyTests::testMethod",
"src/ZPublisher/tests/test_mapply.py::MapplyTests::testNoCallButAcquisition",
"src/ZPublisher/tests/test_mapply.py::MapplyTests::testObjectWithCall",
"src/ZPublisher/tests/test_mapply.py::MapplyTests::testUncallableObject"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2023-06-17T09:43:12Z" | zpl-2.1 |
|
zopefoundation__Zope-1142 | diff --git a/CHANGES.rst b/CHANGES.rst
index e99b7b40f..c4b17af07 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -29,6 +29,9 @@ https://github.com/zopefoundation/Zope/blob/4.x/CHANGES.rst
Note: ``mapply`` still does not support keyword only, var positional
and var keyword parameters.
+- Make Zope's parameters for denial of service protection configurable
+ `#1141 <https://github.com/zopefoundation/Zope/issues/1141>_`.
+
5.8.3 (2023-06-15)
------------------
diff --git a/src/ZPublisher/HTTPRequest.py b/src/ZPublisher/HTTPRequest.py
index 39239ae1a..7983898e1 100644
--- a/src/ZPublisher/HTTPRequest.py
+++ b/src/ZPublisher/HTTPRequest.py
@@ -53,9 +53,9 @@ from .cookie import getCookieValuePolicy
# DOS attack protection -- limiting the amount of memory for forms
# probably should become configurable
-FORM_MEMORY_LIMIT = 2 ** 20 # memory limit for forms
-FORM_DISK_LIMIT = 2 ** 30 # disk limit for forms
-FORM_MEMFILE_LIMIT = 4000 # limit for `BytesIO` -> temporary file switch
+FORM_MEMORY_LIMIT = 2 ** 20 # memory limit for forms
+FORM_DISK_LIMIT = 2 ** 30 # disk limit for forms
+FORM_MEMFILE_LIMIT = 2 ** 12 # limit for `BytesIO` -> temporary file switch
# This may get overwritten during configuration
@@ -1354,6 +1354,8 @@ def sane_environment(env):
class ValueDescriptor:
"""(non data) descriptor to compute `value` from `file`."""
+ VALUE_LIMIT = FORM_MEMORY_LIMIT
+
def __get__(self, inst, owner=None):
if inst is None:
return self
@@ -1364,6 +1366,8 @@ class ValueDescriptor:
fpos = None
try:
v = file.read()
+ if self.VALUE_LIMIT and file.read(1):
+ raise BadRequest("data exceeds memory limit")
if fpos is None:
# store the value as we cannot read it again
inst.value = v
diff --git a/src/Zope2/Startup/handlers.py b/src/Zope2/Startup/handlers.py
index 7369369bf..35b4a4f66 100644
--- a/src/Zope2/Startup/handlers.py
+++ b/src/Zope2/Startup/handlers.py
@@ -90,3 +90,11 @@ def handleWSGIConfig(cfg, multihandler):
if not name.startswith('_'):
handlers[name] = value
return multihandler(handlers)
+
+
+def dos_protection(cfg):
+ if cfg is None:
+ return
+ from ZPublisher import HTTPRequest
+ for attr in cfg.getSectionAttributes():
+ setattr(HTTPRequest, attr.upper(), getattr(cfg, attr))
diff --git a/src/Zope2/Startup/wsgischema.xml b/src/Zope2/Startup/wsgischema.xml
index 1a536fc18..d593c36da 100644
--- a/src/Zope2/Startup/wsgischema.xml
+++ b/src/Zope2/Startup/wsgischema.xml
@@ -80,6 +80,34 @@
</sectiontype>
+ <sectiontype name="dos_protection">
+
+ <description>Defines parameters for DOS attack protection</description>
+
+ <key name="form-memory-limit" datatype="byte-size" default="1MB">
+ <description>
+ The maximum size for each part in a multipart post request,
+ for the complete body in an urlencoded post request
+ and for the complete request body when accessed as bytes
+ (rather than a file).
+ </description>
+ </key>
+
+ <key name="form-disk-limit" datatype="byte-size" default="1GB">
+ <description>
+ The maximum size of a POST request body
+ </description>
+ </key>
+
+ <key name="form-memfile-limit" datatype="byte-size" default="4KB">
+ <description>
+ The value of form variables of type file with larger size
+ are stored on disk rather than in memory.
+ </description>
+ </key>
+ </sectiontype>
+
+
<!-- end of type definitions -->
<!-- schema begins -->
@@ -385,4 +413,7 @@
<metadefault>off</metadefault>
</key>
+ <section type="dos_protection" handler="dos_protection"
+ name="*" attribute="dos_protection" />
+
</schema>
diff --git a/src/Zope2/utilities/skel/etc/zope.conf.in b/src/Zope2/utilities/skel/etc/zope.conf.in
index 39c8c8f20..110f621bb 100644
--- a/src/Zope2/utilities/skel/etc/zope.conf.in
+++ b/src/Zope2/utilities/skel/etc/zope.conf.in
@@ -250,3 +250,33 @@ instancehome $INSTANCE
# security-policy-implementation python
# verbose-security on
+<dos_protection>
+#
+# Description:
+# You can use this section to configure Zope's
+# parameters for denial of service attack protection.
+# The examples below document the default values.
+
+# Parameter: form-memory-limit
+# Description:
+# The maximum size for each part in a multipart post request,
+# for the complete body in an urlencoded post request
+# and for the complete request body when accessed as bytes
+# (rather than a file).
+# Example:
+# form-memory-limit 1MB
+
+# Parameter: form-disk-limit
+# Description:
+# The maximum size of a POST request body
+# Example:
+# form-disk-limit 1GB
+
+# Parameter: form-memfile-limit
+# Description:
+# The value of form variables of type file with larger size
+# are stored on disk rather than in memory.
+# Example:
+# form-memfile-limit 4KB
+
+</dos_protection>
| zopefoundation/Zope | 345d656557bfc414f70b92637fef33dde747a97d | diff --git a/src/Zope2/Startup/tests/test_schema.py b/src/Zope2/Startup/tests/test_schema.py
index 6acf3b301..b1b06641f 100644
--- a/src/Zope2/Startup/tests/test_schema.py
+++ b/src/Zope2/Startup/tests/test_schema.py
@@ -190,3 +190,46 @@ class WSGIStartupTestCase(unittest.TestCase):
self.assertFalse(webdav.enable_ms_public_header)
finally:
webdav.enable_ms_public_header = default_setting
+
+ def test_dos_protection(self):
+ from ZPublisher import HTTPRequest
+
+ params = ["FORM_%s_LIMIT" % name
+ for name in ("MEMORY", "DISK", "MEMFILE")]
+ defaults = dict((name, getattr(HTTPRequest, name)) for name in params)
+
+ try:
+ # missing section
+ conf, handler = self.load_config_text("""\
+ instancehome <<INSTANCE_HOME>>
+ """)
+ handleWSGIConfig(None, handler)
+ for name in params:
+ self.assertEqual(getattr(HTTPRequest, name), defaults[name])
+
+ # empty section
+ conf, handler = self.load_config_text("""\
+ instancehome <<INSTANCE_HOME>>
+ <dos_protection />
+ """)
+ handleWSGIConfig(None, handler)
+ for name in params:
+ self.assertEqual(getattr(HTTPRequest, name), defaults[name])
+
+ # configured values
+
+ # empty section
+ conf, handler = self.load_config_text("""\
+ instancehome <<INSTANCE_HOME>>
+ <dos_protection>
+ form-memory-limit 1KB
+ form-disk-limit 1KB
+ form-memfile-limit 1KB
+ </dos_protection>
+ """)
+ handleWSGIConfig(None, handler)
+ for name in params:
+ self.assertEqual(getattr(HTTPRequest, name), 1024)
+ finally:
+ for name in params:
+ setattr(HTTPRequest, name, defaults[name])
| ZPublisher.HTTPRequest.FORM_MEMORY_LIMIT too low
Hello @d-maurer ,
the choosen data limit for FORM_MEMORY_LIMIT now is limited to only 1 Mb;
https://github.com/zopefoundation/Zope/blob/345d656557bfc414f70b92637fef33dde747a97d/src/ZPublisher/HTTPRequest.py#L54C9-L58
This FORM_MEMORY_LIMIT value was introduced here:
https://github.com/zopefoundation/Zope/pull/1094
https://github.com/zopefoundation/Zope/pull/1094/commits/25990c13f15727d14e118f4170c8e266ef24bb1a
Actually 1Mb is quite low if you work e,g, with [pdfmake,js](https://github.com/bpampuch/pdfmake) to generate PDF in the browser:
_FORM_MEMORY_LIMIT = 1Mb blocks PDF generation in the frontend_
![DESY_V22_PDF_Formlimit0](https://github.com/zopefoundation/Zope/assets/29705216/2fa41ea2-6426-45cf-a52b-0224b954eda4)
_FORM_MEMORY_LIMIT "unlimited"_
![DESY_V22_PDF_Formlimit1](https://github.com/zopefoundation/Zope/assets/29705216/5bccb44a-a6a9-4eb5-adc8-6f5714fc112f)
If the value FORM_MEMORY_LIMIT was chosen arbitrarily, I 'd like to suggest setting it a little bit higher, e.g. to 2\*\*22 (=4Mb).
Best regards
f | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/Zope2/Startup/tests/test_schema.py::WSGIStartupTestCase::test_dos_protection"
] | [
"src/Zope2/Startup/tests/test_schema.py::WSGIStartupTestCase::test_automatically_quote_dtml_request_data",
"src/Zope2/Startup/tests/test_schema.py::WSGIStartupTestCase::test_default_zpublisher_encoding",
"src/Zope2/Startup/tests/test_schema.py::WSGIStartupTestCase::test_environment",
"src/Zope2/Startup/tests/test_schema.py::WSGIStartupTestCase::test_load_config_template",
"src/Zope2/Startup/tests/test_schema.py::WSGIStartupTestCase::test_max_conflict_retries_default",
"src/Zope2/Startup/tests/test_schema.py::WSGIStartupTestCase::test_max_conflict_retries_explicit",
"src/Zope2/Startup/tests/test_schema.py::WSGIStartupTestCase::test_ms_public_header",
"src/Zope2/Startup/tests/test_schema.py::WSGIStartupTestCase::test_pid_filename",
"src/Zope2/Startup/tests/test_schema.py::WSGIStartupTestCase::test_webdav_source_port",
"src/Zope2/Startup/tests/test_schema.py::WSGIStartupTestCase::test_zodb_db"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-07-13T08:13:11Z" | zpl-2.1 |
|
zopefoundation__Zope-1156 | diff --git a/CHANGES.rst b/CHANGES.rst
index d9ecaf643..fcd77f56b 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -18,6 +18,9 @@ https://github.com/zopefoundation/Zope/blob/4.x/CHANGES.rst
- Added image dimensions to SVG file properties
`#1146 <https://github.com/zopefoundation/Zope/pull/1146>`_.
+- Fix username not in access log for error requests, see issue
+ `#1155 <https://github.com/zopefoundation/Zope/issues/1155>`_.
+
5.8.4 (2023-09-06)
------------------
diff --git a/src/ZPublisher/WSGIPublisher.py b/src/ZPublisher/WSGIPublisher.py
index 8f992587b..af66908f6 100644
--- a/src/ZPublisher/WSGIPublisher.py
+++ b/src/ZPublisher/WSGIPublisher.py
@@ -387,12 +387,13 @@ def publish_module(environ, start_response,
try:
with load_app(module_info) as new_mod_info:
with transaction_pubevents(request, response):
- response = _publish(request, new_mod_info)
-
- user = getSecurityManager().getUser()
- if user is not None and \
- user.getUserName() != 'Anonymous User':
- environ['REMOTE_USER'] = user.getUserName()
+ try:
+ response = _publish(request, new_mod_info)
+ finally:
+ user = getSecurityManager().getUser()
+ if user is not None and \
+ user.getUserName() != 'Anonymous User':
+ environ['REMOTE_USER'] = user.getUserName()
break
except TransientError:
if request.supports_retry():
| zopefoundation/Zope | a0f70b6806272523f4d9fafb11ab3ffac1638638 | diff --git a/src/ZPublisher/tests/test_WSGIPublisher.py b/src/ZPublisher/tests/test_WSGIPublisher.py
index 88c29ba0b..b624a3ac7 100644
--- a/src/ZPublisher/tests/test_WSGIPublisher.py
+++ b/src/ZPublisher/tests/test_WSGIPublisher.py
@@ -820,6 +820,15 @@ class TestPublishModule(ZopeTestCase):
self._callFUT(environ, start_response, _publish)
self.assertFalse('REMOTE_USER' in environ)
+ def test_set_REMOTE_USER_environ_error(self):
+ environ = self._makeEnviron()
+ start_response = DummyCallable()
+ _publish = DummyCallable()
+ _publish._raise = ValueError()
+ with self.assertRaises(ValueError):
+ self._callFUT(environ, start_response, _publish)
+ self.assertEqual(environ['REMOTE_USER'], user_name)
+
def test_webdav_source_port(self):
from ZPublisher import WSGIPublisher
old_webdav_source_port = WSGIPublisher._WEBDAV_SOURCE_PORT
| Username not in access log for error requests
## BUG/PROBLEM REPORT / FEATURE REQUEST
<!--
Please do not report security-related issues here. Report them by email to [email protected]. The Security Team will contact the relevant maintainer if necessary.
Include tracebacks, screenshots, code of debugging sessions or code that reproduces the issue if possible.
The best reproductions are in plain Zope installations without addons or at least with minimal needed addons installed.
-->
### What I did:
Create a zope instance:
```
mkwsgiinstance -d username_log_repro -u admin:admin
runwsgi ./username_log_repro/etc/zope.ini
# add a `standard_error_message` at root ( this is necessary for error requests to be logged at all in access log - this looks like another independent issue )
curl -d id=standard_error_message 'http://admin:[email protected]:8080/manage_addProduct/OFSP/addDTMLMethod'
```
Make a successful HTTP request and see in the log that username (`admin`) appears
```console
$ curl --silent -o /dev/null http://admin:[email protected]:8080 ; tail -n 1 username_log_repro/var/log/Z4.log
127.0.0.1 - admin [15/Sep/2023:16:13:03 +0200] "GET / HTTP/1.1" 200 2 "-" "curl/7.87.0"
```
Make an error HTTP request, the username field is empty:
```console
$ curl --silent -o /dev/null http://admin:[email protected]:8080/error ; tail -n 1 username_log_repro/var/log/Z4.log
127.0.0.1 - - [15/Sep/2023:16:14:30 +0200] "GET /error HTTP/1.1" 404 229 "-" "curl/7.87.0"
```
<!-- Enter a reproducible description, including preconditions. -->
### What I expect to happen:
The username field should be present even for error requests.
### What actually happened:
The username field is empty, for error requests. This is not only for "404 not found" requests, but also for server side errors.
### What version of Python and Zope/Addons I am using:
This is on current master
<!-- Enter Operating system, Python and Zope versions you are using -->
---
I investigated and found that username is set in `environ` by https://github.com/zopefoundation/Zope/blob/59f68703c249a0a0f5b3b092395709820f221108/src/ZPublisher/WSGIPublisher.py#L388-L395
but this code is not executed if `_publish` gets an exception. I'm making a pull request. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::test_set_REMOTE_USER_environ_error"
] | [
"src/ZPublisher/tests/test_WSGIPublisher.py::WSGIResponseTests::test___str___raises",
"src/ZPublisher/tests/test_WSGIPublisher.py::WSGIResponseTests::test_debugError",
"src/ZPublisher/tests/test_WSGIPublisher.py::WSGIResponseTests::test_exception_calls_unauthorized",
"src/ZPublisher/tests/test_WSGIPublisher.py::WSGIResponseTests::test_finalize_sets_204_on_empty_not_streaming",
"src/ZPublisher/tests/test_WSGIPublisher.py::WSGIResponseTests::test_finalize_sets_204_on_empty_not_streaming_ignores_non_200",
"src/ZPublisher/tests/test_WSGIPublisher.py::WSGIResponseTests::test_finalize_sets_content_length_if_missing",
"src/ZPublisher/tests/test_WSGIPublisher.py::WSGIResponseTests::test_finalize_skips_content_length_if_missing_w_streaming",
"src/ZPublisher/tests/test_WSGIPublisher.py::WSGIResponseTests::test_listHeaders_includes_Date_header",
"src/ZPublisher/tests/test_WSGIPublisher.py::WSGIResponseTests::test_listHeaders_includes_Server_header_w_server_version_set",
"src/ZPublisher/tests/test_WSGIPublisher.py::WSGIResponseTests::test_listHeaders_skips_Server_header_wo_server_version_set",
"src/ZPublisher/tests/test_WSGIPublisher.py::WSGIResponseTests::test_setBody_IStreamIterator",
"src/ZPublisher/tests/test_WSGIPublisher.py::WSGIResponseTests::test_setBody_IUnboundStreamIterator",
"src/ZPublisher/tests/test_WSGIPublisher.py::WSGIResponseTests::test_setBody_w_locking",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublish::test_w_REMOTE_USER",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublish::test_wo_REMOTE_USER",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::testCustomExceptionViewBadRequest",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::testCustomExceptionViewConflictErrorHandling",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::testCustomExceptionViewForbidden",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::testCustomExceptionViewInternalError",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::testCustomExceptionViewNotFound",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::testCustomExceptionViewUnauthorized",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::testCustomExceptionViewZTKNotFound",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::testDebugExceptionsBypassesExceptionResponse",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::testHandleErrorsFalseBypassesExceptionResponse",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::testRedirectExceptionView",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::test_calls_setDefaultSkin",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::test_handle_ConflictError",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::test_publish_can_return_new_response",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::test_publish_returns_data_witten_to_response_before_body",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::test_raises_redirect",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::test_raises_unauthorized",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::test_request_closed",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::test_response_body_is_file",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::test_response_is_stream",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::test_response_is_unboundstream",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::test_set_REMOTE_USER_environ",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::test_stream_file_wrapper",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::test_stream_file_wrapper_without_read",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::test_unboundstream_file_wrapper",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::test_upgrades_ztk_not_found",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestPublishModule::test_webdav_source_port",
"src/ZPublisher/tests/test_WSGIPublisher.py::ExcViewCreatedTests::testNoStandardErrorMessage",
"src/ZPublisher/tests/test_WSGIPublisher.py::ExcViewCreatedTests::testWithEmptyErrorMessage",
"src/ZPublisher/tests/test_WSGIPublisher.py::ExcViewCreatedTests::testWithStandardErrorMessage",
"src/ZPublisher/tests/test_WSGIPublisher.py::WSGIPublisherTests::test_can_handle_non_ascii_URLs",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestLoadApp::test_no_second_transaction_is_created_if_closed",
"src/ZPublisher/tests/test_WSGIPublisher.py::TestLoadApp::test_open_transaction_is_aborted"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2023-09-15T14:28:01Z" | zpl-2.1 |
|
zopefoundation__Zope-1172 | diff --git a/CHANGES.rst b/CHANGES.rst
index 432f245de..2aa73244f 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -16,6 +16,9 @@ https://github.com/zopefoundation/Zope/blob/4.x/CHANGES.rst
- Update to newest compatible versions of dependencies.
+- Honor a request's ``Content-Length``
+ (`#1171 <https://github.com/zopefoundation/Zope/issues/1171>`_).
+
5.8.6 (2023-10-04)
------------------
diff --git a/src/ZPublisher/HTTPRequest.py b/src/ZPublisher/HTTPRequest.py
index 20421a14b..947a9a88e 100644
--- a/src/ZPublisher/HTTPRequest.py
+++ b/src/ZPublisher/HTTPRequest.py
@@ -1427,9 +1427,17 @@ class ZopeFieldStorage(ValueAccessor):
VALUE_LIMIT = Global("FORM_MEMORY_LIMIT")
def __init__(self, fp, environ):
- self.file = fp
method = environ.get("REQUEST_METHOD", "GET").upper()
url_qs = environ.get("QUERY_STRING", "")
+ content_length = environ.get("CONTENT_LENGTH")
+ if content_length:
+ try:
+ fp.tell()
+ except Exception:
+ # potentially not preprocessed by the WSGI server
+ # enforce ``Content-Length`` specified body length limit
+ fp = LimitedFileReader(fp, int(content_length))
+ self.file = fp
post_qs = ""
hl = []
content_type = environ.get("CONTENT_TYPE",
@@ -1493,6 +1501,53 @@ class ZopeFieldStorage(ValueAccessor):
add_field(field)
+class LimitedFileReader:
+ """File wrapper emulating EOF."""
+
+ # attributes to be delegated to the file
+ DELEGATE = set(["close", "closed", "fileno", "mode", "name"])
+
+ def __init__(self, fp, limit):
+ """emulate EOF after *limit* bytes have been read.
+
+ *fp* is a binary file like object without ``seek`` support.
+ """
+ self.fp = fp
+ assert limit >= 0
+ self.limit = limit
+
+ def _enforce_limit(self, size):
+ limit = self.limit
+ return limit if size is None or size < 0 else min(size, limit)
+
+ def read(self, size=-1):
+ data = self.fp.read(self._enforce_limit(size))
+ self.limit -= len(data)
+ return data
+
+ def readline(self, size=-1):
+ data = self.fp.readline(self._enforce_limit(size))
+ self.limit -= len(data)
+ return data
+
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ data = self.readline()
+ if not data:
+ raise StopIteration()
+ return data
+
+ def __del__(self):
+ return self.fp.__del__()
+
+ def __getattr__(self, attr):
+ if attr not in self.DELEGATE:
+ raise AttributeError(attr)
+ return getattr(self.fp, attr)
+
+
def _mp_charset(part):
"""the charset of *part*."""
content_type = part.headers.get("Content-Type", "")
| zopefoundation/Zope | c070668ea18c585c55784e40c1ef68851cfbd011 | diff --git a/src/ZPublisher/tests/testHTTPRequest.py b/src/ZPublisher/tests/testHTTPRequest.py
index d7fe18e4d..0dafba669 100644
--- a/src/ZPublisher/tests/testHTTPRequest.py
+++ b/src/ZPublisher/tests/testHTTPRequest.py
@@ -31,6 +31,7 @@ from zope.publisher.interfaces.http import IHTTPRequest
from zope.testing.cleanup import cleanUp
from ZPublisher.HTTPRequest import BadRequest
from ZPublisher.HTTPRequest import FileUpload
+from ZPublisher.HTTPRequest import LimitedFileReader
from ZPublisher.HTTPRequest import search_type
from ZPublisher.interfaces import IXmlrpcChecker
from ZPublisher.tests.testBaseRequest import TestRequestViewsBase
@@ -1514,6 +1515,15 @@ class HTTPRequestTests(unittest.TestCase, HTTPRequestFactoryMixin):
self.assertEqual(req["x"], "äöü")
self.assertEqual(req["y"], "äöü")
+ def test_content_length_limitation(self):
+ body = b"123abc"
+ env = self._makePostEnviron(body)
+ env["CONTENT_TYPE"] = "application/octed-stream"
+ env["CONTENT_LENGTH"] = "3"
+ req = self._makeOne(_Unseekable(BytesIO(body)), env)
+ req.processInputs()
+ self.assertEqual(req["BODY"], b"123")
+
class TestHTTPRequestZope3Views(TestRequestViewsBase):
@@ -1570,6 +1580,48 @@ class TestSearchType(unittest.TestCase):
self.check("abc:a-_0b", ":a-_0b")
+class TestLimitedFileReader(unittest.TestCase):
+ def test_enforce_limit(self):
+ f = LimitedFileReader(BytesIO(), 10)
+ enforce = f._enforce_limit
+ self.assertEqual(enforce(None), 10)
+ self.assertEqual(enforce(-1), 10)
+ self.assertEqual(enforce(20), 10)
+ self.assertEqual(enforce(5), 5)
+
+ def test_read(self):
+ f = LimitedFileReader(BytesIO(b"123\n567\n901\n"), 10)
+ self.assertEqual(len(f.read()), 10)
+ self.assertEqual(len(f.read()), 0)
+ f = LimitedFileReader(BytesIO(b"123\n567\n901\n"), 10)
+ self.assertEqual(len(f.read(8)), 8)
+ self.assertEqual(len(f.read(3)), 2)
+ self.assertEqual(len(f.read(3)), 0)
+
+ def test_readline(self):
+ f = LimitedFileReader(BytesIO(b"123\n567\n901\n"), 10)
+ self.assertEqual(f.readline(), b"123\n")
+ self.assertEqual(f.readline(), b"567\n")
+ self.assertEqual(f.readline(), b"90")
+ self.assertEqual(f.readline(), b"")
+ f = LimitedFileReader(BytesIO(b"123\n567\n901\n"), 10)
+ self.assertEqual(f.readline(1), b"1")
+
+ def test_iteration(self):
+ f = LimitedFileReader(BytesIO(b"123\n567\n901\n"), 10)
+ self.assertEqual(list(f), [b"123\n", b"567\n", b"90"])
+
+ def test_del(self):
+ f = LimitedFileReader(BytesIO(b"123\n567\n901\n"), 10)
+ del f
+
+ def test_delegation(self):
+ f = LimitedFileReader(BytesIO(b"123\n567\n901\n"), 10)
+ with self.assertRaises(AttributeError):
+ f.write
+ f.close()
+
+
class _Unseekable:
"""Auxiliary class emulating an unseekable file like object"""
def __init__(self, file):
| Zope 5.8.1 breaks using `wsgiref`
### What I did:
I am using Python's stdlib `wsgiref` in selenium tests to start a simple WSGI server.
### What I expect to happen:
Using `wsgiref` should be possible.
### What actually happened:
`wsgiref` uses a `socket` as `stdin` for the WSGI environment.
And Zope 5.8.1+ uses `read()` to get the data from this socket, the execution is blocked and later on runs into a timeout.
Previous versions (via `cgi` module) called `readline()` on the socket which does not block.
(Sorry I cannot provide a minimal test example as it involves too much custom code. Additionally I did not find an easy way to start a Zope instance using `wsgiref` – the examples for using a different WSGI server in the docs seem to require some preparation.)
### What version of Python and Zope/Addons I am using:
* Zope 5.8.6
* MacOS 13.6
* Python 3.11 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test__str__returns_native_string",
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test_copy",
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test_dict_methods",
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test_dict_special_methods",
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test_eq",
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test_repr",
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test_str",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test___bobo_traverse___raises",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test___str____password_field",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test__authUserPW_non_ascii",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test__authUserPW_simple",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test__authUserPW_with_embedded_colon",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test__str__returns_native_string",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_bytes_converter",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_doesnt_re_clean_environ",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_keeps_only_last_PARENT",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_keeps_preserves__auth",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_preserves_direct_interfaces",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_preserves_request_subclass",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_preserves_response_class",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_updates_method_to_GET",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_close_removes_stdin_references",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_content_length_limitation",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_debug_in_qs_gets_form_var",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_debug_not_in_qs_still_gets_attr",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_debug_override_via_form_other",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_field_charset",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_form_charset",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_form_urlencoded",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getClientAddr_one_trusted_proxy",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getClientAddr_trusted_proxy_last",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getClientAddr_trusted_proxy_no_REMOTE_ADDR",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getClientAddr_wo_trusted_proxy",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getHeader_case_insensitive",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getHeader_exact",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getHeader_literal_turns_off_case_normalization",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getHeader_nonesuch",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getHeader_nonesuch_with_default",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getHeader_underscore_is_dash",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getVirtualRoot",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_get_with_body_and_query_string_ignores_body",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_issue_1095",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_locale_fallback",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_locale_in_qs",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_locale_property_accessor",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_locale_property_override_via_form_other",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_locale_semantics",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_method_GET",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_method_POST",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_no_docstring_on_instance",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_parses_json_cookies",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_BODY",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_BODY_unseekable",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_SOAP",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_SOAP_query_string",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_seekable_form_data",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_unseekable_form_data",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_unspecified_file",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_cookie_parsing",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_defaults",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_defaults_w_taints",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_dotted_name_as_tuple",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_large_input_gets_tempfile",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_marshalling_into_sequences",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_records_w_sequences",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_records_w_sequences_tainted",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_simple_containers",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_simple_containers_w_taints",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_simple_marshalling",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_simple_marshalling_w_taints",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_tainted_attribute_raises",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_tainted_values_cleans_exceptions",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_unicode_conversions",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_unicode_w_taints",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_urlencoded_and_qs",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_with_file_upload_gets_iterator",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_wo_marshalling",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_wo_marshalling_w_Taints",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_wo_query_string",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_xmlrpc",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_xmlrpc_controlled_allowed",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_xmlrpc_controlled_disallowed",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_xmlrpc_method",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_xmlrpc_query_string",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_xmlrpc_with_args",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_put_with_body_and_query_string",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_put_with_body_limit",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_resolve_url_doesnt_send_endrequestevent",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_resolve_url_errorhandling",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_text__password_field",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_url_scheme",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_webdav_source_port_available",
"src/ZPublisher/tests/testHTTPRequest.py::TestHTTPRequestZope3Views::test_no_traversal_of_view_request_attribute",
"src/ZPublisher/tests/testHTTPRequest.py::TestSearchType::test_image_control",
"src/ZPublisher/tests/testHTTPRequest.py::TestSearchType::test_leftmost",
"src/ZPublisher/tests/testHTTPRequest.py::TestSearchType::test_special",
"src/ZPublisher/tests/testHTTPRequest.py::TestSearchType::test_type",
"src/ZPublisher/tests/testHTTPRequest.py::TestLimitedFileReader::test_del",
"src/ZPublisher/tests/testHTTPRequest.py::TestLimitedFileReader::test_delegation",
"src/ZPublisher/tests/testHTTPRequest.py::TestLimitedFileReader::test_enforce_limit",
"src/ZPublisher/tests/testHTTPRequest.py::TestLimitedFileReader::test_iteration",
"src/ZPublisher/tests/testHTTPRequest.py::TestLimitedFileReader::test_read",
"src/ZPublisher/tests/testHTTPRequest.py::TestLimitedFileReader::test_readline"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2023-10-12T10:19:56Z" | zpl-2.1 |
|
zopefoundation__Zope-1175 | diff --git a/CHANGES.rst b/CHANGES.rst
index 2aa73244f..78aaf1f90 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -16,8 +16,13 @@ https://github.com/zopefoundation/Zope/blob/4.x/CHANGES.rst
- Update to newest compatible versions of dependencies.
-- Honor a request's ``Content-Length``
- (`#1171 <https://github.com/zopefoundation/Zope/issues/1171>`_).
+- New ``paste.filter_app_factory`` entry point ``content_length``.
+ This WSGI middleware component can be used with
+ WSGI servers which do not follow the PEP 3333 recommendation
+ regarding input handling for requests with
+ ``Content-Length`` header.
+ Allows administrators to fix
+ `#1171 <https://github.com/zopefoundation/Zope/pull/1171>`_.
5.8.6 (2023-10-04)
diff --git a/setup.py b/setup.py
index af651379b..bf102dc60 100644
--- a/setup.py
+++ b/setup.py
@@ -142,6 +142,7 @@ setup(
],
'paste.filter_app_factory': [
'httpexceptions=ZPublisher.httpexceptions:main',
+ 'content_length=ZPublisher.pastefilter:filter_content_length',
],
'console_scripts': [
'addzopeuser=Zope2.utilities.adduser:main',
diff --git a/src/ZPublisher/HTTPRequest.py b/src/ZPublisher/HTTPRequest.py
index 80e60df5c..20421a14b 100644
--- a/src/ZPublisher/HTTPRequest.py
+++ b/src/ZPublisher/HTTPRequest.py
@@ -1427,17 +1427,9 @@ class ZopeFieldStorage(ValueAccessor):
VALUE_LIMIT = Global("FORM_MEMORY_LIMIT")
def __init__(self, fp, environ):
+ self.file = fp
method = environ.get("REQUEST_METHOD", "GET").upper()
url_qs = environ.get("QUERY_STRING", "")
- content_length = environ.get("CONTENT_LENGTH")
- if content_length:
- try:
- fp.tell()
- except Exception:
- # potentially not preprocessed by the WSGI server
- # enforce ``Content-Length`` specified body length limit
- fp = LimitedFileReader(fp, int(content_length))
- self.file = fp
post_qs = ""
hl = []
content_type = environ.get("CONTENT_TYPE",
@@ -1501,53 +1493,6 @@ class ZopeFieldStorage(ValueAccessor):
add_field(field)
-class LimitedFileReader:
- """File wrapper emulating EOF."""
-
- # attributes to be delegated to the file
- DELEGATE = {"close", "closed", "fileno", "mode", "name"}
-
- def __init__(self, fp, limit):
- """emulate EOF after *limit* bytes have been read.
-
- *fp* is a binary file like object without ``seek`` support.
- """
- self.fp = fp
- assert limit >= 0
- self.limit = limit
-
- def _enforce_limit(self, size):
- limit = self.limit
- return limit if size is None or size < 0 else min(size, limit)
-
- def read(self, size=-1):
- data = self.fp.read(self._enforce_limit(size))
- self.limit -= len(data)
- return data
-
- def readline(self, size=-1):
- data = self.fp.readline(self._enforce_limit(size))
- self.limit -= len(data)
- return data
-
- def __iter__(self):
- return self
-
- def __next__(self):
- data = self.readline()
- if not data:
- raise StopIteration()
- return data
-
- def __del__(self):
- return self.fp.__del__()
-
- def __getattr__(self, attr):
- if attr not in self.DELEGATE:
- raise AttributeError(attr)
- return getattr(self.fp, attr)
-
-
def _mp_charset(part):
"""the charset of *part*."""
content_type = part.headers.get("Content-Type", "")
diff --git a/src/ZPublisher/pastefilter.py b/src/ZPublisher/pastefilter.py
new file mode 100644
index 000000000..71368364b
--- /dev/null
+++ b/src/ZPublisher/pastefilter.py
@@ -0,0 +1,123 @@
+##############################################################################
+#
+# Copyright (c) 2023 Zope Foundation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+""" ``PasteDeploy`` filters also known as WSGI middleware.
+
+`The WSGI architecture <https://peps.python.org/pep-3333>`_
+consists of a WSGI server, a WSGI application and optionally
+WSGI middleware in between.
+The server listens for HTTP requests, describes an incoming
+request via a WSGI environment, calls the application with
+this environment and the function ``start_response`` and sends the
+response to the client.
+The application is a callable with parameters *environ* and
+*start_response*. It processes the request, calls *start_response*
+with the response headers and returns an iterable producing the response
+body.
+A middleware component takes a (base) application and returns an
+(enhanced) application.
+
+``PasteDeploy`` calls a middleware component a "filter".
+In order to be able to provide parameters, filters are configured
+via filter factories. ``paste.deploy`` knows two filter factory types:
+``filter_factory`` and ``filter_app_factory``.
+A filter_factory has signature ``global_conf, **local_conf`` and
+returns a filter (i.e. a function transforming an application into
+an application),
+a filter_app_factory has signature ``app, global_conf, **local_conf``
+and returns the enhanced application directly.
+For details see the ``PasteDeploy`` documentation linked from
+its PyPI page.
+
+The main content of this module are filter factory definitions.
+They are identified by a `filter_` prefix.
+Their factory type is determined by the signature.
+"""
+
+
+def filter_content_length(app, global_conf):
+ """Honor a ``Content-Length`` header.
+
+ Use this filter if the WSGI server does not follow
+ `Note 1 regarding the WSGI input stream
+ <https://peps.python.org/pep-3333/#input-and-error-streams>`_
+ (such as the ``simple_server`` of Python's ``wsgiref``)
+ or violates
+ `section 6.3 of RFC 7230
+ <https://datatracker.ietf.org/doc/html/rfc7230#section-6.3>`_.
+ """
+ def enhanced_app(env, start_response):
+ wrapped = None
+ content_length = env.get("CONTENT_LENGTH")
+ if content_length:
+ env["wsgi.input"] = wrapped = LimitedFileReader(
+ env["wsgi.input"], int(content_length))
+ try:
+ # Note: this does not special case ``wsgiref.util.FileWrapper``
+ # or other similar optimazations
+ yield from app(env, start_response)
+ finally:
+ if wrapped is not None:
+ wrapped.discard_remaining()
+
+ return enhanced_app
+
+
+class LimitedFileReader:
+ """File wrapper emulating EOF."""
+
+ # attributes to be delegated to the file
+ DELEGATE = {"close", "closed", "fileno", "mode", "name"}
+
+ BUFSIZE = 1 << 14
+
+ def __init__(self, fp, limit):
+ """emulate EOF after *limit* bytes have been read.
+
+ *fp* is a binary file like object.
+ """
+ self.fp = fp
+ assert limit >= 0
+ self.limit = limit
+
+ def _enforce_limit(self, size):
+ limit = self.limit
+ return limit if size is None or size < 0 else min(size, limit)
+
+ def read(self, size=-1):
+ data = self.fp.read(self._enforce_limit(size))
+ self.limit -= len(data)
+ return data
+
+ def readline(self, size=-1):
+ data = self.fp.readline(self._enforce_limit(size))
+ self.limit -= len(data)
+ return data
+
+ def __iter__(self):
+ return self
+
+ def __next__(self):
+ data = self.readline()
+ if not data:
+ raise StopIteration()
+ return data
+
+ def discard_remaining(self):
+ while self.read(self.BUFSIZE):
+ pass
+
+ def __getattr__(self, attr):
+ if attr not in self.DELEGATE:
+ raise AttributeError(attr)
+ return getattr(self.fp, attr)
diff --git a/src/Zope2/utilities/skel/etc/zope.ini.in b/src/Zope2/utilities/skel/etc/zope.ini.in
index 9c82ae914..754e45545 100644
--- a/src/Zope2/utilities/skel/etc/zope.ini.in
+++ b/src/Zope2/utilities/skel/etc/zope.ini.in
@@ -15,6 +15,11 @@ setup_console_handler = False
pipeline =
egg:Zope#httpexceptions
translogger
+# uncomment the following line when your WSGI server does
+# not honor the recommendation of note 1
+# regarding the WSGI input stream of PEP 3333
+# or violates section 6.3 of RFC 7230
+# egg:Zope#content_length
zope
[loggers]
| zopefoundation/Zope | 4268cb13a4ba62ec90ff941c2aececbf21c2970b | diff --git a/src/ZPublisher/tests/testHTTPRequest.py b/src/ZPublisher/tests/testHTTPRequest.py
index 0dafba669..d7fe18e4d 100644
--- a/src/ZPublisher/tests/testHTTPRequest.py
+++ b/src/ZPublisher/tests/testHTTPRequest.py
@@ -31,7 +31,6 @@ from zope.publisher.interfaces.http import IHTTPRequest
from zope.testing.cleanup import cleanUp
from ZPublisher.HTTPRequest import BadRequest
from ZPublisher.HTTPRequest import FileUpload
-from ZPublisher.HTTPRequest import LimitedFileReader
from ZPublisher.HTTPRequest import search_type
from ZPublisher.interfaces import IXmlrpcChecker
from ZPublisher.tests.testBaseRequest import TestRequestViewsBase
@@ -1515,15 +1514,6 @@ class HTTPRequestTests(unittest.TestCase, HTTPRequestFactoryMixin):
self.assertEqual(req["x"], "äöü")
self.assertEqual(req["y"], "äöü")
- def test_content_length_limitation(self):
- body = b"123abc"
- env = self._makePostEnviron(body)
- env["CONTENT_TYPE"] = "application/octed-stream"
- env["CONTENT_LENGTH"] = "3"
- req = self._makeOne(_Unseekable(BytesIO(body)), env)
- req.processInputs()
- self.assertEqual(req["BODY"], b"123")
-
class TestHTTPRequestZope3Views(TestRequestViewsBase):
@@ -1580,48 +1570,6 @@ class TestSearchType(unittest.TestCase):
self.check("abc:a-_0b", ":a-_0b")
-class TestLimitedFileReader(unittest.TestCase):
- def test_enforce_limit(self):
- f = LimitedFileReader(BytesIO(), 10)
- enforce = f._enforce_limit
- self.assertEqual(enforce(None), 10)
- self.assertEqual(enforce(-1), 10)
- self.assertEqual(enforce(20), 10)
- self.assertEqual(enforce(5), 5)
-
- def test_read(self):
- f = LimitedFileReader(BytesIO(b"123\n567\n901\n"), 10)
- self.assertEqual(len(f.read()), 10)
- self.assertEqual(len(f.read()), 0)
- f = LimitedFileReader(BytesIO(b"123\n567\n901\n"), 10)
- self.assertEqual(len(f.read(8)), 8)
- self.assertEqual(len(f.read(3)), 2)
- self.assertEqual(len(f.read(3)), 0)
-
- def test_readline(self):
- f = LimitedFileReader(BytesIO(b"123\n567\n901\n"), 10)
- self.assertEqual(f.readline(), b"123\n")
- self.assertEqual(f.readline(), b"567\n")
- self.assertEqual(f.readline(), b"90")
- self.assertEqual(f.readline(), b"")
- f = LimitedFileReader(BytesIO(b"123\n567\n901\n"), 10)
- self.assertEqual(f.readline(1), b"1")
-
- def test_iteration(self):
- f = LimitedFileReader(BytesIO(b"123\n567\n901\n"), 10)
- self.assertEqual(list(f), [b"123\n", b"567\n", b"90"])
-
- def test_del(self):
- f = LimitedFileReader(BytesIO(b"123\n567\n901\n"), 10)
- del f
-
- def test_delegation(self):
- f = LimitedFileReader(BytesIO(b"123\n567\n901\n"), 10)
- with self.assertRaises(AttributeError):
- f.write
- f.close()
-
-
class _Unseekable:
"""Auxiliary class emulating an unseekable file like object"""
def __init__(self, file):
diff --git a/src/ZPublisher/tests/test_pastefilter.py b/src/ZPublisher/tests/test_pastefilter.py
new file mode 100644
index 000000000..91f79b1cf
--- /dev/null
+++ b/src/ZPublisher/tests/test_pastefilter.py
@@ -0,0 +1,87 @@
+##############################################################################
+#
+# Copyright (c) 2023 Zope Foundation and Contributors.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+import unittest
+from io import BytesIO
+
+from paste.deploy import loadfilter
+
+from ..pastefilter import LimitedFileReader
+
+
+class TestLimitedFileReader(unittest.TestCase):
+ def test_enforce_limit(self):
+ f = LimitedFileReader(BytesIO(), 10)
+ enforce = f._enforce_limit
+ self.assertEqual(enforce(None), 10)
+ self.assertEqual(enforce(-1), 10)
+ self.assertEqual(enforce(20), 10)
+ self.assertEqual(enforce(5), 5)
+
+ def test_read(self):
+ f = LimitedFileReader(BytesIO(b"123\n567\n901\n"), 10)
+ self.assertEqual(len(f.read()), 10)
+ self.assertEqual(len(f.read()), 0)
+ f = LimitedFileReader(BytesIO(b"123\n567\n901\n"), 10)
+ self.assertEqual(len(f.read(8)), 8)
+ self.assertEqual(len(f.read(3)), 2)
+ self.assertEqual(len(f.read(3)), 0)
+
+ def test_readline(self):
+ f = LimitedFileReader(BytesIO(b"123\n567\n901\n"), 10)
+ self.assertEqual(f.readline(), b"123\n")
+ self.assertEqual(f.readline(), b"567\n")
+ self.assertEqual(f.readline(), b"90")
+ self.assertEqual(f.readline(), b"")
+ f = LimitedFileReader(BytesIO(b"123\n567\n901\n"), 10)
+ self.assertEqual(f.readline(1), b"1")
+
+ def test_iteration(self):
+ f = LimitedFileReader(BytesIO(b"123\n567\n901\n"), 10)
+ self.assertEqual(list(f), [b"123\n", b"567\n", b"90"])
+
+ def test_discard_remaining(self):
+ fp = BytesIO(b"123\n567\n901\n")
+ LimitedFileReader(fp, 10).discard_remaining()
+ self.assertEqual(fp.read(), b"1\n")
+
+ def test_delegation(self):
+ f = LimitedFileReader(BytesIO(b"123\n567\n901\n"), 10)
+ with self.assertRaises(AttributeError):
+ f.write
+ f.close()
+
+
+class TestFilters(unittest.TestCase):
+ def test_content_length(self):
+ filter = loadfilter("egg:Zope", "content_length")
+
+ def app(env, start_response):
+ return iter((env["wsgi.input"],))
+
+ def request(env, app=filter(app)):
+ return app(env, None)
+
+ fp = BytesIO()
+ env = {"wsgi.input": fp}
+ self.assertIs(next(request(env)), fp)
+
+ fp = BytesIO(b"123")
+ env = {"wsgi.input": fp}
+ env["CONTENT_LENGTH"] = "3"
+ response = request(env)
+ r = next(response)
+ self.assertIsInstance(r, LimitedFileReader)
+ self.assertEqual(r.limit, 3)
+ with self.assertRaises(StopIteration):
+ next(response)
+ self.assertFalse(fp.read())
| Zope 5.8.1 breaks using `wsgiref`
### What I did:
I am using Python's stdlib `wsgiref` in selenium tests to start a simple WSGI server.
### What I expect to happen:
Using `wsgiref` should be possible.
### What actually happened:
`wsgiref` uses a `socket` as `stdin` for the WSGI environment.
And Zope 5.8.1+ uses `read()` to get the data from this socket, the execution is blocked and later on runs into a timeout.
Previous versions (via `cgi` module) called `readline()` on the socket which does not block.
(Sorry I cannot provide a minimal test example as it involves too much custom code. Additionally I did not find an easy way to start a Zope instance using `wsgiref` – the examples for using a different WSGI server in the docs seem to require some preparation.)
### What version of Python and Zope/Addons I am using:
* Zope 5.8.6
* MacOS 13.6
* Python 3.11 | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test__str__returns_native_string",
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test_copy",
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test_dict_methods",
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test_dict_special_methods",
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test_eq",
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test_repr",
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test_str",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test___bobo_traverse___raises",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test___str____password_field",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test__authUserPW_non_ascii",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test__authUserPW_simple",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test__authUserPW_with_embedded_colon",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test__str__returns_native_string",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_bytes_converter",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_doesnt_re_clean_environ",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_keeps_only_last_PARENT",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_keeps_preserves__auth",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_preserves_direct_interfaces",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_preserves_request_subclass",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_preserves_response_class",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_updates_method_to_GET",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_close_removes_stdin_references",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_debug_in_qs_gets_form_var",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_debug_not_in_qs_still_gets_attr",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_debug_override_via_form_other",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_field_charset",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_form_charset",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_form_urlencoded",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getClientAddr_one_trusted_proxy",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getClientAddr_trusted_proxy_last",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getClientAddr_trusted_proxy_no_REMOTE_ADDR",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getClientAddr_wo_trusted_proxy",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getHeader_case_insensitive",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getHeader_exact",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getHeader_literal_turns_off_case_normalization",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getHeader_nonesuch",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getHeader_nonesuch_with_default",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getHeader_underscore_is_dash",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getVirtualRoot",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_get_with_body_and_query_string_ignores_body",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_issue_1095",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_locale_fallback",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_locale_in_qs",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_locale_property_accessor",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_locale_property_override_via_form_other",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_locale_semantics",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_method_GET",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_method_POST",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_no_docstring_on_instance",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_parses_json_cookies",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_BODY",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_BODY_unseekable",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_SOAP",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_SOAP_query_string",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_seekable_form_data",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_unseekable_form_data",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_unspecified_file",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_cookie_parsing",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_defaults",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_defaults_w_taints",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_dotted_name_as_tuple",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_large_input_gets_tempfile",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_marshalling_into_sequences",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_records_w_sequences",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_records_w_sequences_tainted",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_simple_containers",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_simple_containers_w_taints",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_simple_marshalling",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_simple_marshalling_w_taints",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_tainted_attribute_raises",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_tainted_values_cleans_exceptions",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_unicode_conversions",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_unicode_w_taints",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_urlencoded_and_qs",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_with_file_upload_gets_iterator",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_wo_marshalling",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_wo_marshalling_w_Taints",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_wo_query_string",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_xmlrpc",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_xmlrpc_controlled_allowed",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_xmlrpc_controlled_disallowed",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_xmlrpc_method",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_xmlrpc_query_string",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_xmlrpc_with_args",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_put_with_body_and_query_string",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_put_with_body_limit",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_resolve_url_doesnt_send_endrequestevent",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_resolve_url_errorhandling",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_text__password_field",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_url_scheme",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_webdav_source_port_available",
"src/ZPublisher/tests/testHTTPRequest.py::TestHTTPRequestZope3Views::test_no_traversal_of_view_request_attribute",
"src/ZPublisher/tests/testHTTPRequest.py::TestSearchType::test_image_control",
"src/ZPublisher/tests/testHTTPRequest.py::TestSearchType::test_leftmost",
"src/ZPublisher/tests/testHTTPRequest.py::TestSearchType::test_special",
"src/ZPublisher/tests/testHTTPRequest.py::TestSearchType::test_type",
"src/ZPublisher/tests/test_pastefilter.py::TestLimitedFileReader::test_delegation",
"src/ZPublisher/tests/test_pastefilter.py::TestLimitedFileReader::test_discard_remaining",
"src/ZPublisher/tests/test_pastefilter.py::TestLimitedFileReader::test_enforce_limit",
"src/ZPublisher/tests/test_pastefilter.py::TestLimitedFileReader::test_iteration",
"src/ZPublisher/tests/test_pastefilter.py::TestLimitedFileReader::test_read",
"src/ZPublisher/tests/test_pastefilter.py::TestLimitedFileReader::test_readline"
] | [] | {
"failed_lite_validators": [
"has_added_files",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2023-10-17T12:04:15Z" | zpl-2.1 |
|
zopefoundation__Zope-1183 | diff --git a/CHANGES.rst b/CHANGES.rst
index 0a3cd08e0..9665d0317 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -10,6 +10,9 @@ https://github.com/zopefoundation/Zope/blob/4.x/CHANGES.rst
5.8.7 (unreleased)
------------------
+- Support form data in ``PUT`` requests (following the ``multipart`` example).
+ Fixes `#1182 <https://github.com/zopefoundation/Zope/issues/1182>`_.
+
- Separate ZODB connection information into new ZODB Connections view.
- Move the cache detail links to the individual database pages.
diff --git a/src/ZPublisher/HTTPRequest.py b/src/ZPublisher/HTTPRequest.py
index 20421a14b..9a497839e 100644
--- a/src/ZPublisher/HTTPRequest.py
+++ b/src/ZPublisher/HTTPRequest.py
@@ -1432,19 +1432,30 @@ class ZopeFieldStorage(ValueAccessor):
url_qs = environ.get("QUERY_STRING", "")
post_qs = ""
hl = []
- content_type = environ.get("CONTENT_TYPE",
- "application/x-www-form-urlencoded")
- hl.append(("content-type", content_type))
+ content_type = environ.get("CONTENT_TYPE")
+ if content_type is not None:
+ hl.append(("content-type", content_type))
+ else:
+ content_type = ""
content_type, options = parse_options_header(content_type)
content_type = content_type.lower()
content_disposition = environ.get("CONTENT_DISPOSITION")
if content_disposition is not None:
hl.append(("content-disposition", content_disposition))
+ # Note: ``headers`` does not reflect the complete headers.
+ # Likely, it should get removed altogether and accesses be replaced
+ # by a lookup of the corresponding CGI environment keys.
self.headers = Headers(hl)
parts = ()
- if method == "POST" \
- and content_type in \
- ("multipart/form-data", "application/x-www-form-urlencoded"):
+ if method in ("POST", "PUT") \
+ and content_type in (
+ "multipart/form-data", "application/x-www-form-urlencoded",
+ "application/x-url-encoded",
+ # ``Testing`` assumes "application/x-www-form-urlencoded"
+ # as default content type
+ # We have mapped a missing content type to ``""``.
+ "",
+ ):
try:
fpos = fp.tell()
except Exception:
@@ -1456,7 +1467,7 @@ class ZopeFieldStorage(ValueAccessor):
disk_limit=FORM_DISK_LIMIT,
memfile_limit=FORM_MEMFILE_LIMIT,
charset="latin-1").parts()
- elif content_type == "application/x-www-form-urlencoded":
+ else:
post_qs = fp.read(FORM_MEMORY_LIMIT).decode("latin-1")
if fp.read(1):
raise BadRequest("form data processing "
| zopefoundation/Zope | fe08bae876f13dc1dbc333730eaeb51f264f46a3 | diff --git a/src/ZPublisher/tests/testHTTPRequest.py b/src/ZPublisher/tests/testHTTPRequest.py
index d7fe18e4d..7b1131779 100644
--- a/src/ZPublisher/tests/testHTTPRequest.py
+++ b/src/ZPublisher/tests/testHTTPRequest.py
@@ -1468,6 +1468,7 @@ class HTTPRequestTests(unittest.TestCase, HTTPRequestFactoryMixin):
"SERVER_NAME": "localhost",
"SERVER_PORT": "8080",
"REQUEST_METHOD": "PUT",
+ "CONTENT_TYPE": "application",
},
None,
)
@@ -1514,6 +1515,23 @@ class HTTPRequestTests(unittest.TestCase, HTTPRequestFactoryMixin):
self.assertEqual(req["x"], "äöü")
self.assertEqual(req["y"], "äöü")
+ def test_put_with_form(self):
+ req_factory = self._getTargetClass()
+ body = b"foo=foo"
+ req = req_factory(
+ BytesIO(body),
+ {
+ "SERVER_NAME": "localhost",
+ "SERVER_PORT": "8080",
+ "REQUEST_METHOD": "PUT",
+ "CONTENT_TYPE": "application/x-www-form-urlencoded",
+ "CONTENT_LENGTH": len(body),
+ },
+ None,
+ )
+ req.processInputs()
+ self.assertEqual(req.form["foo"], "foo")
+
class TestHTTPRequestZope3Views(TestRequestViewsBase):
| Clarification on Handling Image Uploads via HTTP PUT in Zope5 with WSGI Server
### What I did:
I encountered an issue related to the handling of image uploads when using the HTTP PUT method in Zope5 with a WSGI server. Here are the steps I followed to reproduce the problem:
1. Using a Zope5 installation with the WSGI server.
2. Sending an HTTP PUT request to upload an image.
3. Observing that the image data is received in the request body as encoded data.
### What I expect to happen:
I expected that, similar to Zope4 with the ZServer, I would receive the image data as part of the form, and I would be able to access it as an object. This is the behavior I was accustomed to in Zope4.
### What actually happened:
In Zope5 with the WSGI server, when I use the HTTP PUT method to upload an image, the image data is received in the request body, and the body data is encoded. As a result, I am unable to access the image data as a file upload object, which is different from the behavior in Zope4.
### What version of Python and Zope/Addons I am using:
- Operating System: Windows/Linux
- Python Version: 3.10.9
- Zope Version: 5.8.3
This report aims to highlight the difference in behavior between Zope4 and Zope5 when using HTTP PUT for image uploads and to understand whether this is the expected behavior for PUT operations.
Additional Observation:
https://github.com/zopefoundation/Zope/blob/5.8.3/src/ZPublisher/HTTPRequest.py#L1425
If i include "PUT" condition here, it is working as expected
Thank you.
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_put_with_form"
] | [
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test__str__returns_native_string",
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test_copy",
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test_dict_methods",
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test_dict_special_methods",
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test_eq",
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test_repr",
"src/ZPublisher/tests/testHTTPRequest.py::RecordTests::test_str",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test___bobo_traverse___raises",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test___str____password_field",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test__authUserPW_non_ascii",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test__authUserPW_simple",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test__authUserPW_with_embedded_colon",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test__str__returns_native_string",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_bytes_converter",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_doesnt_re_clean_environ",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_keeps_only_last_PARENT",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_keeps_preserves__auth",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_preserves_direct_interfaces",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_preserves_request_subclass",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_preserves_response_class",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_clone_updates_method_to_GET",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_close_removes_stdin_references",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_debug_in_qs_gets_form_var",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_debug_not_in_qs_still_gets_attr",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_debug_override_via_form_other",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_field_charset",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_form_charset",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_form_urlencoded",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getClientAddr_one_trusted_proxy",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getClientAddr_trusted_proxy_last",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getClientAddr_trusted_proxy_no_REMOTE_ADDR",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getClientAddr_wo_trusted_proxy",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getHeader_case_insensitive",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getHeader_exact",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getHeader_literal_turns_off_case_normalization",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getHeader_nonesuch",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getHeader_nonesuch_with_default",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getHeader_underscore_is_dash",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_getVirtualRoot",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_get_with_body_and_query_string_ignores_body",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_issue_1095",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_locale_fallback",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_locale_in_qs",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_locale_property_accessor",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_locale_property_override_via_form_other",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_locale_semantics",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_method_GET",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_method_POST",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_no_docstring_on_instance",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_parses_json_cookies",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_BODY",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_BODY_unseekable",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_SOAP",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_SOAP_query_string",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_seekable_form_data",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_unseekable_form_data",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_unspecified_file",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_cookie_parsing",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_defaults",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_defaults_w_taints",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_dotted_name_as_tuple",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_large_input_gets_tempfile",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_marshalling_into_sequences",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_records_w_sequences",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_records_w_sequences_tainted",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_simple_containers",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_simple_containers_w_taints",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_simple_marshalling",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_simple_marshalling_w_taints",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_tainted_attribute_raises",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_tainted_values_cleans_exceptions",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_unicode_conversions",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_unicode_w_taints",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_w_urlencoded_and_qs",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_with_file_upload_gets_iterator",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_wo_marshalling",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_wo_marshalling_w_Taints",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_wo_query_string",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_xmlrpc",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_xmlrpc_controlled_allowed",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_xmlrpc_controlled_disallowed",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_xmlrpc_method",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_xmlrpc_query_string",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_processInputs_xmlrpc_with_args",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_put_with_body_and_query_string",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_put_with_body_limit",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_resolve_url_doesnt_send_endrequestevent",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_resolve_url_errorhandling",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_text__password_field",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_url_scheme",
"src/ZPublisher/tests/testHTTPRequest.py::HTTPRequestTests::test_webdav_source_port_available",
"src/ZPublisher/tests/testHTTPRequest.py::TestHTTPRequestZope3Views::test_no_traversal_of_view_request_attribute",
"src/ZPublisher/tests/testHTTPRequest.py::TestSearchType::test_image_control",
"src/ZPublisher/tests/testHTTPRequest.py::TestSearchType::test_leftmost",
"src/ZPublisher/tests/testHTTPRequest.py::TestSearchType::test_special",
"src/ZPublisher/tests/testHTTPRequest.py::TestSearchType::test_type"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2023-11-06T10:53:45Z" | zpl-2.1 |
|
zopefoundation__Zope-412 | diff --git a/CHANGES.rst b/CHANGES.rst
index 7a40b0f37..eb35c5aa0 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -14,6 +14,9 @@ https://github.com/zopefoundation/Zope/blob/4.0a6/CHANGES.rst
Fixes
+++++
+- Recreate ``App.version_txt.getZopeVersion``
+ (`#411 <https://github.com/zopefoundation/Zope/issues/411>`_)
+
- Restore the `View` ZMI tab on folders and their subclasses
(`#449 <https://github.com/zopefoundation/Zope/issues/449>`_)
diff --git a/src/App/version_txt.py b/src/App/version_txt.py
index e4db4fe20..ba9ddd975 100644
--- a/src/App/version_txt.py
+++ b/src/App/version_txt.py
@@ -10,22 +10,54 @@
# FOR A PARTICULAR PURPOSE
#
##############################################################################
+import collections
+import re
import sys
import pkg_resources
_version_string = None
+_zope_version = None
+
+ZopeVersion = collections.namedtuple(
+ "ZopeVersion",
+ ["major", "minor", "micro", "status", "release"]
+ )
def _prep_version_data():
- global _version_string
+ global _version_string, _zope_version
if _version_string is None:
v = sys.version_info
pyver = "python %d.%d.%d, %s" % (v[0], v[1], v[2], sys.platform)
dist = pkg_resources.get_distribution('Zope')
_version_string = "%s, %s" % (dist.version, pyver)
+ expr = re.compile(
+ r'(?P<major>[0-9]+)\.(?P<minor>[0-9]+)(\.(?P<micro>[0-9]+))?'
+ '(?P<status>[A-Za-z]+)?(?P<release>[0-9]+)?')
+ version_dict = expr.match(dist.version).groupdict()
+ _zope_version = ZopeVersion(
+ int(version_dict.get('major') or -1),
+ int(version_dict.get('minor') or -1),
+ int(version_dict.get('micro') or -1),
+ version_dict.get('status') or '',
+ int(version_dict.get('release') or -1),
+ )
+
+
+
def version_txt():
_prep_version_data()
return '(%s)' % _version_string
+
+def getZopeVersion():
+ """return information about the Zope version as a named tuple.
+
+ Format of zope_version tuple:
+ (major <int>, minor <int>, micro <int>, status <string>, release <int>)
+ If unreleased, integers may be -1.
+ """
+ _prep_version_data()
+ return _zope_version
| zopefoundation/Zope | 20d29682acacb73d7fb41d5e37beb46fa87a19b1 | diff --git a/src/App/tests/test_getZopeVersion.py b/src/App/tests/test_getZopeVersion.py
new file mode 100644
index 000000000..eb2172ab8
--- /dev/null
+++ b/src/App/tests/test_getZopeVersion.py
@@ -0,0 +1,32 @@
+##############################################################################
+#
+# Copyright (c) 2004 Zope Foundation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""Tests for the recreated `getZopeVersion`."""
+
+import unittest
+
+from pkg_resources import get_distribution
+from App.version_txt import getZopeVersion
+
+class Test(unittest.TestCase):
+ def test_major(self):
+ self.assertEqual(
+ getZopeVersion().major,
+ int(get_distribution("Zope").version.split(".")[0])
+ )
+
+ def test_types(self):
+ zv = getZopeVersion()
+ for i in (0, 1, 2, 4):
+ self.assertIsInstance(zv[i], int, str(i))
+ self.assertIsInstance(zv[3], str, '3')
| Reliable detecting the Zope version
Add-ons interacting with the ZMI need to provide different templates for Zope 2 (old style ZMI) and Zope 4 (bootstrap based ZMI). Therefore, there is a need to reliable distinguish those versions -- potentially via a mechanism analogous to Python's `sys.version_info`. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/App/tests/test_getZopeVersion.py::Test::test_major",
"src/App/tests/test_getZopeVersion.py::Test::test_types"
] | [] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2018-12-10T08:53:53Z" | zpl-2.1 |
|
zopefoundation__Zope-893 | diff --git a/CHANGES.rst b/CHANGES.rst
index 596f15319..354591a69 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -11,6 +11,8 @@ https://github.com/zopefoundation/Zope/blob/4.x/CHANGES.rst
5.0a3 (unreleased)
------------------
+- Fix export of files with non-latin-1 compatible names
+ (`#890 <https://github.com/zopefoundation/Zope/issues/890>`_)
- Add ``pyupgrade`` via ``pre-commit``
(`#859 <https://github.com/zopefoundation/Zope/issues/859>`_)
diff --git a/src/OFS/ObjectManager.py b/src/OFS/ObjectManager.py
index 7751157cd..73f7fafbe 100644
--- a/src/OFS/ObjectManager.py
+++ b/src/OFS/ObjectManager.py
@@ -61,6 +61,7 @@ from zope.interface import implementer
from zope.interface.interfaces import ComponentLookupError
from zope.lifecycleevent import ObjectAddedEvent
from zope.lifecycleevent import ObjectRemovedEvent
+from ZPublisher.HTTPResponse import make_content_disposition
# Constants: __replaceable__ flags:
@@ -611,8 +612,10 @@ class ObjectManager(
if RESPONSE is not None:
RESPONSE.setHeader('Content-type', 'application/data')
- RESPONSE.setHeader('Content-Disposition',
- f'inline;filename={id}.{suffix}')
+ RESPONSE.setHeader(
+ 'Content-Disposition',
+ make_content_disposition('inline', f'{id}.{suffix}')
+ )
return result
f = os.path.join(CONFIG.clienthome, f'{id}.{suffix}')
diff --git a/src/ZPublisher/HTTPResponse.py b/src/ZPublisher/HTTPResponse.py
index 0883983df..8daf4d9c6 100644
--- a/src/ZPublisher/HTTPResponse.py
+++ b/src/ZPublisher/HTTPResponse.py
@@ -115,6 +115,30 @@ def build_http_date(when):
WEEKDAYNAME[wd], day, MONTHNAME[month], year, hh, mm, ss)
+def make_content_disposition(disposition, file_name):
+ """Create HTTP header for downloading a file with a UTF-8 filename.
+
+ See this and related answers: https://stackoverflow.com/a/8996249/2173868.
+ """
+ header = f'{disposition}'
+ try:
+ file_name.encode('us-ascii')
+ except UnicodeEncodeError:
+ # the file cannot be encoded using the `us-ascii` encoding
+ # which is advocated by RFC 7230 - 7237
+ #
+ # a special header has to be crafted
+ # also see https://tools.ietf.org/html/rfc6266#appendix-D
+ encoded_file_name = file_name.encode('us-ascii', errors='ignore')
+ header += f'; filename="{encoded_file_name}"'
+ quoted_file_name = quote(file_name)
+ header += f'; filename*=UTF-8\'\'{quoted_file_name}'
+ return header
+ else:
+ header += f'; filename="{file_name}"'
+ return header
+
+
class HTTPBaseResponse(BaseResponse):
""" An object representation of an HTTP response.
| zopefoundation/Zope | 29d63d40ebb8455af47e9fef44ac838bd9f96c35 | diff --git a/src/Testing/ZopeTestCase/testZODBCompat.py b/src/Testing/ZopeTestCase/testZODBCompat.py
index a879d4606..c1f9a1b52 100644
--- a/src/Testing/ZopeTestCase/testZODBCompat.py
+++ b/src/Testing/ZopeTestCase/testZODBCompat.py
@@ -32,6 +32,24 @@ folder_name = ZopeTestCase.folder_name
cutpaste_permissions = [add_documents_images_and_files, delete_objects]
+def make_request_response(environ=None):
+ from io import StringIO
+ from ZPublisher.HTTPRequest import HTTPRequest
+ from ZPublisher.HTTPResponse import HTTPResponse
+
+ if environ is None:
+ environ = {}
+
+ stdout = StringIO()
+ stdin = StringIO()
+ resp = HTTPResponse(stdout=stdout)
+ environ.setdefault('SERVER_NAME', 'foo')
+ environ.setdefault('SERVER_PORT', '80')
+ environ.setdefault('REQUEST_METHOD', 'GET')
+ req = HTTPRequest(stdin, environ, resp)
+ return req, resp
+
+
class DummyObject(SimpleItem):
id = 'dummy'
foo = None
@@ -96,6 +114,8 @@ class TestImportExport(ZopeTestCase.ZopeTestCase):
def afterSetUp(self):
self.setupLocalEnvironment()
self.folder.addDTMLMethod('doc', file='foo')
+ # please note the usage of the turkish i
+ self.folder.addDTMLMethod('ıq', file='foo')
# _p_oids are None until we create a savepoint
self.assertEqual(self.folder._p_oid, None)
transaction.savepoint(optimistic=True)
@@ -105,6 +125,23 @@ class TestImportExport(ZopeTestCase.ZopeTestCase):
self.folder.manage_exportObject('doc')
self.assertTrue(os.path.exists(self.zexp_file))
+ def testExportNonLatinFileNames(self):
+ """Test compatibility of the export with unicode characters.
+
+ Since Zope 4 also unicode ids can be used."""
+ _, response = make_request_response()
+ # please note the usage of a turkish `i`
+ self.folder.manage_exportObject(
+ 'ıq', download=1, RESPONSE=response)
+
+ found = False
+ for header in response.listHeaders():
+ if header[0] == 'Content-Disposition':
+ # value needs to be `us-ascii` compatible
+ assert header[1].encode("us-ascii")
+ found = True
+ self.assertTrue(found)
+
def testImport(self):
self.folder.manage_exportObject('doc')
self.folder._delObject('doc')
diff --git a/src/ZPublisher/tests/testHTTPResponse.py b/src/ZPublisher/tests/testHTTPResponse.py
index da1665235..22e94d7bb 100644
--- a/src/ZPublisher/tests/testHTTPResponse.py
+++ b/src/ZPublisher/tests/testHTTPResponse.py
@@ -8,6 +8,7 @@ from zExceptions import InternalError
from zExceptions import NotFound
from zExceptions import ResourceLockedError
from zExceptions import Unauthorized
+from ZPublisher.HTTPResponse import make_content_disposition
class HTTPResponseTests(unittest.TestCase):
@@ -1373,3 +1374,29 @@ class HTTPResponseTests(unittest.TestCase):
def test_isHTML_not_decodable_bytes(self):
response = self._makeOne()
self.assertFalse(response.isHTML('bïñårÿ'.encode('latin1')))
+
+
+class MakeDispositionHeaderTests(unittest.TestCase):
+
+ def test_ascii(self):
+ self.assertEqual(
+ make_content_disposition('inline', 'iq.png'),
+ 'inline; filename="iq.png"')
+
+ def test_latin_one(self):
+ self.assertEqual(
+ make_content_disposition('inline', 'Dänemark.png'),
+ 'inline; filename="b\'Dnemark.png\'"; filename*=UTF-8\'\'D%C3%A4nemark.png' # noqa: E501
+ )
+
+ def test_unicode(self):
+ """HTTP headers need to be latin-1 compatible
+
+ In order to offer file downloads which contain unicode file names,
+ the file name has to be treated in a special way, see
+ https://stackoverflow.com/questions/1361604 .
+ """
+ self.assertEqual(
+ make_content_disposition('inline', 'ıq.png'),
+ 'inline; filename="b\'q.png\'"; filename*=UTF-8\'\'%C4%B1q.png'
+ )
| Export / download of files with non-latin-1 compatible names is broken
**Reproduction**
- upload a file via ZMI with the name "ıqrm.png" (please note, the first letter is a turkish i)
- try to export it
- waitress error
```
2020-09-24 14:57:24,528 ERROR [waitress:358][waitress-0] Exception while serving /bliss/db/manage_exportObject
Traceback (most recent call last):
File "/home/jugmac00/Projects/bliss_deployment/work/_/home/jugmac00/.batou-shared-eggs/waitress-1.4.4-py3.7.egg/waitress/channel.py", line 350, in service
task.service()
File "/home/jugmac00/Projects/bliss_deployment/work/_/home/jugmac00/.batou-shared-eggs/waitress-1.4.4-py3.7.egg/waitress/task.py", line 171, in service
self.execute()
File "/home/jugmac00/Projects/bliss_deployment/work/_/home/jugmac00/.batou-shared-eggs/waitress-1.4.4-py3.7.egg/waitress/task.py", line 479, in execute
self.write(chunk)
File "/home/jugmac00/Projects/bliss_deployment/work/_/home/jugmac00/.batou-shared-eggs/waitress-1.4.4-py3.7.egg/waitress/task.py", line 311, in write
rh = self.build_response_header()
File "/home/jugmac00/Projects/bliss_deployment/work/_/home/jugmac00/.batou-shared-eggs/waitress-1.4.4-py3.7.egg/waitress/task.py", line 284, in build_response_header
return tobytes(res)
File "/home/jugmac00/Projects/bliss_deployment/work/_/home/jugmac00/.batou-shared-eggs/waitress-1.4.4-py3.7.egg/waitress/compat.py", line 69, in tobytes
return bytes(s, "latin-1")
UnicodeEncodeError: 'latin-1' codec can't encode character '\u0131' in position 54: ordinal not in range(256)
```
Actually, this was not my use case. I have a custom download (and a file view) in my Zope app, and noticed that the following code is broken for non latin-1 names:
```
def download(self, REQUEST):
"""
download the attachment
@REQUEST : request
"""
with open(self.completeFileName(), "rb") as f:
ret = f.read()
REQUEST.RESPONSE.setHeader('content-type', self.getMimeType())
REQUEST.RESPONSE.setHeader('content-length', str(len(ret)))
REQUEST.RESPONSE.setHeader('content-disposition', 'attachment; filename="%s"' % self.printFileName())
return ret
```
I then grepped the Zope source for a possible solution and found above bug.
**possible solutions**
- `zope.file` offers some solution - but when I understand that correctly, it changes the file name by double en- and decoding (which seems wrong to me, but possibly I do not understand the trick)
- `cherrypy` and afaik `Django` handle this differently
**zope.file**
https://github.com/zopefoundation/zope.file/blob/b952af17c23f7702b95a93b28b6458b38560874b/src/zope/file/download.py#L65-L70
**cherrypy**
https://github.com/cherrypy/cherrypy/pull/1851/files#diff-1b04e50f6724343e4321295525e2bd58R32
**django-sendfile**
https://github.com/johnsensible/django-sendfile/blob/7a000e0e7ae1732bcea222c7872bfda6a97c495c/sendfile/__init__.py#L69-L86
In my Zope app I implemented `cherrypy`s solution and it works like a charm.
As there is also a bug in Zope's `manage_exportObject` I'd like to have a function in Zope itself, given a filename and the type (inline or attachment), builds a correct header.
I'd volunteer to implement a solution during next Monday's Zope sprint.
@d-maurer @icemac - Maybe there is something I overlook? I hardly can't imagine nobody ever wanted to offer a file download for non-latin-1 names before?
P.S.: Maybe also both the comment of the `setHeader` method and the method itself should be updated, ie either warn or prohibit to set non-latin-1 values. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/Testing/ZopeTestCase/testZODBCompat.py::TestCopyPaste::testClone",
"src/Testing/ZopeTestCase/testZODBCompat.py::TestCopyPaste::testCopyPaste",
"src/Testing/ZopeTestCase/testZODBCompat.py::TestCopyPaste::testCutPaste",
"src/Testing/ZopeTestCase/testZODBCompat.py::TestCopyPaste::testRename",
"src/Testing/ZopeTestCase/testZODBCompat.py::TestImportExport::testExport",
"src/Testing/ZopeTestCase/testZODBCompat.py::TestImportExport::testExportNonLatinFileNames",
"src/Testing/ZopeTestCase/testZODBCompat.py::TestImportExport::testImport",
"src/Testing/ZopeTestCase/testZODBCompat.py::TestTransactionAbort::testTransactionAbort",
"src/Testing/ZopeTestCase/testZODBCompat.py::test_suite",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test___str__after_addHeader",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test___str__after_expireCookie",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test___str__after_redirect",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test___str__after_setCookie_appendCookie",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test___str__after_setHeader",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test___str__after_setHeader_literal",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test___str__already_wrote",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test___str__empty",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test___str__existing_content_length",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test___str__existing_transfer_encoding",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test___str__w_body",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test__encode_unicode_no_content_type_uses_default_encoding",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test__encode_unicode_w_content_type_no_charset_updates_charset",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test__encode_unicode_w_content_type_w_charset",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test__encode_unicode_w_content_type_w_charset_xml_preamble",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test__unauthorized_no_realm",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test__unauthorized_w_default_realm",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test__unauthorized_w_realm",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_addHeader_drops_CRLF",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_addHeader_is_case_sensitive",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_appendCookie_no_existing",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_appendCookie_w_existing",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_appendHeader_drops_CRLF",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_appendHeader_no_existing",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_appendHeader_no_existing_case_insensative",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_appendHeader_w_existing",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_appendHeader_w_existing_case_insenstative",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_badRequestError_invalid_parameter_name",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_badRequestError_valid_parameter_name",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_ctor_body_already_matches_charset_unchanged",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_ctor_body_recodes_to_match_content_type_charset",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_ctor_charset_application_header_no_header",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_ctor_charset_application_header_with_header",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_ctor_charset_no_content_type_header",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_ctor_charset_text_header_no_charset_defaults_latin1",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_ctor_charset_unicode_body_application_header",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_ctor_charset_unicode_body_application_header_diff_encoding",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_ctor_defaults",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_ctor_w_body",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_ctor_w_headers",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_ctor_w_status_code",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_ctor_w_status_errmsg",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_ctor_w_status_exception",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_debugError",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_exception_500_text",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_exception_Internal_Server_Error",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_expireCookie",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_expireCookie1160",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_finalize_after_redirect",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_finalize_empty",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_finalize_w_body",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_finalize_w_existing_content_length",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_finalize_w_transfer_encoding",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_forbiddenError",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_forbiddenError_w_entry",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_getHeader_existing",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_getHeader_existing_not_literal",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_getHeader_existing_w_literal",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_getHeader_nonesuch",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_insertBase_HTML_no_base_w_head_not_munged",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_insertBase_HTML_w_base_no_head_not_munged",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_insertBase_HTML_w_base_w_head_munged",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_insertBase_not_HTML_no_change",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_isHTML_not_decodable_bytes",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_listHeaders_after_addHeader",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_listHeaders_after_expireCookie",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_listHeaders_after_redirect",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_listHeaders_after_setCookie_appendCookie",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_listHeaders_after_setHeader",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_listHeaders_after_setHeader_literal",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_listHeaders_already_wrote",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_listHeaders_empty",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_listHeaders_existing_content_length",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_listHeaders_existing_transfer_encoding",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_listHeaders_w_body",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_notFoundError",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_notFoundError_w_entry",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_quoteHTML",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_redirect_alreadyquoted",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_redirect_defaults",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_redirect_explicit_status",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_redirect_nonascii",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_redirect_reserved_chars",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_redirect_unreserved_chars",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_redirect_w_lock",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_retry",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setBase_None",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setBase_no_trailing_path",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setBase_w_trailing_path",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setBody_2_tuple_w_is_error_converted_to_Site_Error",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setBody_2_tuple_wo_is_error_converted_to_HTML",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setBody_calls_insertBase",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setBody_compression_existing_encoding",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setBody_compression_no_prior_vary_header",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setBody_compression_no_prior_vary_header_but_forced",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setBody_compression_too_short_to_gzip",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setBody_compression_uncompressible_mimetype",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setBody_compression_w_prior_vary_header_incl_encoding",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setBody_compression_w_prior_vary_header_wo_encoding",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setBody_empty_unchanged",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setBody_object_with_asHTML",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setBody_object_with_unicode",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setBody_string_HTML",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setBody_string_not_HTML",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setBody_tuple",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setBody_w_bogus_pseudo_HTML",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setBody_w_locking",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setCookie_handle_byte_values",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setCookie_handle_unicode_values",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setCookie_no_attrs",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setCookie_no_existing",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setCookie_unquoted",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setCookie_w_comment",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setCookie_w_domain",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setCookie_w_existing",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setCookie_w_expires",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setCookie_w_httponly_false_value",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setCookie_w_httponly_true_value",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setCookie_w_path",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setCookie_w_same_site",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setCookie_w_secure_false_value",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setCookie_w_secure_true_value",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setHeader",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setHeader_drops_CRLF",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setHeader_drops_LF",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setHeader_literal",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setStatus_BadRequest",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setStatus_Forbidden_exception",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setStatus_InternalError_exception",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setStatus_NotFound_exception",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setStatus_ResourceLockedError_exception",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setStatus_Unauthorized_exception",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setStatus_code",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_setStatus_errmsg",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_unauthorized_no_debug_mode",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_unauthorized_w_debug_mode_no_credentials",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_unauthorized_w_debug_mode_w_credentials",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_write_already_wrote",
"src/ZPublisher/tests/testHTTPResponse.py::HTTPResponseTests::test_write_not_already_wrote",
"src/ZPublisher/tests/testHTTPResponse.py::MakeDispositionHeaderTests::test_ascii",
"src/ZPublisher/tests/testHTTPResponse.py::MakeDispositionHeaderTests::test_latin_one",
"src/ZPublisher/tests/testHTTPResponse.py::MakeDispositionHeaderTests::test_unicode"
] | [] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_media",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2020-09-28T10:38:56Z" | zpl-2.1 |
|
zopefoundation__Zope-906 | diff --git a/CHANGES.rst b/CHANGES.rst
index ea20b1f0a..befdb874b 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -10,6 +10,10 @@ https://zope.readthedocs.io/en/2.13/CHANGES.html
4.5.2 (unreleased)
------------------
+- Provide a more senseful ``OFS.SimpleItem.Item_w__name__.id``
+ to avoid bugs by use of deprecated direct ``id`` access
+ (as e.g. (`#903 <https://github.com/zopefoundation/Zope/issues/903>`_).
+
- Update dependencies to the latest releases that still support Python 2.
- Update to ``zope.interface > 5.1.0`` to fix a memory leak.
diff --git a/src/OFS/SimpleItem.py b/src/OFS/SimpleItem.py
index d5b5d6ec8..186b7f1b3 100644
--- a/src/OFS/SimpleItem.py
+++ b/src/OFS/SimpleItem.py
@@ -446,6 +446,10 @@ class Item_w__name__(Item):
"""
return self.__name__
+ # Alias (deprecated) `id` to `getId()` (but avoid recursion)
+ id = ComputedAttribute(
+ lambda self: self.getId() if "__name__" in self.__dict__ else "")
+
def title_or_id(self):
"""Return the title if it is not blank and the id otherwise.
"""
| zopefoundation/Zope | a449b8cd38bb5d8c0ede7c259d58e18e2f06713e | diff --git a/src/OFS/tests/testSimpleItem.py b/src/OFS/tests/testSimpleItem.py
index de08de620..c1038c917 100644
--- a/src/OFS/tests/testSimpleItem.py
+++ b/src/OFS/tests/testSimpleItem.py
@@ -79,6 +79,17 @@ class TestItem_w__name__(unittest.TestCase):
verifyClass(IItemWithName, Item_w__name__)
+ def test_id(self):
+ from OFS.SimpleItem import Item_w__name__
+ itm = Item_w__name__()
+ # fall back to inherited `id`
+ self.assertEqual(itm.id, "")
+ itm.id = "id"
+ self.assertEqual(itm.id, "id")
+ del itm.id
+ itm._setId("name")
+ self.assertEqual(itm.id, "name")
+
class TestSimpleItem(unittest.TestCase):
| (Export/)Import broken for "OFS.SimpleItem.Item_w__name__" instances
## BUG/PROBLEM REPORT
If an instance of `OFS.SimpleItem.Item_w__name__` (e.g. an `OFS.Image.File` instance) is exported, a subsequent import fails with `BadRequest: ('Empty or invalid id specified', '')`.
The reason: for `Item_w__name__` instances, `id` must not be used (it is always `''`); for those instances `getId()` must be used to access the object's id.
`OFS.ObjectManager.ObjectManager._importObjectFromFile` violates this restriction.
### What version of Python and Zope/Addons I am using:
current Zope 4.x (likely Zope 5.x as well)
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"src/OFS/tests/testSimpleItem.py::TestItem_w__name__::test_id"
] | [
"src/OFS/tests/testSimpleItem.py::TestItem::test_conforms_to_IItem",
"src/OFS/tests/testSimpleItem.py::TestItem::test_conforms_to_IManageable",
"src/OFS/tests/testSimpleItem.py::TestItem::test_raise_StandardErrorMessage_TaintedString_errorValue",
"src/OFS/tests/testSimpleItem.py::TestItem::test_raise_StandardErrorMessage_str_errorValue",
"src/OFS/tests/testSimpleItem.py::TestItem_w__name__::test_interfaces",
"src/OFS/tests/testSimpleItem.py::TestSimpleItem::test_interfaces",
"src/OFS/tests/testSimpleItem.py::TestSimpleItem::test_standard_error_message_is_called",
"src/OFS/tests/testSimpleItem.py::TestSimpleItem::test_title_and_id_nonascii",
"src/OFS/tests/testSimpleItem.py::TestSimpleItem::test_title_or_id_nonascii"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2020-10-06T09:04:37Z" | zpl-2.1 |
|
zopefoundation__persistent-161 | diff --git a/CHANGES.rst b/CHANGES.rst
index 542e403..81a77a8 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -12,6 +12,10 @@
when setting its ``__class__`` and ``__dict__``. This matches the
behaviour of the C implementation. See `issue 155
<https://github.com/zopefoundation/persistent/issues/155>`_.
+- Fix the CFFI cache implementation (used on CPython when
+ ``PURE_PYTHON=1``) to not print unraisable ``AttributeErrors`` from
+ ``_WeakValueDictionary`` during garbage collection. See `issue 150
+ <https://github.com/zopefoundation/persistent/issues/150>`_.
4.6.4 (2020-03-26)
==================
diff --git a/persistent/picklecache.py b/persistent/picklecache.py
index 43d5067..3dde6c3 100644
--- a/persistent/picklecache.py
+++ b/persistent/picklecache.py
@@ -102,7 +102,13 @@ class _WeakValueDictionary(object):
return self._cast(addr, self._py_object).value
def cleanup_hook(self, cdata):
- oid = self._addr_to_oid.pop(cdata.pobj_id, None)
+ # This is called during GC, possibly at interpreter shutdown
+ # when the __dict__ of this object may have already been cleared.
+ try:
+ addr_to_oid = self._addr_to_oid
+ except AttributeError:
+ return
+ oid = addr_to_oid.pop(cdata.pobj_id, None)
self._data.pop(oid, None)
def __contains__(self, oid):
| zopefoundation/persistent | 6b500fc3f517fb566e8d0b85b756ddf49758c8d8 | diff --git a/persistent/tests/test_picklecache.py b/persistent/tests/test_picklecache.py
index 32811f1..9d6ec25 100644
--- a/persistent/tests/test_picklecache.py
+++ b/persistent/tests/test_picklecache.py
@@ -1102,6 +1102,44 @@ class PythonPickleCacheTests(PickleCacheTestMixin, unittest.TestCase):
self.assertEqual(cache.cache_non_ghost_count, 0)
self.assertEqual(len(cache), 0)
+ def test_interpreter_finalization_ffi_cleanup(self):
+ # When the interpreter is busy garbage collecting old objects
+ # and clearing their __dict__ in random orders, the CFFI cleanup
+ # ``ffi.gc()`` cleanup hooks we use on CPython don't
+ # raise errors.
+ #
+ # Prior to Python 3.8, when ``sys.unraisablehook`` was added,
+ # the only way to know if this test fails is to look for AttributeError
+ # on stderr.
+ #
+ # But wait, it gets worse. Prior to https://foss.heptapod.net/pypy/cffi/-/issues/492
+ # (CFFI > 1.14.5, unreleased at this writing), CFFI ignores
+ # ``sys.unraisablehook``, so even on 3.8 the only way to know
+ # a failure is to watch stderr.
+ #
+ # See https://github.com/zopefoundation/persistent/issues/150
+
+ import sys
+ unraised = []
+ try:
+ old_hook = sys.unraisablehook
+ except AttributeError:
+ pass
+ else: # pragma: no cover
+ sys.unraisablehook = unraised.append
+ self.addCleanup(setattr, sys, 'unraisablehook', old_hook)
+
+ cache = self._makeOne()
+ oid = self._numbered_oid(42)
+ o = cache[oid] = self._makePersist(oid=oid)
+ # Clear the dict, or at least part of it.
+ # This is coupled to ``cleanup_hook``
+ if cache.data.cleanup_hook:
+ del cache.data._addr_to_oid
+ del cache[oid]
+
+ self.assertEqual(unraised, [])
+
@skipIfNoCExtension
class CPickleCacheTests(PickleCacheTestMixin, unittest.TestCase):
@@ -1182,6 +1220,30 @@ class CPickleCacheTests(PickleCacheTestMixin, unittest.TestCase):
self.assertEqual(len(cache), 0)
+class TestWeakValueDictionary(unittest.TestCase):
+
+ def _getTargetClass(self):
+ from persistent.picklecache import _WeakValueDictionary
+ return _WeakValueDictionary
+
+ def _makeOne(self):
+ return self._getTargetClass()()
+
+ @unittest.skipIf(PYPY, "PyPy doesn't have the cleanup_hook")
+ def test_cleanup_hook_gc(self):
+ # A more targeted test than ``test_interpreter_finalization_ffi_cleanup``
+ # See https://github.com/zopefoundation/persistent/issues/150
+ wvd = self._makeOne()
+
+ class cdata(object):
+ o = object()
+ pobj_id = id(o)
+ wvd['key'] = cdata.o
+
+ wvd.__dict__.clear()
+ wvd.cleanup_hook(cdata)
+
+
def test_suite():
return unittest.defaultTestLoader.loadTestsFromName(__name__)
| AttributeError: '_WeakValueDictionary' object has no attribute '_addr_to_oid'
Seen during test teardown of a large app using CPython in PURE_PYTHON=1 mode
```
From callback for ffi.gc <cdata 'struct CPersistentRingCFFI_struct *' owning 24 bytes>:
Traceback (most recent call last):
File "//persistent/persistent/picklecache.py", line 105, in cleanup_hook
oid = self._addr_to_oid.pop(cdata.pobj_id, None)
AttributeError: '_WeakValueDictionary' object has no attribute '_addr_to_oid'
```
This is ignored, and the dict is already gone, so there shouldn't be any harm, but it is annoying. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"persistent/tests/test_picklecache.py::TestWeakValueDictionary::test_cleanup_hook_gc"
] | [
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test___delitem___non_string_oid_raises_TypeError",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test___delitem___nonesuch_raises_KeyError",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test___delitem___w_ghost",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test___delitem___w_normal_object",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test___delitem___w_persistent_class",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test___delitem___w_remaining_object",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test___getitem___nonesuch_raises_KeyError",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test___setitem___duplicate_oid_raises_ValueError",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test___setitem___duplicate_oid_same_obj",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test___setitem___ghost",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test___setitem___mismatch_key_oid",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test___setitem___non_ghost",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test___setitem___non_string_oid_raises_TypeError",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test___setitem___persistent_class",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_cache_garbage_collection_bytes_also_deactivates_object",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_cache_garbage_collection_bytes_with_cache_size_0",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_cache_raw",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_cache_size",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_cannot_update_mru_while_already_locked",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_class_conforms_to_IPickleCache",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_debug_info_w_ghost",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_debug_info_w_normal_object",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_debug_info_w_persistent_class",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_empty",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_full_sweep",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_full_sweep_w_changed",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_full_sweep_w_sticky",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_get_nonesuch_no_default",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_get_nonesuch_w_default",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_incrgc_simple",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_incrgc_w_larger_drain_resistance",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_incrgc_w_smaller_drain_resistance",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_init_with_cacheless_jar",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_instance_conforms_to_IPickleCache",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_interpreter_finalization_ffi_cleanup",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_invalidate_hit_multiple_mixed",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_invalidate_hit_multiple_non_ghost",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_invalidate_hit_pclass",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_invalidate_hit_single_ghost",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_invalidate_hit_single_non_ghost",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_invalidate_miss_multiple",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_invalidate_miss_single",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_invalidate_persistent_class_calls_p_invalidate",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_lruitems",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_minimize",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_minimize_turns_into_ghosts",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_mru_first",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_mru_ghost",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_mru_last",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_mru_nonesuch_raises_KeyError",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_mru_normal",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_mru_was_ghost_now_active",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_new_ghost_non_persistent_object",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_new_ghost_obj_already_has_jar",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_new_ghost_obj_already_has_oid",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_new_ghost_obj_already_in_cache",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_new_ghost_success_already_ghost",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_new_ghost_success_not_already_ghost",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_new_ghost_w_pclass_ghost",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_new_ghost_w_pclass_non_ghost",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_reify_hit_multiple_mixed",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_reify_hit_single_ghost",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_reify_hit_single_non_ghost",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_reify_miss_multiple",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_reify_miss_single",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_setting_already_cached",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_setting_non_persistent_item",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_setting_without_jar",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_sweep_empty",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_sweep_of_non_deactivating_object",
"persistent/tests/test_picklecache.py::PythonPickleCacheTests::test_update_object_size_estimation_simple",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test___delitem___non_string_oid_raises_TypeError",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test___delitem___nonesuch_raises_KeyError",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test___delitem___w_ghost",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test___delitem___w_normal_object",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test___delitem___w_persistent_class",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test___delitem___w_remaining_object",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test___getitem___nonesuch_raises_KeyError",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test___setitem___duplicate_oid_raises_ValueError",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test___setitem___duplicate_oid_same_obj",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test___setitem___ghost",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test___setitem___mismatch_key_oid",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test___setitem___non_ghost",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test___setitem___non_string_oid_raises_TypeError",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test___setitem___persistent_class",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_cache_garbage_collection_bytes_with_cache_size_0",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_cache_raw",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_cache_size",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_class_conforms_to_IPickleCache",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_debug_info_w_ghost",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_debug_info_w_normal_object",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_debug_info_w_persistent_class",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_empty",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_full_sweep",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_get_nonesuch_no_default",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_get_nonesuch_w_default",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_incrgc_simple",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_incrgc_w_larger_drain_resistance",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_incrgc_w_smaller_drain_resistance",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_inst_does_not_conform_to_IExtendedPickleCache",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_instance_conforms_to_IPickleCache",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_invalidate_hit_multiple_non_ghost",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_invalidate_hit_single_non_ghost",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_invalidate_miss_multiple",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_invalidate_miss_single",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_invalidate_persistent_class_calls_p_invalidate",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_lruitems",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_minimize",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_minimize_turns_into_ghosts",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_new_ghost_non_persistent_object",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_new_ghost_obj_already_has_jar",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_new_ghost_obj_already_has_oid",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_new_ghost_obj_already_in_cache",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_new_ghost_success_already_ghost",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_new_ghost_success_not_already_ghost",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_new_ghost_w_pclass_ghost",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_new_ghost_w_pclass_non_ghost",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_setting_already_cached",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_setting_non_persistent_item",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_setting_without_jar",
"persistent/tests/test_picklecache.py::CPickleCacheTests::test_sweep_empty",
"persistent/tests/test_picklecache.py::test_suite"
] | {
"failed_lite_validators": [
"has_many_modified_files"
],
"has_test_patch": true,
"is_lite": false
} | "2021-03-10T14:52:25Z" | zpl-2.1 |
|
zopefoundation__persistent-83 | diff --git a/CHANGES.rst b/CHANGES.rst
index 956c0a5..02823d6 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -37,6 +37,15 @@
- Remove some internal compatibility shims that are no longer
necessary. See `PR 82 <https://github.com/zopefoundation/persistent/pull/82>`_.
+- Make the return value of ``TimeStamp.second()`` consistent across C
+ and Python implementations when the ``TimeStamp`` was created from 6
+ arguments with floating point seconds. Also make it match across
+ trips through ``TimeStamp.raw()``. Previously, the C version could
+ initially have erroneous rounding and too much false precision,
+ while the Python version could have too much precision. The raw/repr
+ values have not changed. See `issue 41
+ <https://github.com/zopefoundation/persistent/issues/41>`_.
+
4.3.0 (2018-07-30)
------------------
diff --git a/persistent/timestamp.py b/persistent/timestamp.py
index 5da8535..a031a72 100644
--- a/persistent/timestamp.py
+++ b/persistent/timestamp.py
@@ -53,6 +53,7 @@ class _UTC(datetime.tzinfo):
return dt
def _makeUTC(y, mo, d, h, mi, s):
+ s = round(s, 6) # microsecond precision, to match the C implementation
usec, sec = math.modf(s)
sec = int(sec)
usec = int(usec * 1e6)
@@ -75,7 +76,7 @@ def _parseRaw(octets):
day = a // (60 * 24) % 31 + 1
month = a // (60 * 24 * 31) % 12 + 1
year = a // (60 * 24 * 31 * 12) + 1900
- second = round(b * _SCONV, 6) #microsecond precision
+ second = b * _SCONV
return (year, month, day, hour, minute, second)
@@ -83,6 +84,7 @@ class pyTimeStamp(object):
__slots__ = ('_raw', '_elements')
def __init__(self, *args):
+ self._elements = None
if len(args) == 1:
raw = args[0]
if not isinstance(raw, _RAWTYPE):
@@ -90,14 +92,18 @@ class pyTimeStamp(object):
if len(raw) != 8:
raise TypeError('Raw must be 8 octets')
self._raw = raw
- self._elements = _parseRaw(raw)
elif len(args) == 6:
self._raw = _makeRaw(*args)
- self._elements = args
+ # Note that we don't preserve the incoming arguments in self._elements,
+ # we derive them from the raw value. This is because the incoming
+ # seconds value could have more precision than would survive
+ # in the raw data, so we must be consistent.
else:
raise TypeError('Pass either a single 8-octet arg '
'or 5 integers and a float')
+ self._elements = _parseRaw(self._raw)
+
def raw(self):
return self._raw
| zopefoundation/persistent | aa6048a342d91656f3d1be6ff04bd1815e191a04 | diff --git a/persistent/tests/test_timestamp.py b/persistent/tests/test_timestamp.py
index cc1253c..ff8b6a9 100644
--- a/persistent/tests/test_timestamp.py
+++ b/persistent/tests/test_timestamp.py
@@ -17,6 +17,8 @@ import sys
MAX_32_BITS = 2 ** 31 - 1
MAX_64_BITS = 2 ** 63 - 1
+import persistent.timestamp
+
class Test__UTC(unittest.TestCase):
def _getTargetClass(self):
@@ -202,7 +204,8 @@ class TimeStampTests(pyTimeStampTests):
from persistent.timestamp import TimeStamp
return TimeStamp
-
[email protected](persistent.timestamp.CTimeStamp is None,
+ "CTimeStamp not available")
class PyAndCComparisonTests(unittest.TestCase):
"""
Compares C and Python implementations.
@@ -254,7 +257,6 @@ class PyAndCComparisonTests(unittest.TestCase):
def test_equal(self):
c, py = self._make_C_and_Py(*self.now_ts_args)
-
self.assertEqual(c, py)
def test_hash_equal(self):
@@ -396,22 +398,32 @@ class PyAndCComparisonTests(unittest.TestCase):
self.assertTrue(big_c != small_py)
self.assertTrue(small_py != big_c)
+ def test_seconds_precision(self, seconds=6.123456789):
+ # https://github.com/zopefoundation/persistent/issues/41
+ args = (2001, 2, 3, 4, 5, seconds)
+ c = self._makeC(*args)
+ py = self._makePy(*args)
-def test_suite():
- suite = [
- unittest.makeSuite(Test__UTC),
- unittest.makeSuite(pyTimeStampTests),
- unittest.makeSuite(TimeStampTests),
- ]
+ self.assertEqual(c, py)
+ self.assertEqual(c.second(), py.second())
+
+ py2 = self._makePy(c.raw())
+ self.assertEqual(py2, c)
+
+ c2 = self._makeC(c.raw())
+ self.assertEqual(c2, c)
+
+ def test_seconds_precision_half(self):
+ # make sure our rounding matches
+ self.test_seconds_precision(seconds=6.5)
+ self.test_seconds_precision(seconds=6.55)
+ self.test_seconds_precision(seconds=6.555)
+ self.test_seconds_precision(seconds=6.5555)
+ self.test_seconds_precision(seconds=6.55555)
+ self.test_seconds_precision(seconds=6.555555)
+ self.test_seconds_precision(seconds=6.5555555)
+ self.test_seconds_precision(seconds=6.55555555)
+ self.test_seconds_precision(seconds=6.555555555)
- try:
- from persistent.timestamp import pyTimeStamp
- from persistent.timestamp import TimeStamp
- except ImportError: # pragma: no cover
- pass
- else:
- if pyTimeStamp != TimeStamp:
- # We have both implementations available
- suite.append(unittest.makeSuite(PyAndCComparisonTests))
-
- return unittest.TestSuite(suite)
+def test_suite():
+ return unittest.defaultTestLoader.loadTestsFromName(__name__)
| pyTimeStamp and TimeStamp have different sub-second precision
I don't think this is correct:
```
>>> from persistent.timestamp import TimeStamp, pyTimeStamp
>>> ts1 = TimeStamp(2001, 2, 3, 4, 5, 6.123456789)
>>> ts2 = pyTimeStamp(2001, 2, 3, 4, 5, 6.123456789)
>>> ts1 == ts2
True
>>> ts1.second() == ts2.second()
False
>>> ts1.second()
6.1234567780047655
>>> ts2.second()
6.123456789
```
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"persistent/tests/test_timestamp.py::PyAndCComparisonTests::test_seconds_precision",
"persistent/tests/test_timestamp.py::PyAndCComparisonTests::test_seconds_precision_half"
] | [
"persistent/tests/test_timestamp.py::Test__UTC::test_dst",
"persistent/tests/test_timestamp.py::Test__UTC::test_fromutc",
"persistent/tests/test_timestamp.py::Test__UTC::test_tzname",
"persistent/tests/test_timestamp.py::Test__UTC::test_utcoffset",
"persistent/tests/test_timestamp.py::pyTimeStampTests::test_comparisons_to_non_timestamps",
"persistent/tests/test_timestamp.py::pyTimeStampTests::test_ctor_from_elements",
"persistent/tests/test_timestamp.py::pyTimeStampTests::test_ctor_from_invalid_strings",
"persistent/tests/test_timestamp.py::pyTimeStampTests::test_ctor_from_string",
"persistent/tests/test_timestamp.py::pyTimeStampTests::test_ctor_from_string_non_zero",
"persistent/tests/test_timestamp.py::pyTimeStampTests::test_ctor_invalid_arglist",
"persistent/tests/test_timestamp.py::pyTimeStampTests::test_laterThan_invalid",
"persistent/tests/test_timestamp.py::pyTimeStampTests::test_laterThan_self_is_earlier",
"persistent/tests/test_timestamp.py::pyTimeStampTests::test_laterThan_self_is_later",
"persistent/tests/test_timestamp.py::pyTimeStampTests::test_repr",
"persistent/tests/test_timestamp.py::TimeStampTests::test_comparisons_to_non_timestamps",
"persistent/tests/test_timestamp.py::TimeStampTests::test_ctor_from_elements",
"persistent/tests/test_timestamp.py::TimeStampTests::test_ctor_from_invalid_strings",
"persistent/tests/test_timestamp.py::TimeStampTests::test_ctor_from_string",
"persistent/tests/test_timestamp.py::TimeStampTests::test_ctor_from_string_non_zero",
"persistent/tests/test_timestamp.py::TimeStampTests::test_ctor_invalid_arglist",
"persistent/tests/test_timestamp.py::TimeStampTests::test_laterThan_invalid",
"persistent/tests/test_timestamp.py::TimeStampTests::test_laterThan_self_is_earlier",
"persistent/tests/test_timestamp.py::TimeStampTests::test_laterThan_self_is_later",
"persistent/tests/test_timestamp.py::TimeStampTests::test_repr",
"persistent/tests/test_timestamp.py::PyAndCComparisonTests::test_equal",
"persistent/tests/test_timestamp.py::PyAndCComparisonTests::test_hash_equal",
"persistent/tests/test_timestamp.py::PyAndCComparisonTests::test_hash_equal_constants",
"persistent/tests/test_timestamp.py::PyAndCComparisonTests::test_ordering",
"persistent/tests/test_timestamp.py::PyAndCComparisonTests::test_py_hash_32_64_bit",
"persistent/tests/test_timestamp.py::PyAndCComparisonTests::test_raw_equal",
"persistent/tests/test_timestamp.py::PyAndCComparisonTests::test_reprs_equal",
"persistent/tests/test_timestamp.py::test_suite"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2018-08-01T20:06:48Z" | zpl-2.1 |
|
zopefoundation__transaction-24 | diff --git a/CHANGES.rst b/CHANGES.rst
index 32b7510..b976f79 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -4,6 +4,9 @@ Changes
Unreleased
----------
+- Fixed the transaction manager ``attempts`` method. It didn't stop
+ repeating when there wasn't an error.
+
- Corrected ITransaction by removing beforeCommitHook (which is no longer
implemented) and removing 'self' from two methods.
diff --git a/buildout.cfg b/buildout.cfg
index fe65737..0fd0713 100644
--- a/buildout.cfg
+++ b/buildout.cfg
@@ -1,6 +1,6 @@
[buildout]
develop = .
-parts = py
+parts = py sphinx
[test]
recipe = zc.recipe.testrunner
@@ -10,3 +10,10 @@ eggs = transaction [test]
recipe = zc.recipe.egg
eggs = ${test:eggs}
interpreter = py
+
+[sphinx]
+recipe = zc.recipe.egg
+eggs =
+ transaction
+ sphinx
+ repoze.sphinx.autointerface
diff --git a/docs/convenience.rst b/docs/convenience.rst
index cb1c1ff..bfc3cc3 100644
--- a/docs/convenience.rst
+++ b/docs/convenience.rst
@@ -125,7 +125,7 @@ Of course, other errors are propagated directly:
>>> for attempt in transaction.manager.attempts():
... with attempt:
... ntry += 1
- ... if ntry == 3:
+ ... if ntry % 3:
... raise ValueError(ntry)
Traceback (most recent call last):
...
@@ -135,6 +135,7 @@ We can use the default transaction manager:
.. doctest::
+ >>> ntry = 0
>>> for attempt in transaction.attempts():
... with attempt as t:
... t.note('test')
@@ -143,9 +144,9 @@ We can use the default transaction manager:
... dm['ntry'] = ntry
... if ntry % 3:
... raise Retry(ntry)
- 3 3
- 3 4
- 3 5
+ 3 0
+ 3 1
+ 3 2
Sometimes, a data manager doesn't raise exceptions directly, but
wraps other other systems that raise exceptions outside of it's
@@ -172,9 +173,9 @@ attempted again.
... dm2['ntry'] = ntry
... if ntry % 3:
... raise ValueError('we really should retry this')
- 6 0
- 6 1
- 6 2
+ 3 0
+ 3 1
+ 3 2
>>> dm2['ntry']
3
diff --git a/transaction/_manager.py b/transaction/_manager.py
index 8f642ba..b4bfbe3 100644
--- a/transaction/_manager.py
+++ b/transaction/_manager.py
@@ -144,7 +144,10 @@ class TransactionManager(object):
while number:
number -= 1
if number:
- yield Attempt(self)
+ attempt = Attempt(self)
+ yield attempt
+ if attempt.success:
+ break
else:
yield self
@@ -167,6 +170,8 @@ class ThreadTransactionManager(TransactionManager, threading.local):
class Attempt(object):
+ success = False
+
def __init__(self, manager):
self.manager = manager
@@ -186,5 +191,7 @@ class Attempt(object):
self.manager.commit()
except:
return self._retry_or_raise(*sys.exc_info())
+ else:
+ self.success = True
else:
return self._retry_or_raise(t, v, tb)
| zopefoundation/transaction | efd6988269d90c71b5db1aa70263b4a9a60f27dd | diff --git a/transaction/tests/test__manager.py b/transaction/tests/test__manager.py
index 8db9ca4..8ec9a04 100644
--- a/transaction/tests/test__manager.py
+++ b/transaction/tests/test__manager.py
@@ -236,6 +236,16 @@ class TransactionManagerTests(unittest.TestCase):
self.assertEqual(len(found), 1)
self.assertTrue(found[0] is tm)
+ def test_attempts_stop_on_success(self):
+ tm = self._makeOne()
+
+ i = 0
+ for attempt in tm.attempts():
+ with attempt:
+ i += 1
+
+ self.assertEqual(i, 1)
+
def test_attempts_w_default_count(self):
from transaction._manager import Attempt
tm = self._makeOne()
| Attemps are retried on successful run
I'm not sure if this is a bug or intended behavior. But the attempts function does work as described in the example code in the [documents](http://transaction.readthedocs.io/en/latest/convenience.html#retries):
```
for i in range(3):
try:
with transaction.manager:
... some something ...
except SomeTransientException:
contine
else:
break
```
Instead it works as:
```
for i in range(3):
try:
with transaction.manager:
... some something ...
except SomeTransientException:
contine
```
A successful attempt will just try again, as shown in the following:
```
import transaction.tests.savepointsample
import transaction
dm = transaction.tests.savepointsample.SampleSavepointDataManager()
with transaction.manager:
dm['ntry'] = 0
ntry = 0
import transaction.interfaces
class Retry(transaction.interfaces.TransientError):
pass
for attempt in transaction.manager.attempts(6):
with attempt as t:
t.note('test')
print("%s %s" % (dm['ntry'], ntry))
ntry += 1
dm['ntry'] = ntry
if ntry % 3:
raise Retry(ntry)
print('current ntry: %s' % dm['ntry'])
```
The result:
```
0 0
0 1
0 2
3 3
3 4
3 5
current ntry 6
```
While if the documentation is to be believed I'd expect a result as follows:
```
0 0
0 1
0 2
current ntry 3
```
Thus my question is really what is correct, the documentation or the implementation?
| 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"transaction/tests/test__manager.py::TransactionManagerTests::test_attempts_stop_on_success"
] | [
"transaction/tests/test__manager.py::TransactionManagerTests::test__retryable_w_multiple",
"transaction/tests/test__manager.py::TransactionManagerTests::test__retryable_w_normal_exception_no_resources",
"transaction/tests/test__manager.py::TransactionManagerTests::test__retryable_w_normal_exception_w_resource_voting_yes",
"transaction/tests/test__manager.py::TransactionManagerTests::test__retryable_w_transient_error",
"transaction/tests/test__manager.py::TransactionManagerTests::test__retryable_w_transient_subclass",
"transaction/tests/test__manager.py::TransactionManagerTests::test_abort_normal",
"transaction/tests/test__manager.py::TransactionManagerTests::test_abort_w_broken_jar",
"transaction/tests/test__manager.py::TransactionManagerTests::test_abort_w_existing_txn",
"transaction/tests/test__manager.py::TransactionManagerTests::test_abort_w_nonsub_jar",
"transaction/tests/test__manager.py::TransactionManagerTests::test_as_context_manager_w_error",
"transaction/tests/test__manager.py::TransactionManagerTests::test_as_context_manager_wo_error",
"transaction/tests/test__manager.py::TransactionManagerTests::test_attempts_w_default_count",
"transaction/tests/test__manager.py::TransactionManagerTests::test_attempts_w_invalid_count",
"transaction/tests/test__manager.py::TransactionManagerTests::test_attempts_w_valid_count",
"transaction/tests/test__manager.py::TransactionManagerTests::test_begin_w_existing_txn",
"transaction/tests/test__manager.py::TransactionManagerTests::test_begin_wo_existing_txn_w_synchs",
"transaction/tests/test__manager.py::TransactionManagerTests::test_begin_wo_existing_txn_wo_synchs",
"transaction/tests/test__manager.py::TransactionManagerTests::test_clearSynchs",
"transaction/tests/test__manager.py::TransactionManagerTests::test_commit_normal",
"transaction/tests/test__manager.py::TransactionManagerTests::test_commit_w_broken_jar_commit",
"transaction/tests/test__manager.py::TransactionManagerTests::test_commit_w_broken_jar_tpc_abort_tpc_vote",
"transaction/tests/test__manager.py::TransactionManagerTests::test_commit_w_broken_jar_tpc_begin",
"transaction/tests/test__manager.py::TransactionManagerTests::test_commit_w_broken_jar_tpc_vote",
"transaction/tests/test__manager.py::TransactionManagerTests::test_commit_w_existing_txn",
"transaction/tests/test__manager.py::TransactionManagerTests::test_commit_w_nonsub_jar",
"transaction/tests/test__manager.py::TransactionManagerTests::test_ctor",
"transaction/tests/test__manager.py::TransactionManagerTests::test_doom",
"transaction/tests/test__manager.py::TransactionManagerTests::test_free_w_existing_txn",
"transaction/tests/test__manager.py::TransactionManagerTests::test_free_w_other_txn",
"transaction/tests/test__manager.py::TransactionManagerTests::test_get_w_existing_txn",
"transaction/tests/test__manager.py::TransactionManagerTests::test_get_wo_existing_txn",
"transaction/tests/test__manager.py::TransactionManagerTests::test_isDoomed_w_existing_txn",
"transaction/tests/test__manager.py::TransactionManagerTests::test_isDoomed_wo_existing_txn",
"transaction/tests/test__manager.py::TransactionManagerTests::test_notify_transaction_late_comers",
"transaction/tests/test__manager.py::TransactionManagerTests::test_registerSynch",
"transaction/tests/test__manager.py::TransactionManagerTests::test_savepoint_default",
"transaction/tests/test__manager.py::TransactionManagerTests::test_savepoint_explicit",
"transaction/tests/test__manager.py::TransactionManagerTests::test_unregisterSynch",
"transaction/tests/test__manager.py::AttemptTests::test___enter__",
"transaction/tests/test__manager.py::AttemptTests::test___exit__no_exc_abort_exception_after_nonretryable_commit_exc",
"transaction/tests/test__manager.py::AttemptTests::test___exit__no_exc_no_commit_exception",
"transaction/tests/test__manager.py::AttemptTests::test___exit__no_exc_nonretryable_commit_exception",
"transaction/tests/test__manager.py::AttemptTests::test___exit__no_exc_retryable_commit_exception",
"transaction/tests/test__manager.py::AttemptTests::test___exit__with_exception_value_nonretryable",
"transaction/tests/test__manager.py::AttemptTests::test___exit__with_exception_value_retryable",
"transaction/tests/test__manager.py::test_suite"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2016-11-07T15:52:31Z" | zpl-2.1 |
|
zopefoundation__transaction-28 | diff --git a/CHANGES.rst b/CHANGES.rst
index 7569466..4a1e878 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -1,6 +1,29 @@
Changes
=======
+2.0.0 (unreleased)
+------------------
+
+- The transaction ``user`` and ``description`` attributes are now
+ defined to be text (unicode) as apposed to Python the ``str`` type.
+
+- Added the ``extended_info`` transaction attribute which contains
+ transaction meta data. (The ``_extension`` attribute is retained as
+ an alias for backward compatibility.)
+
+ The transaction interface, ``ITransaction``, now requires
+ ``extended_info`` keys to be text (unicode) and values to be
+ JSON-serializable.
+
+- Removed setUser from ITransaction. We'll keep the method
+ undefinately, but it's unseemly in ITransaction. :)
+
+The main purpose of these changes is to tighten up the text
+specification of user, description and extended_info keys, and to give
+us more flexibility in the future for serializing extended info. It's
+possible that these changes will be breaking, so we're also increasing
+the major version number.
+
1.7.0 (2016-11-08)
------------------
diff --git a/transaction/_transaction.py b/transaction/_transaction.py
index fd4122e..3aa2050 100644
--- a/transaction/_transaction.py
+++ b/transaction/_transaction.py
@@ -76,10 +76,10 @@ class Transaction(object):
# savepoint to its index (see above).
_savepoint2index = None
- # Meta data. ._extension is also metadata, but is initialized to an
+ # Meta data. extended_info is also metadata, but is initialized to an
# emtpy dict in __init__.
- user = ""
- description = ""
+ _user = u""
+ _description = u""
def __init__(self, synchronizers=None, manager=None):
self.status = Status.ACTIVE
@@ -100,9 +100,9 @@ class Transaction(object):
# manager as a key, because we can't guess whether the actual
# resource managers will be safe to use as dict keys.
- # The user, description, and _extension attributes are accessed
+ # The user, description, and extended_info attributes are accessed
# directly by storages, leading underscore notwithstanding.
- self._extension = {}
+ self.extended_info = {}
self.log = _makeLogger()
self.log.debug("new transaction")
@@ -118,6 +118,28 @@ class Transaction(object):
# List of (hook, args, kws) tuples added by addAfterCommitHook().
self._after_commit = []
+ @property
+ def _extension(self):
+ # for backward compatibility, since most clients used this
+ # absent any formal API.
+ return self.extended_info
+
+ @property
+ def user(self):
+ return self._user
+
+ @user.setter
+ def user(self, v):
+ self._user = v + u'' # + u'' to make sure it's unicode
+
+ @property
+ def description(self):
+ return self._description
+
+ @description.setter
+ def description(self, v):
+ self._description = v + u'' # + u'' to make sure it's unicode
+
def isDoomed(self):
""" See ITransaction.
"""
@@ -504,19 +526,19 @@ class Transaction(object):
"""
text = text.strip()
if self.description:
- self.description += "\n" + text
+ self.description += u"\n" + text
else:
self.description = text
def setUser(self, user_name, path="/"):
""" See ITransaction.
"""
- self.user = "%s %s" % (path, user_name)
+ self.user = u"%s %s" % (path, user_name)
def setExtendedInfo(self, name, value):
""" See ITransaction.
"""
- self._extension[name] = value
+ self.extended_info[name + u''] = value # + u'' to make sure it's unicode
# TODO: We need a better name for the adapters.
diff --git a/transaction/interfaces.py b/transaction/interfaces.py
index 52798fa..c7be269 100644
--- a/transaction/interfaces.py
+++ b/transaction/interfaces.py
@@ -105,7 +105,7 @@ class ITransaction(Interface):
"""A user name associated with the transaction.
The format of the user name is defined by the application. The value
- is of Python type str. Storages record the user value, as meta-data,
+ is text (unicode). Storages record the user value, as meta-data,
when a transaction commits.
A storage may impose a limit on the size of the value; behavior is
@@ -116,7 +116,7 @@ class ITransaction(Interface):
description = Attribute(
"""A textual description of the transaction.
- The value is of Python type str. Method note() is the intended
+ The value is text (unicode). Method note() is the intended
way to set the value. Storages record the description, as meta-data,
when a transaction commits.
@@ -125,6 +125,13 @@ class ITransaction(Interface):
raise an exception, or truncate the value).
""")
+ extended_info = Attribute(
+ """A dictionary containing application-defined metadata.
+
+ Keys must be text (unicode). Values must be simple values
+ serializable with json or pickle (not instances).
+ """)
+
def commit():
"""Finalize the transaction.
@@ -167,7 +174,7 @@ class ITransaction(Interface):
"""
def note(text):
- """Add text to the transaction description.
+ """Add text (unicode) to the transaction description.
This modifies the `.description` attribute; see its docs for more
detail. First surrounding whitespace is stripped from `text`. If
@@ -176,21 +183,17 @@ class ITransaction(Interface):
appended to `.description`.
"""
- def setUser(user_name, path="/"):
- """Set the user name.
-
- path should be provided if needed to further qualify the
- identified user. This is a convenience method used by Zope.
- It sets the .user attribute to str(path) + " " + str(user_name).
- This sets the `.user` attribute; see its docs for more detail.
- """
-
def setExtendedInfo(name, value):
"""Add extension data to the transaction.
- name is the name of the extension property to set, of Python type
- str; value must be picklable. Multiple calls may be made to set
- multiple extension properties, provided the names are distinct.
+ name
+ is the text (unicode) name of the extension property to set
+
+ value
+ must be picklable and json serializable (not an instance).
+
+ Multiple calls may be made to set multiple extension
+ properties, provided the names are distinct.
Storages record the extension data, as meta-data, when a transaction
commits.
| zopefoundation/transaction | 085ab4fb0521127cd5428db9fd9fdcd3b8eaed10 | diff --git a/transaction/tests/test__transaction.py b/transaction/tests/test__transaction.py
index 4e63bb3..8fe8c68 100644
--- a/transaction/tests/test__transaction.py
+++ b/transaction/tests/test__transaction.py
@@ -69,14 +69,15 @@ class TransactionTests(unittest.TestCase):
self.assertTrue(isinstance(txn._synchronizers, WeakSet))
self.assertEqual(len(txn._synchronizers), 0)
self.assertTrue(txn._manager is None)
- self.assertEqual(txn.user, "")
- self.assertEqual(txn.description, "")
+ self.assertEqual(txn.user, u"")
+ self.assertEqual(txn.description, u"")
self.assertTrue(txn._savepoint2index is None)
self.assertEqual(txn._savepoint_index, 0)
self.assertEqual(txn._resources, [])
self.assertEqual(txn._adapters, {})
self.assertEqual(txn._voted, {})
- self.assertEqual(txn._extension, {})
+ self.assertEqual(txn.extended_info, {})
+ self.assertTrue(txn._extension is txn.extended_info) # legacy
self.assertTrue(txn.log is logger)
self.assertEqual(len(logger._log), 1)
self.assertEqual(logger._log[0][0], 'debug')
@@ -983,33 +984,45 @@ class TransactionTests(unittest.TestCase):
txn = self._makeOne()
try:
txn.note('This is a note.')
- self.assertEqual(txn.description, 'This is a note.')
+ self.assertEqual(txn.description, u'This is a note.')
txn.note('Another.')
- self.assertEqual(txn.description, 'This is a note.\nAnother.')
+ self.assertEqual(txn.description, u'This is a note.\nAnother.')
finally:
txn.abort()
+ def test_description_nonascii_bytes(self):
+ txn = self._makeOne()
+ with self.assertRaises((UnicodeDecodeError, TypeError)):
+ txn.description = b'\xc2\x80'
+
def test_setUser_default_path(self):
txn = self._makeOne()
txn.setUser('phreddy')
- self.assertEqual(txn.user, '/ phreddy')
+ self.assertEqual(txn.user, u'/ phreddy')
def test_setUser_explicit_path(self):
txn = self._makeOne()
txn.setUser('phreddy', '/bedrock')
- self.assertEqual(txn.user, '/bedrock phreddy')
+ self.assertEqual(txn.user, u'/bedrock phreddy')
+
+ def test_user_nonascii_bytes(self):
+ txn = self._makeOne()
+ with self.assertRaises((UnicodeDecodeError, TypeError)):
+ txn.user = b'\xc2\x80'
def test_setExtendedInfo_single(self):
txn = self._makeOne()
txn.setExtendedInfo('frob', 'qux')
- self.assertEqual(txn._extension, {'frob': 'qux'})
+ self.assertEqual(txn.extended_info, {u'frob': 'qux'})
+ self.assertTrue(txn._extension is txn._extension) # legacy
def test_setExtendedInfo_multiple(self):
txn = self._makeOne()
txn.setExtendedInfo('frob', 'qux')
txn.setExtendedInfo('baz', 'spam')
txn.setExtendedInfo('frob', 'quxxxx')
- self.assertEqual(txn._extension, {'frob': 'quxxxx', 'baz': 'spam'})
+ self.assertEqual(txn._extension, {u'frob': 'quxxxx', u'baz': 'spam'})
+ self.assertTrue(txn._extension is txn._extension) # legacy
def test_data(self):
txn = self._makeOne()
| Define transaction description and user to be unicode
See:
https://groups.google.com/forum/#!topic/python-transaction/Yn326XwCZ5E | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"transaction/tests/test__transaction.py::TransactionTests::test_ctor_defaults",
"transaction/tests/test__transaction.py::TransactionTests::test_description_nonascii_bytes",
"transaction/tests/test__transaction.py::TransactionTests::test_setExtendedInfo_single",
"transaction/tests/test__transaction.py::TransactionTests::test_user_nonascii_bytes"
] | [
"transaction/tests/test__transaction.py::TransactionTests::test__commitResources_error_in_afterCompletion",
"transaction/tests/test__transaction.py::TransactionTests::test__commitResources_error_in_commit",
"transaction/tests/test__transaction.py::TransactionTests::test__commitResources_error_in_tpc_begin",
"transaction/tests/test__transaction.py::TransactionTests::test__commitResources_error_in_tpc_finish",
"transaction/tests/test__transaction.py::TransactionTests::test__commitResources_error_in_tpc_vote",
"transaction/tests/test__transaction.py::TransactionTests::test__commitResources_normal",
"transaction/tests/test__transaction.py::TransactionTests::test__invalidate_all_savepoints",
"transaction/tests/test__transaction.py::TransactionTests::test__prior_operation_failed",
"transaction/tests/test__transaction.py::TransactionTests::test__remove_and_invalidate_after_hit",
"transaction/tests/test__transaction.py::TransactionTests::test__remove_and_invalidate_after_miss",
"transaction/tests/test__transaction.py::TransactionTests::test__unjoin_hit",
"transaction/tests/test__transaction.py::TransactionTests::test__unjoin_miss",
"transaction/tests/test__transaction.py::TransactionTests::test_abort_clears_resources",
"transaction/tests/test__transaction.py::TransactionTests::test_abort_error_w_afterCompleteHooks",
"transaction/tests/test__transaction.py::TransactionTests::test_abort_error_w_synchronizers",
"transaction/tests/test__transaction.py::TransactionTests::test_abort_w_afterCommitHooks",
"transaction/tests/test__transaction.py::TransactionTests::test_abort_w_beforeCommitHooks",
"transaction/tests/test__transaction.py::TransactionTests::test_abort_w_savepoints",
"transaction/tests/test__transaction.py::TransactionTests::test_abort_w_synchronizers",
"transaction/tests/test__transaction.py::TransactionTests::test_abort_wo_savepoints_wo_hooks_wo_synchronizers",
"transaction/tests/test__transaction.py::TransactionTests::test_addAfterCommitHook",
"transaction/tests/test__transaction.py::TransactionTests::test_addAfterCommitHook_wo_kws",
"transaction/tests/test__transaction.py::TransactionTests::test_addBeforeCommitHook",
"transaction/tests/test__transaction.py::TransactionTests::test_addBeforeCommitHook_w_kws",
"transaction/tests/test__transaction.py::TransactionTests::test_callAfterCommitHook_w_abort",
"transaction/tests/test__transaction.py::TransactionTests::test_callAfterCommitHook_w_error",
"transaction/tests/test__transaction.py::TransactionTests::test_commit_COMMITFAILED",
"transaction/tests/test__transaction.py::TransactionTests::test_commit_DOOMED",
"transaction/tests/test__transaction.py::TransactionTests::test_commit_clears_resources",
"transaction/tests/test__transaction.py::TransactionTests::test_commit_error_w_afterCompleteHooks",
"transaction/tests/test__transaction.py::TransactionTests::test_commit_error_w_synchronizers",
"transaction/tests/test__transaction.py::TransactionTests::test_commit_w_afterCommitHooks",
"transaction/tests/test__transaction.py::TransactionTests::test_commit_w_beforeCommitHooks",
"transaction/tests/test__transaction.py::TransactionTests::test_commit_w_savepoints",
"transaction/tests/test__transaction.py::TransactionTests::test_commit_w_synchronizers",
"transaction/tests/test__transaction.py::TransactionTests::test_commit_wo_savepoints_wo_hooks_wo_synchronizers",
"transaction/tests/test__transaction.py::TransactionTests::test_ctor_w_syncs",
"transaction/tests/test__transaction.py::TransactionTests::test_data",
"transaction/tests/test__transaction.py::TransactionTests::test_doom_active",
"transaction/tests/test__transaction.py::TransactionTests::test_doom_already_doomed",
"transaction/tests/test__transaction.py::TransactionTests::test_doom_invalid",
"transaction/tests/test__transaction.py::TransactionTests::test_getAfterCommitHooks_empty",
"transaction/tests/test__transaction.py::TransactionTests::test_getBeforeCommitHooks_empty",
"transaction/tests/test__transaction.py::TransactionTests::test_isDoomed",
"transaction/tests/test__transaction.py::TransactionTests::test_join_ACTIVE_w_preparing_w_sp2index",
"transaction/tests/test__transaction.py::TransactionTests::test_join_COMMITFAILED",
"transaction/tests/test__transaction.py::TransactionTests::test_join_COMMITTED",
"transaction/tests/test__transaction.py::TransactionTests::test_join_COMMITTING",
"transaction/tests/test__transaction.py::TransactionTests::test_join_DOOMED_non_preparing_wo_sp2index",
"transaction/tests/test__transaction.py::TransactionTests::test_note",
"transaction/tests/test__transaction.py::TransactionTests::test_register_w_jar",
"transaction/tests/test__transaction.py::TransactionTests::test_register_w_jar_already_adapted",
"transaction/tests/test__transaction.py::TransactionTests::test_register_wo_jar",
"transaction/tests/test__transaction.py::TransactionTests::test_savepoint_COMMITFAILED",
"transaction/tests/test__transaction.py::TransactionTests::test_savepoint_empty",
"transaction/tests/test__transaction.py::TransactionTests::test_savepoint_non_optimistc_resource_wo_support",
"transaction/tests/test__transaction.py::TransactionTests::test_setExtendedInfo_multiple",
"transaction/tests/test__transaction.py::TransactionTests::test_setUser_default_path",
"transaction/tests/test__transaction.py::TransactionTests::test_setUser_explicit_path",
"transaction/tests/test__transaction.py::TransactionTests::test_verifyImplements_ITransaction",
"transaction/tests/test__transaction.py::TransactionTests::test_verifyProvides_ITransaction",
"transaction/tests/test__transaction.py::MultiObjectResourceAdapterTests::test___repr__",
"transaction/tests/test__transaction.py::MultiObjectResourceAdapterTests::test_abort",
"transaction/tests/test__transaction.py::MultiObjectResourceAdapterTests::test_abort_w_error",
"transaction/tests/test__transaction.py::MultiObjectResourceAdapterTests::test_commit",
"transaction/tests/test__transaction.py::MultiObjectResourceAdapterTests::test_ctor",
"transaction/tests/test__transaction.py::MultiObjectResourceAdapterTests::test_sortKey",
"transaction/tests/test__transaction.py::MultiObjectResourceAdapterTests::test_tpc_abort",
"transaction/tests/test__transaction.py::MultiObjectResourceAdapterTests::test_tpc_begin",
"transaction/tests/test__transaction.py::MultiObjectResourceAdapterTests::test_tpc_finish",
"transaction/tests/test__transaction.py::MultiObjectResourceAdapterTests::test_tpc_vote",
"transaction/tests/test__transaction.py::Test_rm_key::test_hit",
"transaction/tests/test__transaction.py::Test_rm_key::test_miss",
"transaction/tests/test__transaction.py::Test_object_hint::test_hit",
"transaction/tests/test__transaction.py::Test_object_hint::test_miss",
"transaction/tests/test__transaction.py::Test_oid_repr::test_as_nonstring",
"transaction/tests/test__transaction.py::Test_oid_repr::test_as_string_all_Fs",
"transaction/tests/test__transaction.py::Test_oid_repr::test_as_string_not_8_chars",
"transaction/tests/test__transaction.py::Test_oid_repr::test_as_string_xxx",
"transaction/tests/test__transaction.py::Test_oid_repr::test_as_string_z64",
"transaction/tests/test__transaction.py::DataManagerAdapterTests::test_abort",
"transaction/tests/test__transaction.py::DataManagerAdapterTests::test_commit",
"transaction/tests/test__transaction.py::DataManagerAdapterTests::test_ctor",
"transaction/tests/test__transaction.py::DataManagerAdapterTests::test_sortKey",
"transaction/tests/test__transaction.py::DataManagerAdapterTests::test_tpc_abort",
"transaction/tests/test__transaction.py::DataManagerAdapterTests::test_tpc_begin",
"transaction/tests/test__transaction.py::DataManagerAdapterTests::test_tpc_finish",
"transaction/tests/test__transaction.py::DataManagerAdapterTests::test_tpc_vote",
"transaction/tests/test__transaction.py::SavepointTests::test_ctor_w_savepoint_aware_resources",
"transaction/tests/test__transaction.py::SavepointTests::test_ctor_w_savepoint_oblivious_resource_non_optimistic",
"transaction/tests/test__transaction.py::SavepointTests::test_ctor_w_savepoint_oblivious_resource_optimistic",
"transaction/tests/test__transaction.py::SavepointTests::test_rollback_w_sp_error",
"transaction/tests/test__transaction.py::SavepointTests::test_rollback_w_txn_None",
"transaction/tests/test__transaction.py::SavepointTests::test_valid_w_transacction",
"transaction/tests/test__transaction.py::SavepointTests::test_valid_wo_transacction",
"transaction/tests/test__transaction.py::AbortSavepointTests::test_ctor",
"transaction/tests/test__transaction.py::AbortSavepointTests::test_rollback",
"transaction/tests/test__transaction.py::NoRollbackSavepointTests::test_ctor",
"transaction/tests/test__transaction.py::NoRollbackSavepointTests::test_rollback",
"transaction/tests/test__transaction.py::MiscellaneousTests::test_BBB_join",
"transaction/tests/test__transaction.py::MiscellaneousTests::test_bug239086",
"transaction/tests/test__transaction.py::test_suite"
] | {
"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
} | "2016-11-11T17:20:00Z" | zpl-2.1 |
|
zulip__python-zulip-api-633 | diff --git a/zulip_botserver/README.md b/zulip_botserver/README.md
index 5efbbeaf..c16e0b1e 100644
--- a/zulip_botserver/README.md
+++ b/zulip_botserver/README.md
@@ -1,16 +1,29 @@
```
zulip-botserver --config-file <path to botserverrc> --hostname <address> --port <port>
-
```
Example: `zulip-botserver --config-file ~/botserverrc`
This program loads the bot configurations from the
-config file (botserverrc here) and loads the bot modules.
+config file (`botserverrc`, here) and loads the bot modules.
It then starts the server and fetches the requests to the
above loaded modules and returns the success/failure result.
-Please make sure you have a current botserverrc file with the
-configurations of the required bots.
-Hostname and Port are optional arguments. Default hostname is
-127.0.0.1 and default port is 5002.
+The `--hostname` and `--port` arguments are optional, and default to
+127.0.0.1 and 5002 respectively.
+
+The format for a configuration file is:
+
+ [helloworld]
+ key=value
+ [email protected]
+ site=http://localhost
+ token=abcd1234
+
+Is passed `--use-env-vars` instead of `--config-file`, the
+configuration can instead be provided via the `ZULIP_BOTSERVER_CONFIG`
+environment variable. This should be a JSON-formatted dictionary of
+bot names to dictionary of their configuration; for example:
+
+ ZULIP_BOTSERVER_CONFIG='{"helloworld":{"email":"[email protected]","key":"value","site":"http://localhost","token":"abcd1234"}}' \
+ zulip-botserver --use-env-vars
diff --git a/zulip_botserver/zulip_botserver/input_parameters.py b/zulip_botserver/zulip_botserver/input_parameters.py
index 2d6a2fe0..1b7d585a 100644
--- a/zulip_botserver/zulip_botserver/input_parameters.py
+++ b/zulip_botserver/zulip_botserver/input_parameters.py
@@ -7,13 +7,19 @@ def parse_args() -> argparse.Namespace:
'''
parser = argparse.ArgumentParser(usage=usage)
- parser.add_argument(
+ mutually_exclusive_args = parser.add_mutually_exclusive_group(required=True)
+ # config-file or use-env-vars made mutually exclusive to prevent conflicts
+ mutually_exclusive_args.add_argument(
'--config-file', '-c',
action='store',
- required=True,
help='Config file for the Botserver. Use your `botserverrc` for multiple bots or'
'`zuliprc` for a single bot.'
)
+ mutually_exclusive_args.add_argument(
+ '--use-env-vars', '-e',
+ action='store_true',
+ help='Load configuration from JSON in ZULIP_BOTSERVER_CONFIG environment variable.'
+ )
parser.add_argument(
'--bot-config-file',
action='store',
diff --git a/zulip_botserver/zulip_botserver/server.py b/zulip_botserver/zulip_botserver/server.py
index 6ad67629..ed5a048e 100644
--- a/zulip_botserver/zulip_botserver/server.py
+++ b/zulip_botserver/zulip_botserver/server.py
@@ -7,6 +7,7 @@ import os
import sys
import importlib.util
+from collections import OrderedDict
from configparser import MissingSectionHeaderError, NoOptionError
from flask import Flask, request
from importlib import import_module
@@ -28,6 +29,32 @@ def read_config_section(parser: configparser.ConfigParser, section: str) -> Dict
}
return section_info
+def read_config_from_env_vars(bot_name: Optional[str] = None) -> Dict[str, Dict[str, str]]:
+ bots_config = {} # type: Dict[str, Dict[str, str]]
+ json_config = os.environ.get('ZULIP_BOTSERVER_CONFIG')
+
+ if json_config is None:
+ raise OSError("Could not read environment variable 'ZULIP_BOTSERVER_CONFIG': Variable not set.")
+
+ # Load JSON-formatted environment variable; use OrderedDict to
+ # preserve ordering on Python 3.6 and below.
+ env_config = json.loads(json_config, object_pairs_hook=OrderedDict)
+ if bot_name is not None:
+ if bot_name in env_config:
+ bots_config[bot_name] = env_config[bot_name]
+ else:
+ # If the bot name provided via the command line does not
+ # exist in the configuration provided via the environment
+ # variable, use the first bot in the environment variable,
+ # with name updated to match, along with a warning.
+ first_bot_name = list(env_config.keys())[0]
+ bots_config[bot_name] = env_config[first_bot_name]
+ logging.warning(
+ "First bot name in the config list was changed from '{}' to '{}'".format(first_bot_name, bot_name)
+ )
+ else:
+ bots_config = dict(env_config)
+ return bots_config
def read_config_file(config_file_path: str, bot_name: Optional[str] = None) -> Dict[str, Dict[str, str]]:
parser = parse_config_file(config_file_path)
@@ -178,16 +205,20 @@ def handle_bot() -> str:
def main() -> None:
options = parse_args()
global bots_config
- try:
- bots_config = read_config_file(options.config_file, options.bot_name)
- except MissingSectionHeaderError:
- sys.exit("Error: Your Botserver config file `{0}` contains an empty section header!\n"
- "You need to write the names of the bots you want to run in the "
- "section headers of `{0}`.".format(options.config_file))
- except NoOptionError as e:
- sys.exit("Error: Your Botserver config file `{0}` has a missing option `{1}` in section `{2}`!\n"
- "You need to add option `{1}` with appropriate value in section `{2}` of `{0}`"
- .format(options.config_file, e.option, e.section))
+
+ if options.use_env_vars:
+ bots_config = read_config_from_env_vars(options.bot_name)
+ elif options.config_file:
+ try:
+ bots_config = read_config_file(options.config_file, options.bot_name)
+ except MissingSectionHeaderError:
+ sys.exit("Error: Your Botserver config file `{0}` contains an empty section header!\n"
+ "You need to write the names of the bots you want to run in the "
+ "section headers of `{0}`.".format(options.config_file))
+ except NoOptionError as e:
+ sys.exit("Error: Your Botserver config file `{0}` has a missing option `{1}` in section `{2}`!\n"
+ "You need to add option `{1}` with appropriate value in section `{2}` of `{0}`"
+ .format(options.config_file, e.option, e.section))
available_bots = list(bots_config.keys())
bots_lib_modules = load_lib_modules(available_bots)
| zulip/python-zulip-api | 984d9151d5d101e8bbfe2c60cc6434b88577217d | diff --git a/zulip_botserver/tests/test_server.py b/zulip_botserver/tests/test_server.py
index d38cd93e..653ef4b9 100644
--- a/zulip_botserver/tests/test_server.py
+++ b/zulip_botserver/tests/test_server.py
@@ -4,6 +4,7 @@ from typing import Any, Dict
import unittest
from .server_test_lib import BotServerTestCase
import json
+from collections import OrderedDict
from importlib import import_module
from types import ModuleType
@@ -132,6 +133,34 @@ class BotServerTests(BotServerTestCase):
assert opts.hostname == '127.0.0.1'
assert opts.port == 5002
+ def test_read_config_from_env_vars(self) -> None:
+ # We use an OrderedDict so that the order of the entries in
+ # the stringified environment variable is standard even on
+ # Python 3.7 and earlier.
+ bots_config = OrderedDict()
+ bots_config['hello_world'] = {
+ 'email': '[email protected]',
+ 'key': 'value',
+ 'site': 'http://localhost',
+ 'token': 'abcd1234',
+ }
+ bots_config['giphy'] = {
+ 'email': '[email protected]',
+ 'key': 'value2',
+ 'site': 'http://localhost',
+ 'token': 'abcd1234',
+ }
+ os.environ['ZULIP_BOTSERVER_CONFIG'] = json.dumps(bots_config)
+
+ # No bot specified; should read all bot configs
+ assert server.read_config_from_env_vars() == bots_config
+
+ # Specified bot exists; should read only that section.
+ assert server.read_config_from_env_vars("giphy") == {'giphy': bots_config['giphy']}
+
+ # Specified bot doesn't exist; should read the first section of the config.
+ assert server.read_config_from_env_vars("redefined_bot") == {'redefined_bot': bots_config['hello_world']}
+
def test_read_config_file(self) -> None:
with self.assertRaises(IOError):
server.read_config_file("nonexistentfile.conf")
| Allow passing config via environment variables to zulip-botserver
**Component:** `zulip-botserver`
**Package:** https://pypi.org/project/zulip-botserver/
**Code:** https://github.com/zulip/python-zulip-api/tree/master/zulip_botserver
Instead of requiring that config be passed as a file with the `--config-file` option, it would be great if we could pass config via environment variables.
This would make our secure key storage system much easier, as right now we use env variables to pass down secure keys to containers, and creating a config file to store them on disk is suboptimal.
```ini
[helloworld]
email=foo-bot@hostname
key=dOHHlyqgpt5g0tVuVl6NHxDLlc9eFRX4
site=http://hostname
token=aQVQmSd6j6IHphJ9m1jhgHdbnhl5ZcsY
```
Becomes:
```bash
env BOT_EMAIL=foo-bot@hostname BOT_KEY=abc... BOT_SITE=https://hostname BOT_TOKEN=abc... zulip-botserver
```
I would require adding ~20 LOC to https://github.com/zulip/python-zulip-api/blob/master/zulip_botserver/zulip_botserver/server.py, if this proposal sounds reasonable, I can probably submit a PR for it myself without too much difficulty. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"zulip_botserver/tests/test_server.py::BotServerTests::test_read_config_from_env_vars"
] | [
"zulip_botserver/tests/test_server.py::BotServerTests::test_argument_parsing_defaults",
"zulip_botserver/tests/test_server.py::BotServerTests::test_load_lib_modules",
"zulip_botserver/tests/test_server.py::BotServerTests::test_read_config_file",
"zulip_botserver/tests/test_server.py::BotServerTests::test_request_for_unkown_bot",
"zulip_botserver/tests/test_server.py::BotServerTests::test_successful_request",
"zulip_botserver/tests/test_server.py::BotServerTests::test_successful_request_from_two_bots",
"zulip_botserver/tests/test_server.py::BotServerTests::test_wrong_bot_credentials",
"zulip_botserver/tests/test_server.py::BotServerTests::test_wrong_bot_token"
] | {
"failed_lite_validators": [
"has_hyperlinks",
"has_many_modified_files",
"has_many_hunks",
"has_pytest_match_arg"
],
"has_test_patch": true,
"is_lite": false
} | "2020-11-08T20:55:09Z" | apache-2.0 |
|
zulip__zulip-terminal-1350 | diff --git a/zulipterminal/ui_tools/views.py b/zulipterminal/ui_tools/views.py
index 1ae51ec..8f6ad15 100644
--- a/zulipterminal/ui_tools/views.py
+++ b/zulipterminal/ui_tools/views.py
@@ -1520,13 +1520,15 @@ class MsgInfoView(PopUpView):
date_and_time = controller.model.formatted_local_time(
msg["timestamp"], show_seconds=True, show_year=True
)
- view_in_browser_keys = ", ".join(map(repr, keys_for_command("VIEW_IN_BROWSER")))
+ view_in_browser_keys = "[{}]".format(
+ ", ".join(map(str, keys_for_command("VIEW_IN_BROWSER")))
+ )
- full_rendered_message_keys = ", ".join(
- map(repr, keys_for_command("FULL_RENDERED_MESSAGE"))
+ full_rendered_message_keys = "[{}]".format(
+ ", ".join(map(str, keys_for_command("FULL_RENDERED_MESSAGE")))
)
- full_raw_message_keys = ", ".join(
- map(repr, keys_for_command("FULL_RAW_MESSAGE"))
+ full_raw_message_keys = "[{}]".format(
+ ", ".join(map(str, keys_for_command("FULL_RAW_MESSAGE")))
)
msg_info = [
(
@@ -1535,22 +1537,22 @@ class MsgInfoView(PopUpView):
("Date & Time", date_and_time),
("Sender", msg["sender_full_name"]),
("Sender's Email ID", msg["sender_email"]),
- (
- "View message in browser",
- f"Press {view_in_browser_keys} to view message in browser",
- ),
- (
- "Full rendered message",
- f"Press {full_rendered_message_keys} to view",
- ),
- (
- "Full raw message",
- f"Press {full_raw_message_keys} to view",
- ),
],
- ),
+ )
]
+
+ # actions for message info popup
+ viewing_actions = (
+ "Viewing Actions",
+ [
+ ("Open in web browser", view_in_browser_keys),
+ ("Full rendered message", full_rendered_message_keys),
+ ("Full raw message", full_raw_message_keys),
+ ],
+ )
+ msg_info.append(viewing_actions)
# Only show the 'Edit History' label for edited messages.
+
self.show_edit_history_label = (
self.msg["id"] in controller.model.index["edited_messages"]
and controller.model.initial_data["realm_allow_edit_history"]
@@ -1558,8 +1560,8 @@ class MsgInfoView(PopUpView):
if self.show_edit_history_label:
msg_info[0][1][0] = ("Date & Time (Original)", date_and_time)
- keys = ", ".join(map(repr, keys_for_command("EDIT_HISTORY")))
- msg_info[0][1].append(("Edit History", f"Press {keys} to view"))
+ keys = "[{}]".format(", ".join(map(str, keys_for_command("EDIT_HISTORY"))))
+ msg_info[1][1].append(("Edit History", keys))
# Render the category using the existing table methods if links exist.
if message_links:
msg_info.append(("Message Links", []))
@@ -1594,7 +1596,9 @@ class MsgInfoView(PopUpView):
# slice_index = Number of labels before message links + 1 newline
# + 1 'Message Links' category label.
- slice_index = len(msg_info[0][1]) + 2
+ # + 2 for Viewing Actions category label and its newline
+ slice_index = len(msg_info[0][1]) + len(msg_info[1][1]) + 2 + 2
+
slice_index += sum([len(w) + 2 for w in self.button_widgets])
self.button_widgets.append(message_links)
@@ -1610,7 +1614,8 @@ class MsgInfoView(PopUpView):
# slice_index = Number of labels before topic links + 1 newline
# + 1 'Topic Links' category label.
- slice_index = len(msg_info[0][1]) + 2
+ # + 2 for Viewing Actions category label and its newline
+ slice_index = len(msg_info[0][1]) + len(msg_info[1][1]) + 2 + 2
slice_index += sum([len(w) + 2 for w in self.button_widgets])
self.button_widgets.append(topic_links)
| zulip/zulip-terminal | b89def63d642cecd4fa6e1d1a9d01a2f001afe2c | diff --git a/tests/ui_tools/test_popups.py b/tests/ui_tools/test_popups.py
index a1eb9fe..3205a13 100644
--- a/tests/ui_tools/test_popups.py
+++ b/tests/ui_tools/test_popups.py
@@ -1027,8 +1027,10 @@ class TestMsgInfoView:
assert self.controller.open_in_browser.called
def test_height_noreactions(self) -> None:
- expected_height = 6
+ expected_height = 8
# 6 = 1 (date & time) +1 (sender's name) +1 (sender's email)
+ # +1 (display group header)
+ # +1 (whitespace column)
# +1 (view message in browser)
# +1 (full rendered message)
# +1 (full raw message)
@@ -1099,9 +1101,9 @@ class TestMsgInfoView:
OrderedDict(),
list(),
)
- # 12 = 6 labels + 1 blank line + 1 'Reactions' (category)
+ # 12 = 7 labels + 2 blank lines + 1 'Reactions' (category)
# + 4 reactions (excluding 'Message Links').
- expected_height = 12
+ expected_height = 14
assert self.msg_info_view.height == expected_height
@pytest.mark.parametrize(
| Message information popup: Tidy shortcut key text & place into a group
The current shortcut/hotkey list in the message information popup (`i` on a message) could be improved by:
- moving the current hotkey lines into a separate display-group, maybe titled 'Viewing Actions'
- simplifying the text in each entry, including replacing the 'Press <key> to...' text by `[<key>]` (like we use in other parts of the UI)
All 'popups' are currently defined in `views.py`, though may be split out in future since their tests are already extracted into `test_popups.py`. See `MsgInfoView` for the relevant class.
There are currently existing display-groups for links in messages, links in topics that a message is in, time mentions, and reactions - though these are conditional upon those elements being present. Explore those in existing messages, or create some in **#test here** on chat.zulip.org (or your own Zulip server), which should give a guide of how groups are shown. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_height_noreactions[stream_message]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_height_noreactions[pm_message]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_height_noreactions[group_pm_message]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_height_reactions[stream_message-to_vary_in_each_message0]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_height_reactions[pm_message-to_vary_in_each_message0]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_height_reactions[group_pm_message-to_vary_in_each_message0]"
] | [
"tests/ui_tools/test_popups.py::TestPopUpConfirmationView::test_init",
"tests/ui_tools/test_popups.py::TestPopUpConfirmationView::test_exit_popup_yes",
"tests/ui_tools/test_popups.py::TestPopUpConfirmationView::test_exit_popup_no",
"tests/ui_tools/test_popups.py::TestPopUpConfirmationView::test_exit_popup_GO_BACK[esc]",
"tests/ui_tools/test_popups.py::TestPopUpView::test_init",
"tests/ui_tools/test_popups.py::TestPopUpView::test_keypress_GO_BACK[esc]",
"tests/ui_tools/test_popups.py::TestPopUpView::test_keypress_command_key",
"tests/ui_tools/test_popups.py::TestPopUpView::test_keypress_navigation[nav-key:u]",
"tests/ui_tools/test_popups.py::TestPopUpView::test_keypress_navigation[nav-key:k]",
"tests/ui_tools/test_popups.py::TestPopUpView::test_keypress_navigation[nav-key:d]",
"tests/ui_tools/test_popups.py::TestPopUpView::test_keypress_navigation[nav-key:j]",
"tests/ui_tools/test_popups.py::TestPopUpView::test_keypress_navigation[nav-key:l0]",
"tests/ui_tools/test_popups.py::TestPopUpView::test_keypress_navigation[nav-key:h]",
"tests/ui_tools/test_popups.py::TestPopUpView::test_keypress_navigation[nav-key:r]",
"tests/ui_tools/test_popups.py::TestPopUpView::test_keypress_navigation[nav-key:l1]",
"tests/ui_tools/test_popups.py::TestPopUpView::test_keypress_navigation[nav-key:p0]",
"tests/ui_tools/test_popups.py::TestPopUpView::test_keypress_navigation[nav-key:K]",
"tests/ui_tools/test_popups.py::TestPopUpView::test_keypress_navigation[nav-key:p1]",
"tests/ui_tools/test_popups.py::TestPopUpView::test_keypress_navigation[nav-key:J]",
"tests/ui_tools/test_popups.py::TestPopUpView::test_keypress_navigation[nav-key:e]",
"tests/ui_tools/test_popups.py::TestPopUpView::test_keypress_navigation[nav-key:G]",
"tests/ui_tools/test_popups.py::TestAboutView::test_keypress_exit_popup[meta",
"tests/ui_tools/test_popups.py::TestAboutView::test_keypress_exit_popup[esc]",
"tests/ui_tools/test_popups.py::TestAboutView::test_keypress_exit_popup_invalid_key",
"tests/ui_tools/test_popups.py::TestAboutView::test_feature_level_content[server_version:2.1-server_feature_level:None]",
"tests/ui_tools/test_popups.py::TestAboutView::test_feature_level_content[server_version:3.0-server_feature_level:25]",
"tests/ui_tools/test_popups.py::TestUserInfoView::test__fetch_user_data[user_email]",
"tests/ui_tools/test_popups.py::TestUserInfoView::test__fetch_user_data[user_empty_email]",
"tests/ui_tools/test_popups.py::TestUserInfoView::test__fetch_user_data[user_date_joined]",
"tests/ui_tools/test_popups.py::TestUserInfoView::test__fetch_user_data[user_empty_date_joined]",
"tests/ui_tools/test_popups.py::TestUserInfoView::test__fetch_user_data[user_timezone]",
"tests/ui_tools/test_popups.py::TestUserInfoView::test__fetch_user_data[user_empty_timezone]",
"tests/ui_tools/test_popups.py::TestUserInfoView::test__fetch_user_data[user_bot_owner]",
"tests/ui_tools/test_popups.py::TestUserInfoView::test__fetch_user_data[user_empty_bot_owner]",
"tests/ui_tools/test_popups.py::TestUserInfoView::test__fetch_user_data[user_last_active]",
"tests/ui_tools/test_popups.py::TestUserInfoView::test__fetch_user_data[user_empty_last_active]",
"tests/ui_tools/test_popups.py::TestUserInfoView::test__fetch_user_data[user_is_generic_bot]",
"tests/ui_tools/test_popups.py::TestUserInfoView::test__fetch_user_data[user_is_incoming_webhook_bot]",
"tests/ui_tools/test_popups.py::TestUserInfoView::test__fetch_user_data[user_is_outgoing_webhook_bot]",
"tests/ui_tools/test_popups.py::TestUserInfoView::test__fetch_user_data[user_is_embedded_bot]",
"tests/ui_tools/test_popups.py::TestUserInfoView::test__fetch_user_data[user_is_owner]",
"tests/ui_tools/test_popups.py::TestUserInfoView::test__fetch_user_data[user_is_admin]",
"tests/ui_tools/test_popups.py::TestUserInfoView::test__fetch_user_data[user_is_moderator]",
"tests/ui_tools/test_popups.py::TestUserInfoView::test__fetch_user_data[user_is_guest]",
"tests/ui_tools/test_popups.py::TestUserInfoView::test__fetch_user_data[user_is_member]",
"tests/ui_tools/test_popups.py::TestUserInfoView::test__fetch_user_data_USER_NOT_FOUND",
"tests/ui_tools/test_popups.py::TestUserInfoView::test_keypress_exit_popup[i]",
"tests/ui_tools/test_popups.py::TestUserInfoView::test_keypress_exit_popup[esc]",
"tests/ui_tools/test_popups.py::TestUserInfoView::test_keypress_exit_popup_invalid_key",
"tests/ui_tools/test_popups.py::TestFullRenderedMsgView::test_init",
"tests/ui_tools/test_popups.py::TestFullRenderedMsgView::test_keypress_exit_popup[i]",
"tests/ui_tools/test_popups.py::TestFullRenderedMsgView::test_keypress_exit_popup_invalid_key",
"tests/ui_tools/test_popups.py::TestFullRenderedMsgView::test_keypress_show_msg_info[f]",
"tests/ui_tools/test_popups.py::TestFullRenderedMsgView::test_keypress_show_msg_info[esc]",
"tests/ui_tools/test_popups.py::TestFullRawMsgView::test_init",
"tests/ui_tools/test_popups.py::TestFullRawMsgView::test_keypress_exit_popup[i]",
"tests/ui_tools/test_popups.py::TestFullRawMsgView::test_keypress_exit_popup_invalid_key",
"tests/ui_tools/test_popups.py::TestFullRawMsgView::test_keypress_show_msg_info[r]",
"tests/ui_tools/test_popups.py::TestFullRawMsgView::test_keypress_show_msg_info[esc]",
"tests/ui_tools/test_popups.py::TestEditHistoryView::test_init",
"tests/ui_tools/test_popups.py::TestEditHistoryView::test_keypress_exit_popup[i]",
"tests/ui_tools/test_popups.py::TestEditHistoryView::test_keypress_exit_popup_invalid_key",
"tests/ui_tools/test_popups.py::TestEditHistoryView::test_keypress_show_msg_info[esc]",
"tests/ui_tools/test_popups.py::TestEditHistoryView::test_keypress_show_msg_info[e]",
"tests/ui_tools/test_popups.py::TestEditHistoryView::test__make_edit_block[with_user_id-snapshot0]",
"tests/ui_tools/test_popups.py::TestEditHistoryView::test__make_edit_block[without_user_id-snapshot0]",
"tests/ui_tools/test_popups.py::TestEditHistoryView::test__get_author_prefix[posted-snapshot0]",
"tests/ui_tools/test_popups.py::TestEditHistoryView::test__get_author_prefix[content_&_topic_edited-snapshot0]",
"tests/ui_tools/test_popups.py::TestEditHistoryView::test__get_author_prefix[content_edited-snapshot0]",
"tests/ui_tools/test_popups.py::TestEditHistoryView::test__get_author_prefix[topic_edited-snapshot0]",
"tests/ui_tools/test_popups.py::TestEditHistoryView::test__get_author_prefix[false_alarm_content_&_topic-snapshot0]",
"tests/ui_tools/test_popups.py::TestEditHistoryView::test__get_author_prefix[content_edited_with_false_alarm_topic-snapshot0]",
"tests/ui_tools/test_popups.py::TestEditHistoryView::test__get_author_prefix[topic_edited_with_false_alarm_content-snapshot0]",
"tests/ui_tools/test_popups.py::TestEditModeView::test_init[change_one]",
"tests/ui_tools/test_popups.py::TestEditModeView::test_init[change_later]",
"tests/ui_tools/test_popups.py::TestEditModeView::test_init[change_all]",
"tests/ui_tools/test_popups.py::TestEditModeView::test_select_edit_mode[change_one-enter-1-change_later]",
"tests/ui_tools/test_popups.py::TestEditModeView::test_select_edit_mode[change_one-enter-2-change_all]",
"tests/ui_tools/test_popups.py::TestEditModeView::test_select_edit_mode[change_later-enter-0-change_one]",
"tests/ui_tools/test_popups.py::TestEditModeView::test_select_edit_mode[change_later-enter-2-change_all]",
"tests/ui_tools/test_popups.py::TestEditModeView::test_select_edit_mode[change_all-enter-0-change_one]",
"tests/ui_tools/test_popups.py::TestEditModeView::test_select_edit_mode[change_all-enter-1-change_later]",
"tests/ui_tools/test_popups.py::TestMarkdownHelpView::test_keypress_any_key",
"tests/ui_tools/test_popups.py::TestMarkdownHelpView::test_keypress_exit_popup[esc]",
"tests/ui_tools/test_popups.py::TestMarkdownHelpView::test_keypress_exit_popup[meta",
"tests/ui_tools/test_popups.py::TestHelpView::test_keypress_any_key",
"tests/ui_tools/test_popups.py::TestHelpView::test_keypress_exit_popup[esc]",
"tests/ui_tools/test_popups.py::TestHelpView::test_keypress_exit_popup[?]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_init[stream_message]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_init[pm_message]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_init[group_pm_message]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_pop_up_info_order[stream_message]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_pop_up_info_order[pm_message]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_pop_up_info_order[group_pm_message]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_any_key[stream_message]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_any_key[pm_message]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_any_key[group_pm_message]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_edit_history[stream_message-stream_message_id-True-e]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_edit_history[stream_message-stream_message_id-False-e]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_edit_history[stream_message-pm_message_id-True-e]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_edit_history[stream_message-pm_message_id-False-e]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_edit_history[stream_message-group_pm_message_id-True-e]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_edit_history[stream_message-group_pm_message_id-False-e]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_edit_history[pm_message-stream_message_id-True-e]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_edit_history[pm_message-stream_message_id-False-e]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_edit_history[pm_message-pm_message_id-True-e]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_edit_history[pm_message-pm_message_id-False-e]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_edit_history[pm_message-group_pm_message_id-True-e]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_edit_history[pm_message-group_pm_message_id-False-e]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_edit_history[group_pm_message-stream_message_id-True-e]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_edit_history[group_pm_message-stream_message_id-False-e]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_edit_history[group_pm_message-pm_message_id-True-e]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_edit_history[group_pm_message-pm_message_id-False-e]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_edit_history[group_pm_message-group_pm_message_id-True-e]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_edit_history[group_pm_message-group_pm_message_id-False-e]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_full_rendered_message[stream_message-f]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_full_rendered_message[pm_message-f]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_full_rendered_message[group_pm_message-f]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_full_raw_message[stream_message-r]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_full_raw_message[pm_message-r]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_full_raw_message[group_pm_message-r]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_exit_popup[stream_message-i]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_exit_popup[stream_message-esc]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_exit_popup[pm_message-i]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_exit_popup[pm_message-esc]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_exit_popup[group_pm_message-i]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_exit_popup[group_pm_message-esc]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_view_in_browser[stream_message-v]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_view_in_browser[pm_message-v]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_keypress_view_in_browser[group_pm_message-v]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_create_link_buttons[stream_message-link_with_link_text]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_create_link_buttons[stream_message-link_without_link_text]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_create_link_buttons[pm_message-link_with_link_text]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_create_link_buttons[pm_message-link_without_link_text]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_create_link_buttons[group_pm_message-link_with_link_text]",
"tests/ui_tools/test_popups.py::TestMsgInfoView::test_create_link_buttons[group_pm_message-link_without_link_text]",
"tests/ui_tools/test_popups.py::TestStreamInfoView::test_keypress_any_key",
"tests/ui_tools/test_popups.py::TestStreamInfoView::test_keypress_stream_members[m]",
"tests/ui_tools/test_popups.py::TestStreamInfoView::test_popup_height[ZFL=None_no_date_created__no_retention_days__admins_only]",
"tests/ui_tools/test_popups.py::TestStreamInfoView::test_popup_height[ZFL=None_no_date_created__no_retention_days__anyone_can_type]",
"tests/ui_tools/test_popups.py::TestStreamInfoView::test_popup_height[ZFL<30_no_date_created__ZFL<17_no_retention_days]",
"tests/ui_tools/test_popups.py::TestStreamInfoView::test_popup_height[ZFL<30_no_date_created__ZFL=17_custom_finite_retention_days]",
"tests/ui_tools/test_popups.py::TestStreamInfoView::test_popup_height[ZFL<30_no_date_created__ZFL>17_default_indefinite_retention_days]",
"tests/ui_tools/test_popups.py::TestStreamInfoView::test_popup_height[ZFL=30_with_date_created__ZFL>17_custom_finite_retention_days]",
"tests/ui_tools/test_popups.py::TestStreamInfoView::test_popup_height[ZFL>30_with_date_created__ZFL>17_default_finite_retention_days]",
"tests/ui_tools/test_popups.py::TestStreamInfoView::test_popup_height[ZFL>30_new_stream_with_date_created__ZFL>17_finite_retention_days]",
"tests/ui_tools/test_popups.py::TestStreamInfoView::test_keypress_copy_stream_email[c]",
"tests/ui_tools/test_popups.py::TestStreamInfoView::test_markup_description[<p>Simple</p>-expected_markup0]",
"tests/ui_tools/test_popups.py::TestStreamInfoView::test_markup_description[<p>A",
"tests/ui_tools/test_popups.py::TestStreamInfoView::test_footlinks[message_links0-1:",
"tests/ui_tools/test_popups.py::TestStreamInfoView::test_keypress_exit_popup[i]",
"tests/ui_tools/test_popups.py::TestStreamInfoView::test_keypress_exit_popup[esc]",
"tests/ui_tools/test_popups.py::TestStreamInfoView::test_checkbox_toggle_mute_stream[enter]",
"tests/ui_tools/test_popups.py::TestStreamInfoView::test_checkbox_toggle_mute_stream[",
"tests/ui_tools/test_popups.py::TestStreamInfoView::test_checkbox_toggle_pin_stream[enter]",
"tests/ui_tools/test_popups.py::TestStreamInfoView::test_checkbox_toggle_pin_stream[",
"tests/ui_tools/test_popups.py::TestStreamInfoView::test_checkbox_toggle_visual_notification[enter]",
"tests/ui_tools/test_popups.py::TestStreamInfoView::test_checkbox_toggle_visual_notification[",
"tests/ui_tools/test_popups.py::TestStreamMembersView::test_keypress_exit_popup[m]",
"tests/ui_tools/test_popups.py::TestStreamMembersView::test_keypress_exit_popup[esc]",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_update_emoji_list[stream_message-e-assert_list0-emoji_units0]",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_update_emoji_list[stream_message-sm-assert_list1-emoji_units0]",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_update_emoji_list[stream_message-ang-assert_list2-emoji_units0]",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_update_emoji_list[stream_message-abc-assert_list3-emoji_units0]",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_update_emoji_list[stream_message-q-assert_list4-emoji_units0]",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_update_emoji_list[pm_message-e-assert_list0-emoji_units0]",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_update_emoji_list[pm_message-sm-assert_list1-emoji_units0]",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_update_emoji_list[pm_message-ang-assert_list2-emoji_units0]",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_update_emoji_list[pm_message-abc-assert_list3-emoji_units0]",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_update_emoji_list[pm_message-q-assert_list4-emoji_units0]",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_update_emoji_list[group_pm_message-e-assert_list0-emoji_units0]",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_update_emoji_list[group_pm_message-sm-assert_list1-emoji_units0]",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_update_emoji_list[group_pm_message-ang-assert_list2-emoji_units0]",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_update_emoji_list[group_pm_message-abc-assert_list3-emoji_units0]",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_update_emoji_list[group_pm_message-q-assert_list4-emoji_units0]",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_mouse_event[stream_message-mouse",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_mouse_event[pm_message-mouse",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_mouse_event[group_pm_message-mouse",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_keypress_search_emoji[stream_message-p]",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_keypress_search_emoji[pm_message-p]",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_keypress_search_emoji[group_pm_message-p]",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_keypress_exit_called[stream_message-:]",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_keypress_exit_called[stream_message-esc]",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_keypress_exit_called[pm_message-:]",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_keypress_exit_called[pm_message-esc]",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_keypress_exit_called[group_pm_message-:]",
"tests/ui_tools/test_popups.py::TestEmojiPickerView::test_keypress_exit_called[group_pm_message-esc]"
] | {
"failed_lite_validators": [
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-03-22T17:07:44Z" | apache-2.0 |
|
zulip__zulip-terminal-1356 | diff --git a/zulipterminal/model.py b/zulipterminal/model.py
index 82d809a..7073e4f 100644
--- a/zulipterminal/model.py
+++ b/zulipterminal/model.py
@@ -2,6 +2,7 @@
Defines the `Model`, fetching and storing data retrieved from the Zulip server
"""
+import bisect
import itertools
import json
import time
@@ -111,7 +112,6 @@ class Model:
self.stream_id: Optional[int] = None
self.recipients: FrozenSet[Any] = frozenset()
self.index = initial_index
- self._last_unread_topic = None
self.last_unread_pm = None
self.user_id = -1
@@ -886,23 +886,67 @@ class Model:
topic_to_search = (stream_name, topic)
return topic_to_search in self._muted_topics
- def get_next_unread_topic(self) -> Optional[Tuple[int, str]]:
+ def stream_topic_from_message_id(
+ self, message_id: int
+ ) -> Optional[Tuple[int, str]]:
+ """
+ Returns the stream and topic of a message of a given message id.
+ If the message is not a stream message or if it is not present in the index,
+ None is returned.
+ """
+ message = self.index["messages"].get(message_id, None)
+ if message is not None and message["type"] == "stream":
+ stream_id = message["stream_id"]
+ topic = message["subject"]
+ return (stream_id, topic)
+ return None
+
+ def next_unread_topic_from_message_id(
+ self, current_message: Optional[int]
+ ) -> Optional[Tuple[int, str]]:
+ if current_message:
+ current_topic = self.stream_topic_from_message_id(current_message)
+ else:
+ current_topic = (
+ self.stream_id_from_name(self.narrow[0][1]),
+ self.narrow[1][1],
+ )
unread_topics = sorted(self.unread_counts["unread_topics"].keys())
next_topic = False
- if self._last_unread_topic not in unread_topics:
+ stream_start: Optional[Tuple[int, str]] = None
+ if current_topic is None:
next_topic = True
+ elif current_topic not in unread_topics:
+ # insert current_topic in list of unread_topics for the case where
+ # current_topic is not in unread_topics, and the next unmuted topic
+ # is to be returned. This does not modify the original unread topics
+ # data, and is just used to compute the next unmuted topic to be returned.
+ bisect.insort(unread_topics, current_topic)
# loop over unread_topics list twice for the case that last_unread_topic was
# the last valid unread_topic in unread_topics list.
for unread_topic in unread_topics * 2:
stream_id, topic_name = unread_topic
- if (
- not self.is_muted_topic(stream_id, topic_name)
- and not self.is_muted_stream(stream_id)
- and next_topic
- ):
- self._last_unread_topic = unread_topic
- return unread_topic
- if unread_topic == self._last_unread_topic:
+ if not self.is_muted_topic(
+ stream_id, topic_name
+ ) and not self.is_muted_stream(stream_id):
+ if next_topic:
+ if unread_topic == current_topic:
+ return None
+ if (
+ current_topic is not None
+ and unread_topic[0] != current_topic[0]
+ and stream_start != current_topic
+ ):
+ return stream_start
+ return unread_topic
+
+ if (
+ stream_start is None
+ and current_topic is not None
+ and unread_topic[0] == current_topic[0]
+ ):
+ stream_start = unread_topic
+ if unread_topic == current_topic:
next_topic = True
return None
diff --git a/zulipterminal/ui_tools/views.py b/zulipterminal/ui_tools/views.py
index 64eebeb..6a1e4e6 100644
--- a/zulipterminal/ui_tools/views.py
+++ b/zulipterminal/ui_tools/views.py
@@ -584,9 +584,20 @@ class MiddleColumnView(urwid.Frame):
elif is_command_key("NEXT_UNREAD_TOPIC", key):
# narrow to next unread topic
- stream_topic = self.model.get_next_unread_topic()
- if stream_topic is None:
+ focus = self.view.message_view.focus
+ narrow = self.model.narrow
+ if focus:
+ current_msg_id = focus.original_widget.message["id"]
+ stream_topic = self.model.next_unread_topic_from_message_id(
+ current_msg_id
+ )
+ if stream_topic is None:
+ return key
+ elif narrow[0][0] == "stream" and narrow[1][0] == "topic":
+ stream_topic = self.model.next_unread_topic_from_message_id(None)
+ else:
return key
+
stream_id, topic = stream_topic
self.controller.narrow_to_topic(
stream_name=self.model.stream_dict[stream_id]["name"],
| zulip/zulip-terminal | 2781e34514be0e606a3f88ebf8fd409781d9f625 | diff --git a/tests/model/test_model.py b/tests/model/test_model.py
index 2bf150a..fe2ba55 100644
--- a/tests/model/test_model.py
+++ b/tests/model/test_model.py
@@ -72,7 +72,6 @@ class TestModel:
assert model.stream_dict == stream_dict
assert model.recipients == frozenset()
assert model.index == initial_index
- assert model._last_unread_topic is None
assert model.last_unread_pm is None
model.get_messages.assert_called_once_with(
num_before=30, num_after=10, anchor=None
@@ -3900,7 +3899,7 @@ class TestModel:
assert return_value == is_muted
@pytest.mark.parametrize(
- "unread_topics, last_unread_topic, next_unread_topic",
+ "unread_topics, current_topic, next_unread_topic",
[
case(
{(1, "topic"), (2, "topic2")},
@@ -3920,10 +3919,10 @@ class TestModel:
(1, "topic"),
id="unread_present_before_previous_topic",
),
- case( # TODO Should be None? (2 other cases)
+ case(
{(1, "topic")},
(1, "topic"),
- (1, "topic"),
+ None,
id="unread_still_present_in_topic",
),
case(
@@ -3993,16 +3992,42 @@ class TestModel:
(2, "topic2"),
id="unread_present_after_previous_topic_muted",
),
+ case(
+ {(1, "topic1"), (2, "topic2"), (2, "topic2 muted")},
+ (2, "topic1"),
+ (2, "topic2"),
+ id="unmuted_unread_present_in_same_stream_as_current_topic_not_in_unread_list",
+ ),
+ case(
+ {(1, "topic1"), (2, "topic2 muted"), (4, "topic4")},
+ (2, "topic1"),
+ (4, "topic4"),
+ id="unmuted_unread_present_in_next_stream_as_current_topic_not_in_unread_list",
+ ),
+ case(
+ {(1, "topic1"), (2, "topic2 muted"), (3, "topic3")},
+ (2, "topic1"),
+ (1, "topic1"),
+ id="unmuted_unread_not_present_in_next_stream_as_current_topic_not_in_unread_list",
+ ),
+ case(
+ {(1, "topic1"), (1, "topic11"), (2, "topic2")},
+ (1, "topic11"),
+ (1, "topic1"),
+ id="unread_present_in_same_stream_wrap_around",
+ ),
],
)
- def test_get_next_unread_topic(
- self, model, unread_topics, last_unread_topic, next_unread_topic
+ def test_next_unread_topic_from_message(
+ self, mocker, model, unread_topics, current_topic, next_unread_topic
):
# NOTE Not important how many unreads per topic, so just use '1'
model.unread_counts = {
"unread_topics": {stream_topic: 1 for stream_topic in unread_topics}
}
- model._last_unread_topic = last_unread_topic
+
+ current_message_id = 10 # Arbitrary value due to mock below
+ model.stream_topic_from_message_id = mocker.Mock(return_value=current_topic)
# Minimal extra streams for muted stream testing (should not exist otherwise)
assert {3, 4} & set(model.stream_dict) == set()
@@ -4020,7 +4045,38 @@ class TestModel:
]
}
- unread_topic = model.get_next_unread_topic()
+ unread_topic = model.next_unread_topic_from_message_id(current_message_id)
+
+ assert unread_topic == next_unread_topic
+
+ @pytest.mark.parametrize(
+ "unread_topics, empty_narrow, narrow_stream_id, next_unread_topic",
+ [
+ case(
+ {(1, "topic1"), (1, "topic2"), (2, "topic3")},
+ [["stream", "Stream 1"], ["topic", "topic1.5"]],
+ 1,
+ (1, "topic2"),
+ ),
+ ],
+ )
+ def test_next_unread_topic_from_message__empty_narrow(
+ self,
+ mocker,
+ model,
+ unread_topics,
+ empty_narrow,
+ narrow_stream_id,
+ next_unread_topic,
+ ):
+ # NOTE Not important how many unreads per topic, so just use '1'
+ model.unread_counts = {
+ "unread_topics": {stream_topic: 1 for stream_topic in unread_topics}
+ }
+ model.stream_id_from_name = mocker.Mock(return_value=narrow_stream_id)
+ model.narrow = empty_narrow
+
+ unread_topic = model.next_unread_topic_from_message_id(None)
assert unread_topic == next_unread_topic
@@ -4043,6 +4099,21 @@ class TestModel:
assert return_value is None
assert model.last_unread_pm is None
+ @pytest.mark.parametrize(
+ "message_id, expected_value",
+ [
+ case(537286, (205, "Test"), id="stream_message"),
+ case(537287, None, id="direct_message"),
+ case(537289, None, id="non-existent message"),
+ ],
+ )
+ def test_stream_topic_from_message_id(
+ self, mocker, model, message_id, expected_value, empty_index
+ ):
+ model.index = empty_index
+ current_topic = model.stream_topic_from_message_id(message_id)
+ assert current_topic == expected_value
+
@pytest.mark.parametrize(
"stream_id, expected_response",
[
diff --git a/tests/ui/test_ui_tools.py b/tests/ui/test_ui_tools.py
index c04c9c3..324ee04 100644
--- a/tests/ui/test_ui_tools.py
+++ b/tests/ui/test_ui_tools.py
@@ -887,9 +887,10 @@ class TestMiddleColumnView:
):
size = widget_size(mid_col_view)
mocker.patch(MIDCOLVIEW + ".focus_position")
+ mocker.patch.object(self.view, "message_view")
mid_col_view.model.stream_dict = {1: {"name": "stream"}}
- mid_col_view.model.get_next_unread_topic.return_value = (1, "topic")
+ mid_col_view.model.next_unread_topic_from_message_id.return_value = (1, "topic")
return_value = mid_col_view.keypress(size, key)
@@ -904,7 +905,8 @@ class TestMiddleColumnView:
):
size = widget_size(mid_col_view)
mocker.patch(MIDCOLVIEW + ".focus_position")
- mid_col_view.model.get_next_unread_topic.return_value = None
+ mocker.patch.object(self.view, "message_view")
+ mid_col_view.model.next_unread_topic_from_message_id.return_value = None
return_value = mid_col_view.keypress(size, key)
| Improve algorithm for 'next unread topic' (n) to use current message state
This is intended as a first step to resolving #1332. Please focus on this element of that issue first, and if things go well, then extending the algorithm further to resolve the remaining elements would be great as followup PR(s).
The current message is part of the UI, so we likely want to try passing this information as an additional parameter to the `get_next_unread_topic` method. This seems likely to replace the persistent topic state stored in the model right now.
There are existing tests for this method, which will need to be adjusted to account for the change in method signature (new parameter) and possible change in behavior. Depending on the cases covered by the tests, this may also warrant additional cases to demonstrate the code is working well. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_after_no_state]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_after_previous_topic]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_before_previous_topic]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_still_present_in_topic]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[no_unreads_with_previous_topic_state]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[no_unreads_with_no_previous_topic_state]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_before_previous_topic_skipping_muted_stream]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_after_previous_topic_skipping_muted_stream]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_only_in_muted_stream]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_starting_in_muted_stream]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_skipping_first_muted_stream_unread]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_only_in_muted_topic]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_starting_in_muted_topic]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_only_in_muted_topic_in_muted_stream]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_after_previous_topic_skipping_muted_topic]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_after_previous_topic_muted]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unmuted_unread_present_in_same_stream_as_current_topic_not_in_unread_list]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unmuted_unread_present_in_next_stream_as_current_topic_not_in_unread_list]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unmuted_unread_not_present_in_next_stream_as_current_topic_not_in_unread_list]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_in_same_stream_wrap_around]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message__empty_narrow[unread_topics0-empty_narrow0-1-next_unread_topic0]",
"tests/model/test_model.py::TestModel::test_stream_topic_from_message_id[stream_message]",
"tests/model/test_model.py::TestModel::test_stream_topic_from_message_id[direct_message]",
"tests/model/test_model.py::TestModel::test_stream_topic_from_message_id[non-existent",
"tests/ui/test_ui_tools.py::TestMiddleColumnView::test_keypress_NEXT_UNREAD_TOPIC_stream[n]",
"tests/ui/test_ui_tools.py::TestMiddleColumnView::test_keypress_NEXT_UNREAD_TOPIC_no_stream[n]"
] | [
"tests/model/test_model.py::TestModel::test_init",
"tests/model/test_model.py::TestModel::test_init_user_settings[None-True]",
"tests/model/test_model.py::TestModel::test_init_user_settings[True-True]",
"tests/model/test_model.py::TestModel::test_init_user_settings[False-False]",
"tests/model/test_model.py::TestModel::test_user_settings_expected_contents",
"tests/model/test_model.py::TestModel::test_init_muted_topics[zulip_feature_level:None]",
"tests/model/test_model.py::TestModel::test_init_muted_topics[zulip_feature_level:1]",
"tests/model/test_model.py::TestModel::test_init_InvalidAPIKey_response",
"tests/model/test_model.py::TestModel::test_init_ZulipError_exception",
"tests/model/test_model.py::TestModel::test_register_initial_desired_events",
"tests/model/test_model.py::TestModel::test_normalize_and_cache_message_retention_text[ZFL=None_no_stream_retention_realm_retention=None]",
"tests/model/test_model.py::TestModel::test_normalize_and_cache_message_retention_text[ZFL=16_no_stream_retention_realm_retention=-1]",
"tests/model/test_model.py::TestModel::test_normalize_and_cache_message_retention_text[ZFL=17_stream_retention_days=30]",
"tests/model/test_model.py::TestModel::test_normalize_and_cache_message_retention_text[ZFL=18_stream_retention_days=[None,",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow0-1]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow0-5]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow0-None]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow1-1]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow1-5]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow1-None]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow2-1]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow2-5]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow2-None]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow3-1]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow3-5]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow3-None]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow4-1]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow4-5]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow4-None]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow5-1]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow5-5]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow5-None]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow6-1]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow6-5]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow6-None]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow0-1]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow0-5]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow1-1]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow1-5]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow2-1]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow2-5]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow3-1]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow3-5]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow4-1]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow4-5]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow5-1]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow5-5]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow6-1]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow6-5]",
"tests/model/test_model.py::TestModel::test_is_search_narrow[narrow0-False]",
"tests/model/test_model.py::TestModel::test_is_search_narrow[narrow1-True]",
"tests/model/test_model.py::TestModel::test_is_search_narrow[narrow2-False]",
"tests/model/test_model.py::TestModel::test_is_search_narrow[narrow3-True]",
"tests/model/test_model.py::TestModel::test_is_search_narrow[narrow4-True]",
"tests/model/test_model.py::TestModel::test_is_search_narrow[narrow5-False]",
"tests/model/test_model.py::TestModel::test_is_search_narrow[narrow6-True]",
"tests/model/test_model.py::TestModel::test_is_search_narrow[narrow7-False]",
"tests/model/test_model.py::TestModel::test_is_search_narrow[narrow8-True]",
"tests/model/test_model.py::TestModel::test_is_search_narrow[narrow9-True]",
"tests/model/test_model.py::TestModel::test_is_search_narrow[narrow10-True]",
"tests/model/test_model.py::TestModel::test_set_narrow_bad_input[bad_args0]",
"tests/model/test_model.py::TestModel::test_set_narrow_bad_input[bad_args1]",
"tests/model/test_model.py::TestModel::test_set_narrow_bad_input[bad_args2]",
"tests/model/test_model.py::TestModel::test_set_narrow_bad_input[bad_args3]",
"tests/model/test_model.py::TestModel::test_set_narrow_already_set[narrow0-good_args0]",
"tests/model/test_model.py::TestModel::test_set_narrow_already_set[narrow1-good_args1]",
"tests/model/test_model.py::TestModel::test_set_narrow_already_set[narrow2-good_args2]",
"tests/model/test_model.py::TestModel::test_set_narrow_already_set[narrow3-good_args3]",
"tests/model/test_model.py::TestModel::test_set_narrow_already_set[narrow4-good_args4]",
"tests/model/test_model.py::TestModel::test_set_narrow_already_set[narrow5-good_args5]",
"tests/model/test_model.py::TestModel::test_set_narrow_already_set[narrow6-good_args6]",
"tests/model/test_model.py::TestModel::test_set_narrow_not_already_set[initial_narrow0-narrow0-good_args0]",
"tests/model/test_model.py::TestModel::test_set_narrow_not_already_set[initial_narrow1-narrow1-good_args1]",
"tests/model/test_model.py::TestModel::test_set_narrow_not_already_set[initial_narrow2-narrow2-good_args2]",
"tests/model/test_model.py::TestModel::test_set_narrow_not_already_set[initial_narrow3-narrow3-good_args3]",
"tests/model/test_model.py::TestModel::test_set_narrow_not_already_set[initial_narrow4-narrow4-good_args4]",
"tests/model/test_model.py::TestModel::test_set_narrow_not_already_set[initial_narrow5-narrow5-good_args5]",
"tests/model/test_model.py::TestModel::test_set_narrow_not_already_set[initial_narrow6-narrow6-good_args6]",
"tests/model/test_model.py::TestModel::test_get_message_ids_in_current_narrow[narrow0-index0-current_ids0]",
"tests/model/test_model.py::TestModel::test_get_message_ids_in_current_narrow[narrow1-index1-current_ids1]",
"tests/model/test_model.py::TestModel::test_get_message_ids_in_current_narrow[narrow2-index2-current_ids2]",
"tests/model/test_model.py::TestModel::test_get_message_ids_in_current_narrow[narrow3-index3-current_ids3]",
"tests/model/test_model.py::TestModel::test_get_message_ids_in_current_narrow[narrow4-index4-current_ids4]",
"tests/model/test_model.py::TestModel::test_get_message_ids_in_current_narrow[narrow5-index5-current_ids5]",
"tests/model/test_model.py::TestModel::test_get_message_ids_in_current_narrow[narrow6-index6-current_ids6]",
"tests/model/test_model.py::TestModel::test_get_message_ids_in_current_narrow[narrow7-index7-current_ids7]",
"tests/model/test_model.py::TestModel::test_get_message_ids_in_current_narrow[narrow8-index8-current_ids8]",
"tests/model/test_model.py::TestModel::test_get_message_ids_in_current_narrow[narrow9-index9-current_ids9]",
"tests/model/test_model.py::TestModel::test_get_message_ids_in_current_narrow[narrow10-index10-current_ids10]",
"tests/model/test_model.py::TestModel::test__fetch_topics_in_streams[response0-expected_index0-]",
"tests/model/test_model.py::TestModel::test__fetch_topics_in_streams[response1-expected_index1-]",
"tests/model/test_model.py::TestModel::test__fetch_topics_in_streams[response2-expected_index2-Some",
"tests/model/test_model.py::TestModel::test_topics_in_stream[topics_index0-False]",
"tests/model/test_model.py::TestModel::test_topics_in_stream[topics_index1-True]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_unicode_original_no_existing_emoji-user_id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_unicode_original_no_existing_emoji-id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_unicode_original_no_existing_emoji-None]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_realm_original_no_existing_emoji-user_id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_realm_original_no_existing_emoji-id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_realm_original_no_existing_emoji-None]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_unicode_original_mine_existing_different_emoji-user_id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_unicode_original_mine_existing_different_emoji-id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_unicode_original_mine_existing_different_emoji-None]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_zulip_original_mine_existing_different_emoji-user_id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_zulip_original_mine_existing_different_emoji-id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_zulip_original_mine_existing_different_emoji-None]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_unicode_original_others_existing_same_emoji-user_id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_unicode_original_others_existing_same_emoji-id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_unicode_original_others_existing_same_emoji-None]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_unicode_alias_others_existing_same_emoji-user_id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_unicode_alias_others_existing_same_emoji-id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_unicode_alias_others_existing_same_emoji-None]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[remove_unicode_original_mine_existing_same_emoji-user_id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[remove_unicode_original_mine_existing_same_emoji-id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[remove_unicode_original_mine_existing_same_emoji-None]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[remove_unicode_alias_mine_existing_same_emoji-user_id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[remove_unicode_alias_mine_existing_same_emoji-id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[remove_unicode_alias_mine_existing_same_emoji-None]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[remove_zulip_original_mine_existing_same_emoji-user_id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[remove_zulip_original_mine_existing_same_emoji-id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[remove_zulip_original_mine_existing_same_emoji-None]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_invalid_emoji",
"tests/model/test_model.py::TestModel::test_has_user_reacted_to_message[id_inside_user_field__user_not_reacted]",
"tests/model/test_model.py::TestModel::test_has_user_reacted_to_message[user_id_inside_user_field__user_has_reacted]",
"tests/model/test_model.py::TestModel::test_has_user_reacted_to_message[no_user_field_with_user_id__user_has_reacted]",
"tests/model/test_model.py::TestModel::test_has_user_reacted_to_message[no_user_field_with_user_id__user_not_reacted]",
"tests/model/test_model.py::TestModel::test_send_typing_status_by_user_ids[start-recipient_user_ids0]",
"tests/model/test_model.py::TestModel::test_send_typing_status_by_user_ids[start-recipient_user_ids1]",
"tests/model/test_model.py::TestModel::test_send_typing_status_by_user_ids[stop-recipient_user_ids0]",
"tests/model/test_model.py::TestModel::test_send_typing_status_by_user_ids[stop-recipient_user_ids1]",
"tests/model/test_model.py::TestModel::test_send_typing_status_with_no_recipients[start]",
"tests/model/test_model.py::TestModel::test_send_typing_status_with_no_recipients[stop]",
"tests/model/test_model.py::TestModel::test_send_typing_status_avoided_due_to_user_setting[start-recipient_user_ids0]",
"tests/model/test_model.py::TestModel::test_send_typing_status_avoided_due_to_user_setting[start-recipient_user_ids1]",
"tests/model/test_model.py::TestModel::test_send_typing_status_avoided_due_to_user_setting[stop-recipient_user_ids0]",
"tests/model/test_model.py::TestModel::test_send_typing_status_avoided_due_to_user_setting[stop-recipient_user_ids1]",
"tests/model/test_model.py::TestModel::test_send_private_message[recipients0-response0-True]",
"tests/model/test_model.py::TestModel::test_send_private_message[recipients0-response1-False]",
"tests/model/test_model.py::TestModel::test_send_private_message[recipients1-response0-True]",
"tests/model/test_model.py::TestModel::test_send_private_message[recipients1-response1-False]",
"tests/model/test_model.py::TestModel::test_send_private_message_with_no_recipients",
"tests/model/test_model.py::TestModel::test_send_stream_message[response0-True]",
"tests/model/test_model.py::TestModel::test_send_stream_message[response1-False]",
"tests/model/test_model.py::TestModel::test_update_private_message[response0-True]",
"tests/model/test_model.py::TestModel::test_update_private_message[response1-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_passed_but_same_so_not_changed:content_changed-API_success]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_passed_but_same_so_not_changed:content_changed-API_error]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_changed[one]-API_success]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_changed[one]-API_error]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_passed_but_same_so_not_changed[all]-API_success]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_passed_but_same_so_not_changed[all]-API_error]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_passed_but_same_so_not_changed[later]:content_changed-API_success]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_passed_but_same_so_not_changed[later]:content_changed-API_error]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_changed[later]:content_changed-API_success]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_changed[later]:content_changed-API_error]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_changed[one]:content_changed-API_success]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_changed[one]:content_changed-API_error]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_changed[all]:content_changed-API_success]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_changed[all]:content_changed-API_error]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args0-False-False-None-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args0-False-False-8-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args0-False-False-9-True]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args0-False-False-152-True]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args1-False-False-None-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args1-False-False-8-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args1-False-False-9-True]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args1-False-False-152-True]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args2-False-False-None-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args2-False-False-8-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args2-False-False-9-True]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args2-False-False-152-True]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args3-True-False-None-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args3-True-False-8-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args3-True-False-9-True]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args3-True-False-152-True]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args4-False-True-None-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args4-False-True-8-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args4-False-True-9-True]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args4-False-True-152-True]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args5-True-True-None-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args5-True-True-8-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args5-True-True-9-True]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args5-True-True-152-True]",
"tests/model/test_model.py::TestModel::test_get_latest_message_in_topic[response0-return_value0]",
"tests/model/test_model.py::TestModel::test_get_latest_message_in_topic[response1-None]",
"tests/model/test_model.py::TestModel::test_get_latest_message_in_topic[response2-None]",
"tests/model/test_model.py::TestModel::test_get_latest_message_in_topic[response3-None]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_msg_disabled:PreZulip4.0-None-_]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_msg_disabled:PreZulip4.0-user_role1-_owner]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_msg_disabled:PreZulip4.0-user_role2-_admin]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_msg_disabled:PreZulip4.0-user_role3-_moderator]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_msg_disabled:PreZulip4.0-user_role4-_member]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_msg_disabled:PreZulip4.0-user_role5-_guest]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_topic_disabled:PreZulip4.0-None-_]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_topic_disabled:PreZulip4.0-user_role1-_owner]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_topic_disabled:PreZulip4.0-user_role2-_admin]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_topic_disabled:PreZulip4.0-user_role3-_moderator]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_topic_disabled:PreZulip4.0-user_role4-_member]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_topic_disabled:PreZulip4.0-user_role5-_guest]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_topic_and_msg_enabled:PreZulip4.0-None-_]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_topic_and_msg_enabled:PreZulip4.0-user_role1-_owner]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_topic_and_msg_enabled:PreZulip4.0-user_role2-_admin]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_topic_and_msg_enabled:PreZulip4.0-user_role3-_moderator]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_topic_and_msg_enabled:PreZulip4.0-user_role4-_member]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_topic_and_msg_enabled:PreZulip4.0-user_role5-_guest]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[all_but_no_editing:Zulip4.0+:ZFL75-None-_]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[all_but_no_editing:Zulip4.0+:ZFL75-user_role1-_owner]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[all_but_no_editing:Zulip4.0+:ZFL75-user_role2-_admin]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[all_but_no_editing:Zulip4.0+:ZFL75-user_role3-_moderator]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[all_but_no_editing:Zulip4.0+:ZFL75-user_role4-_member]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[all_but_no_editing:Zulip4.0+:ZFL75-user_role5-_guest]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[members:Zulip4.0+:ZFL75-None-_]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[members:Zulip4.0+:ZFL75-user_role1-_owner]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[members:Zulip4.0+:ZFL75-user_role2-_admin]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[members:Zulip4.0+:ZFL75-user_role3-_moderator]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[members:Zulip4.0+:ZFL75-user_role4-_member]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[members:Zulip4.0+:ZFL75-user_role5-_guest]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[admins:Zulip4.0+:ZFL75-None-_]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[admins:Zulip4.0+:ZFL75-user_role1-_owner]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[admins:Zulip4.0+:ZFL75-user_role2-_admin]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[admins:Zulip4.0+:ZFL75-user_role3-_moderator]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[admins:Zulip4.0+:ZFL75-user_role4-_member]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[admins:Zulip4.0+:ZFL75-user_role5-_guest]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[full_members:Zulip4.0+:ZFL75-None-_]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[full_members:Zulip4.0+:ZFL75-user_role1-_owner]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[full_members:Zulip4.0+:ZFL75-user_role2-_admin]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[full_members:Zulip4.0+:ZFL75-user_role3-_moderator]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[full_members:Zulip4.0+:ZFL75-user_role4-_member]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[full_members:Zulip4.0+:ZFL75-user_role5-_guest]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[moderators:Zulip4.0+:ZFL75-None-_]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[moderators:Zulip4.0+:ZFL75-user_role1-_owner]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[moderators:Zulip4.0+:ZFL75-user_role2-_admin]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[moderators:Zulip4.0+:ZFL75-user_role3-_moderator]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[moderators:Zulip4.0+:ZFL75-user_role4-_member]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[moderators:Zulip4.0+:ZFL75-user_role5-_guest]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[guests:Zulip4.0+:ZFL75-None-_]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[guests:Zulip4.0+:ZFL75-user_role1-_owner]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[guests:Zulip4.0+:ZFL75-user_role2-_admin]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[guests:Zulip4.0+:ZFL75-user_role3-_moderator]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[guests:Zulip4.0+:ZFL75-user_role4-_member]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[guests:Zulip4.0+:ZFL75-user_role5-_guest]",
"tests/model/test_model.py::TestModel::test_success_get_messages",
"tests/model/test_model.py::TestModel::test_modernize_message_response[Zulip_4.0+_ZFL46_response_with_topic_links]",
"tests/model/test_model.py::TestModel::test_modernize_message_response[Zulip_3.0+_ZFL1_response_with_topic_links]",
"tests/model/test_model.py::TestModel::test_modernize_message_response[Zulip_3.0+_ZFL1_response_empty_topic_links]",
"tests/model/test_model.py::TestModel::test_modernize_message_response[Zulip_2.1+_response_with_subject_links]",
"tests/model/test_model.py::TestModel::test_modernize_message_response[Zulip_2.1+_response_empty_subject_links]",
"tests/model/test_model.py::TestModel::test__store_content_length_restrictions[Zulip_2.1.x_ZFL_None_no_restrictions]",
"tests/model/test_model.py::TestModel::test__store_content_length_restrictions[Zulip_3.1.x_ZFL_27_no_restrictions]",
"tests/model/test_model.py::TestModel::test__store_content_length_restrictions[Zulip_4.0.x_ZFL_52_no_restrictions]",
"tests/model/test_model.py::TestModel::test__store_content_length_restrictions[Zulip_4.0.x_ZFL_53_with_restrictions]",
"tests/model/test_model.py::TestModel::test_get_message_false_first_anchor",
"tests/model/test_model.py::TestModel::test_fail_get_messages",
"tests/model/test_model.py::TestModel::test_fetch_raw_message_content[response0-Feels",
"tests/model/test_model.py::TestModel::test_fetch_raw_message_content[response1-None-True]",
"tests/model/test_model.py::TestModel::test_toggle_stream_muted_status[muting_205]",
"tests/model/test_model.py::TestModel::test_toggle_stream_muted_status[unmuting_205]",
"tests/model/test_model.py::TestModel::test_toggle_stream_muted_status[first_muted_205]",
"tests/model/test_model.py::TestModel::test_toggle_stream_muted_status[last_unmuted_205]",
"tests/model/test_model.py::TestModel::test_stream_access_type",
"tests/model/test_model.py::TestModel::test_toggle_message_star_status[flags_before0-add]",
"tests/model/test_model.py::TestModel::test_toggle_message_star_status[flags_before1-remove]",
"tests/model/test_model.py::TestModel::test_toggle_message_star_status[flags_before2-add]",
"tests/model/test_model.py::TestModel::test_toggle_message_star_status[flags_before3-remove]",
"tests/model/test_model.py::TestModel::test_toggle_message_star_status[flags_before4-remove]",
"tests/model/test_model.py::TestModel::test_mark_message_ids_as_read",
"tests/model/test_model.py::TestModel::test_mark_message_ids_as_read_empty_message_view",
"tests/model/test_model.py::TestModel::test__update_initial_data",
"tests/model/test_model.py::TestModel::test__group_info_from_realm_user_groups",
"tests/model/test_model.py::TestModel::test__clean_and_order_custom_profile_data",
"tests/model/test_model.py::TestModel::test_get_user_info[user_full_name]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_empty_full_name]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_email]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_empty_email]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_date_joined]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_empty_date_joined]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_timezone]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_empty_timezone]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_bot_type]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_empty_bot_type]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_is_owner:Zulip_4.0+_ZFL59]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_is_admin:Zulip_4.0+_ZFL59]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_is_moderator:Zulip_4.0+_ZFL60]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_is_guest:Zulip_4.0+_ZFL59]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_is_member]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_is_owner:Zulip_3.0+]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_is_admin:preZulip_4.0]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_is_guest:preZulip_4.0]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_is_bot]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_bot_has_owner:Zulip_3.0+_ZFL1]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_bot_has_owner:preZulip_3.0]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_bot_has_no_owner]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_has_custom_profile_data]",
"tests/model/test_model.py::TestModel::test_get_user_info_USER_NOT_FOUND",
"tests/model/test_model.py::TestModel::test_get_user_info_sample_response",
"tests/model/test_model.py::TestModel::test__update_users_data_from_initial_data",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled0-muted0]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled0-muted1]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled0-muted2]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled0-muted3]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled1-muted0]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled1-muted1]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled1-muted2]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled1-muted3]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled2-muted0]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled2-muted1]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled2-muted2]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled2-muted3]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled3-muted0]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled3-muted1]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled3-muted2]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled3-muted3]",
"tests/model/test_model.py::TestModel::test__handle_message_event_with_Falsey_log[stream_message]",
"tests/model/test_model.py::TestModel::test__handle_message_event_with_Falsey_log[pm_message]",
"tests/model/test_model.py::TestModel::test__handle_message_event_with_Falsey_log[group_pm_message]",
"tests/model/test_model.py::TestModel::test__handle_message_event_with_valid_log[stream_message]",
"tests/model/test_model.py::TestModel::test__handle_message_event_with_valid_log[pm_message]",
"tests/model/test_model.py::TestModel::test__handle_message_event_with_valid_log[group_pm_message]",
"tests/model/test_model.py::TestModel::test__handle_message_event_with_flags[stream_message]",
"tests/model/test_model.py::TestModel::test__handle_message_event_with_flags[pm_message]",
"tests/model/test_model.py::TestModel::test__handle_message_event_with_flags[group_pm_message]",
"tests/model/test_model.py::TestModel::test__handle_message_event[stream_to_all_messages]",
"tests/model/test_model.py::TestModel::test__handle_message_event[private_to_all_private]",
"tests/model/test_model.py::TestModel::test__handle_message_event[stream_to_stream]",
"tests/model/test_model.py::TestModel::test__handle_message_event[stream_to_topic]",
"tests/model/test_model.py::TestModel::test__handle_message_event[stream_to_different_stream_same_topic]",
"tests/model/test_model.py::TestModel::test__handle_message_event[user_pm_x_appears_in_narrow_with_x]",
"tests/model/test_model.py::TestModel::test__handle_message_event[search]",
"tests/model/test_model.py::TestModel::test__handle_message_event[user_pm_x_does_not_appear_in_narrow_without_x]",
"tests/model/test_model.py::TestModel::test__handle_message_event[mentioned_msg_in_mentioned_msg_narrow]",
"tests/model/test_model.py::TestModel::test__update_topic_index[reorder_topic3]",
"tests/model/test_model.py::TestModel::test__update_topic_index[topic1_discussion_continues]",
"tests/model/test_model.py::TestModel::test__update_topic_index[new_topic4]",
"tests/model/test_model.py::TestModel::test__update_topic_index[first_topic_1]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[stream_message-not_notified_since_self_message]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[stream_message-notified_stream_and_private_since_directly_mentioned]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[stream_message-notified_stream_and_private_since_wildcard_mentioned]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[stream_message-notified_stream_since_stream_has_desktop_notifications]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[stream_message-notified_private_since_private_message]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[pm_message-not_notified_since_self_message]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[pm_message-notified_stream_and_private_since_directly_mentioned]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[pm_message-notified_stream_and_private_since_wildcard_mentioned]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[pm_message-notified_stream_since_stream_has_desktop_notifications]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[pm_message-notified_private_since_private_message]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[group_pm_message-not_notified_since_self_message]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[group_pm_message-notified_stream_and_private_since_directly_mentioned]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[group_pm_message-notified_stream_and_private_since_wildcard_mentioned]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[group_pm_message-notified_stream_since_stream_has_desktop_notifications]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[group_pm_message-notified_private_since_private_message]",
"tests/model/test_model.py::TestModel::test_notify_user_transformed_content[stream_message-simple_text]",
"tests/model/test_model.py::TestModel::test_notify_user_transformed_content[stream_message-spoiler_with_title]",
"tests/model/test_model.py::TestModel::test_notify_user_transformed_content[stream_message-spoiler_no_title]",
"tests/model/test_model.py::TestModel::test_notify_user_transformed_content[pm_message-simple_text]",
"tests/model/test_model.py::TestModel::test_notify_user_transformed_content[pm_message-spoiler_with_title]",
"tests/model/test_model.py::TestModel::test_notify_user_transformed_content[pm_message-spoiler_no_title]",
"tests/model/test_model.py::TestModel::test_notify_user_transformed_content[group_pm_message-simple_text]",
"tests/model/test_model.py::TestModel::test_notify_user_transformed_content[group_pm_message-spoiler_with_title]",
"tests/model/test_model.py::TestModel::test_notify_user_transformed_content[group_pm_message-spoiler_no_title]",
"tests/model/test_model.py::TestModel::test_notify_users_enabled[stream_message-True-True]",
"tests/model/test_model.py::TestModel::test_notify_users_enabled[stream_message-False-False]",
"tests/model/test_model.py::TestModel::test_notify_users_enabled[pm_message-True-True]",
"tests/model/test_model.py::TestModel::test_notify_users_enabled[pm_message-False-False]",
"tests/model/test_model.py::TestModel::test_notify_users_enabled[group_pm_message-True-True]",
"tests/model/test_model.py::TestModel::test_notify_users_enabled[group_pm_message-False-False]",
"tests/model/test_model.py::TestModel::test_notify_users_hides_PM_content_based_on_user_setting[pm_template-True-New",
"tests/model/test_model.py::TestModel::test_notify_users_hides_PM_content_based_on_user_setting[pm_template-False-private",
"tests/model/test_model.py::TestModel::test_notify_users_hides_PM_content_based_on_user_setting[group_pm_template-True-New",
"tests/model/test_model.py::TestModel::test_notify_users_hides_PM_content_based_on_user_setting[group_pm_template-False-private",
"tests/model/test_model.py::TestModel::test__handle_update_message_event[Only",
"tests/model/test_model.py::TestModel::test__handle_update_message_event[Subject",
"tests/model/test_model.py::TestModel::test__handle_update_message_event[Message",
"tests/model/test_model.py::TestModel::test__handle_update_message_event[Both",
"tests/model/test_model.py::TestModel::test__handle_update_message_event[Some",
"tests/model/test_model.py::TestModel::test__handle_update_message_event[message_id",
"tests/model/test_model.py::TestModel::test__update_rendered_view[msgbox_updated_in_topic_narrow]",
"tests/model/test_model.py::TestModel::test__update_rendered_view[msgbox_removed_due_to_topic_narrow_mismatch]",
"tests/model/test_model.py::TestModel::test__update_rendered_view[msgbox_updated_in_all_messages_narrow]",
"tests/model/test_model.py::TestModel::test__update_rendered_view_change_narrow[same_topic_narrow]",
"tests/model/test_model.py::TestModel::test__update_rendered_view_change_narrow[previous_topic_narrow_empty_so_change_narrow]",
"tests/model/test_model.py::TestModel::test__update_rendered_view_change_narrow[same_all_messages_narrow]",
"tests/model/test_model.py::TestModel::test__handle_reaction_event_not_in_index[add]",
"tests/model/test_model.py::TestModel::test__handle_reaction_event_not_in_index[remove]",
"tests/model/test_model.py::TestModel::test__handle_reaction_event_for_msg_in_index[add-2]",
"tests/model/test_model.py::TestModel::test__handle_reaction_event_for_msg_in_index[remove-1]",
"tests/model/test_model.py::TestModel::test_update_star_status_no_index[update_message_flags_operation0]",
"tests/model/test_model.py::TestModel::test_update_star_status_no_index[update_message_flags_operation1]",
"tests/model/test_model.py::TestModel::test_update_star_status_no_index[update_message_flags_operation2]",
"tests/model/test_model.py::TestModel::test_update_star_status_invalid_operation[update_message_flags_operation0]",
"tests/model/test_model.py::TestModel::test_update_star_status_invalid_operation[update_message_flags_operation1]",
"tests/model/test_model.py::TestModel::test_update_star_status_invalid_operation[update_message_flags_operation2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before0-flags_after0-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before0-flags_after0-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before0-flags_after0-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before0-flags_after0-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before0-flags_after0-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before0-flags_after0-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before1-flags_after1-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before1-flags_after1-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before1-flags_after1-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before1-flags_after1-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before1-flags_after1-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before1-flags_after1-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before2-flags_after2-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before2-flags_after2-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before2-flags_after2-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before2-flags_after2-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before2-flags_after2-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before2-flags_after2-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before3-flags_after3-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before3-flags_after3-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before3-flags_after3-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before3-flags_after3-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before3-flags_after3-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before3-flags_after3-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before4-flags_after4-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before4-flags_after4-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before4-flags_after4-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before4-flags_after4-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before4-flags_after4-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before4-flags_after4-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before5-flags_after5-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before5-flags_after5-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before5-flags_after5-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before5-flags_after5-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before5-flags_after5-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before5-flags_after5-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before6-flags_after6-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before6-flags_after6-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before6-flags_after6-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before6-flags_after6-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before6-flags_after6-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before6-flags_after6-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before7-flags_after7-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before7-flags_after7-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before7-flags_after7-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before7-flags_after7-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before7-flags_after7-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before7-flags_after7-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before8-flags_after8-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before8-flags_after8-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before8-flags_after8-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before8-flags_after8-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before8-flags_after8-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before8-flags_after8-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before0-flags_after0-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before0-flags_after0-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before0-flags_after0-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before0-flags_after0-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before0-flags_after0-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before0-flags_after0-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before1-flags_after1-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before1-flags_after1-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before1-flags_after1-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before1-flags_after1-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before1-flags_after1-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before1-flags_after1-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before2-flags_after2-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before2-flags_after2-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before2-flags_after2-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before2-flags_after2-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before2-flags_after2-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before2-flags_after2-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before3-flags_after3-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before3-flags_after3-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before3-flags_after3-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before3-flags_after3-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before3-flags_after3-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before3-flags_after3-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before4-flags_after4-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before4-flags_after4-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before4-flags_after4-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before4-flags_after4-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before4-flags_after4-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before4-flags_after4-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before5-flags_after5-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before5-flags_after5-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before5-flags_after5-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before5-flags_after5-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before5-flags_after5-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before5-flags_after5-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before6-flags_after6-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before6-flags_after6-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before6-flags_after6-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before6-flags_after6-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before6-flags_after6-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before6-flags_after6-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before7-flags_after7-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before7-flags_after7-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before7-flags_after7-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before7-flags_after7-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before7-flags_after7-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before7-flags_after7-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before8-flags_after8-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before8-flags_after8-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before8-flags_after8-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before8-flags_after8-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before8-flags_after8-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before8-flags_after8-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before0-flags_after0-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before0-flags_after0-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before0-flags_after0-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before0-flags_after0-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before0-flags_after0-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before0-flags_after0-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before1-flags_after1-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before1-flags_after1-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before1-flags_after1-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before1-flags_after1-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before1-flags_after1-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before1-flags_after1-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before2-flags_after2-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before2-flags_after2-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before2-flags_after2-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before2-flags_after2-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before2-flags_after2-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before2-flags_after2-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before3-flags_after3-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before3-flags_after3-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before3-flags_after3-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before3-flags_after3-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before3-flags_after3-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before3-flags_after3-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before4-flags_after4-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before4-flags_after4-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before4-flags_after4-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before4-flags_after4-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before4-flags_after4-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before4-flags_after4-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before5-flags_after5-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before5-flags_after5-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before5-flags_after5-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before5-flags_after5-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before5-flags_after5-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before5-flags_after5-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before6-flags_after6-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before6-flags_after6-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before6-flags_after6-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before6-flags_after6-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before6-flags_after6-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before6-flags_after6-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before7-flags_after7-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before7-flags_after7-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before7-flags_after7-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before7-flags_after7-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before7-flags_after7-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before7-flags_after7-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before8-flags_after8-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before8-flags_after8-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before8-flags_after8-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before8-flags_after8-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before8-flags_after8-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before8-flags_after8-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before0-flags_after0-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before0-flags_after0-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before0-flags_after0-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before0-flags_after0-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before0-flags_after0-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before0-flags_after0-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before1-flags_after1-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before1-flags_after1-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before1-flags_after1-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before1-flags_after1-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before1-flags_after1-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before1-flags_after1-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before2-flags_after2-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before2-flags_after2-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before2-flags_after2-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before2-flags_after2-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before2-flags_after2-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before2-flags_after2-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before3-flags_after3-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before3-flags_after3-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before3-flags_after3-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before3-flags_after3-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before3-flags_after3-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before3-flags_after3-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before4-flags_after4-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before4-flags_after4-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before4-flags_after4-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before4-flags_after4-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before4-flags_after4-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before4-flags_after4-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before5-flags_after5-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before5-flags_after5-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before5-flags_after5-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before5-flags_after5-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before5-flags_after5-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before5-flags_after5-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before6-flags_after6-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before6-flags_after6-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before6-flags_after6-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before6-flags_after6-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before6-flags_after6-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before6-flags_after6-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before7-flags_after7-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before7-flags_after7-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before7-flags_after7-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before7-flags_after7-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before7-flags_after7-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before7-flags_after7-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before8-flags_after8-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before8-flags_after8-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before8-flags_after8-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before8-flags_after8-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before8-flags_after8-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before8-flags_after8-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before0-flags_after0-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before0-flags_after0-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before0-flags_after0-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before0-flags_after0-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before0-flags_after0-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before0-flags_after0-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before1-flags_after1-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before1-flags_after1-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before1-flags_after1-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before1-flags_after1-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before1-flags_after1-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before1-flags_after1-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before2-flags_after2-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before2-flags_after2-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before2-flags_after2-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before2-flags_after2-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before2-flags_after2-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before2-flags_after2-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before3-flags_after3-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before3-flags_after3-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before3-flags_after3-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before3-flags_after3-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before3-flags_after3-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before3-flags_after3-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before4-flags_after4-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before4-flags_after4-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before4-flags_after4-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before4-flags_after4-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before4-flags_after4-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before4-flags_after4-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before5-flags_after5-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before5-flags_after5-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before5-flags_after5-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before5-flags_after5-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before5-flags_after5-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before5-flags_after5-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before6-flags_after6-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before6-flags_after6-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before6-flags_after6-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before6-flags_after6-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before6-flags_after6-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before6-flags_after6-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before7-flags_after7-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before7-flags_after7-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before7-flags_after7-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before7-flags_after7-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before7-flags_after7-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before7-flags_after7-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before8-flags_after8-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before8-flags_after8-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before8-flags_after8-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before8-flags_after8-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before8-flags_after8-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before8-flags_after8-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before0-flags_after0-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before0-flags_after0-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before0-flags_after0-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before0-flags_after0-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before0-flags_after0-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before0-flags_after0-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before1-flags_after1-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before1-flags_after1-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before1-flags_after1-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before1-flags_after1-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before1-flags_after1-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before1-flags_after1-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before2-flags_after2-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before2-flags_after2-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before2-flags_after2-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before2-flags_after2-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before2-flags_after2-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before2-flags_after2-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before3-flags_after3-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before3-flags_after3-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before3-flags_after3-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before3-flags_after3-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before3-flags_after3-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before3-flags_after3-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before4-flags_after4-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before4-flags_after4-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before4-flags_after4-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before4-flags_after4-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before4-flags_after4-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before4-flags_after4-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before5-flags_after5-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before5-flags_after5-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before5-flags_after5-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before5-flags_after5-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before5-flags_after5-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before5-flags_after5-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before6-flags_after6-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before6-flags_after6-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before6-flags_after6-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before6-flags_after6-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before6-flags_after6-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before6-flags_after6-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before7-flags_after7-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before7-flags_after7-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before7-flags_after7-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before7-flags_after7-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before7-flags_after7-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before7-flags_after7-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before8-flags_after8-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before8-flags_after8-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before8-flags_after8-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before8-flags_after8-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before8-flags_after8-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before8-flags_after8-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_toggle_stream_pinned_status[pinning]",
"tests/model/test_model.py::TestModel::test_toggle_stream_pinned_status[unpinning]",
"tests/model/test_model.py::TestModel::test_toggle_stream_pinned_status[first_pinned]",
"tests/model/test_model.py::TestModel::test_toggle_stream_pinned_status[last_unpinned]",
"tests/model/test_model.py::TestModel::test_toggle_stream_visual_notifications[visual_notification_enable_205]",
"tests/model/test_model.py::TestModel::test_toggle_stream_visual_notifications[visual_notification_disable_205]",
"tests/model/test_model.py::TestModel::test_toggle_stream_visual_notifications[first_notification_enable_205]",
"tests/model/test_model.py::TestModel::test_toggle_stream_visual_notifications[last_notification_disable_205]",
"tests/model/test_model.py::TestModel::test__handle_typing_event[not_in_pm_narrow]",
"tests/model/test_model.py::TestModel::test__handle_typing_event[not_in_pm_narrow_with_sender]",
"tests/model/test_model.py::TestModel::test__handle_typing_event[in_pm_narrow_with_sender_typing:start]",
"tests/model/test_model.py::TestModel::test__handle_typing_event[in_pm_narrow_with_sender_typing:start_while_animation_in_progress]",
"tests/model/test_model.py::TestModel::test__handle_typing_event[in_pm_narrow_with_sender_typing:stop]",
"tests/model/test_model.py::TestModel::test__handle_typing_event[in_pm_narrow_with_other_myself_typing:start]",
"tests/model/test_model.py::TestModel::test__handle_typing_event[in_pm_narrow_with_other_myself_typing:stop]",
"tests/model/test_model.py::TestModel::test__handle_typing_event[in_pm_narrow_with_oneself:start]",
"tests/model/test_model.py::TestModel::test__handle_typing_event[in_pm_narrow_with_oneself:stop]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_mute_streams[remove_18_in_home_view:already_unmuted:ZFLNone]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_mute_streams[remove_19_in_home_view:muted:ZFLNone]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_mute_streams[add_19_in_home_view:already_muted:ZFLNone]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_mute_streams[add_30_in_home_view:unmuted:ZFLNone]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_mute_streams[remove_30_is_muted:already_unmutedZFL139]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_mute_streams[remove_19_is_muted:muted:ZFL139]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_mute_streams[add_15_is_muted:already_muted:ZFL139]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_mute_streams[add_30_is_muted:unmuted:ZFL139]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_pin_streams[pin_stream]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_pin_streams[unpin_stream]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_visual_notifications[remove_visual_notified_stream_15:present]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_visual_notifications[add_visual_notified_stream_19:not_present]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_visual_notifications[remove_visual_notified_stream_15:not_present]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_visual_notifications[add_visual_notified_stream_19:present]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers[user_subscribed_to_stream:ZFLNone]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers[user_subscribed_to_stream:ZFL34]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers[user_subscribed_to_stream:ZFL34_should_be_35]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers[user_subscribed_to_stream:ZFL35]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers[user_unsubscribed_from_stream:ZFLNone]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers[user_unsubscribed_from_stream:ZFL34]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers[user_unsubscribed_from_stream:ZFL34_should_be_35]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers[user_unsubscribed_from_stream:ZFL35]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers_to_unsubscribed_streams[peer_subscribed_to_stream_that_user_is_unsubscribed_to]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers_to_unsubscribed_streams[peer_subscribed_to_stream_that_user_is_unsubscribed_to:ZFL35+]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers_to_unsubscribed_streams[peer_unsubscribed_from_stream_that_user_is_unsubscribed_to]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers_to_unsubscribed_streams[peer_unsubscribed_from_stream_that_user_is_unsubscribed_to:ZFL35+]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers_multiple_users_one_stream[users_subscribed_to_stream:ZFL34_should_be_35]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers_multiple_users_one_stream[users_subscribed_to_stream:ZFL35]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers_multiple_users_one_stream[users_unsubscribed_from_stream:ZFL34_should_be_35]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers_multiple_users_one_stream[users_unsubscribed_from_stream:ZFL35]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers_one_user_multiple_streams[user_subscribed_to_streams:ZFL34_should_be_35]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers_one_user_multiple_streams[user_subscribed_to_streams:ZFL35]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers_one_user_multiple_streams[user_unsubscribed_from_streams:ZFL34_should_be_35]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers_one_user_multiple_streams[user_unsubscribed_from_streams:ZFL35]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__general[full_name]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__general[timezone]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__general[billing_admin_role]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__general[role]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__general[avatar]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__general[display_email]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__general[delivery_email]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__custom_profile_data__update_data[Short",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__custom_profile_data__update_data[Long",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__custom_profile_data__update_data[List",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__custom_profile_data__update_data[Date",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__custom_profile_data__update_data[Link-no_custom]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__custom_profile_data__update_data[Link-many_custom]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__custom_profile_data__update_data[Person",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__custom_profile_data__update_data[External",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__custom_profile_data__update_data[Pronouns-no_custom]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__custom_profile_data__update_data[Pronouns-many_custom]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__custom_profile_data__remove_data[update_data0-8-no_custom]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__custom_profile_data__remove_data[update_data0-8-many_custom]",
"tests/model/test_model.py::TestModel::test__handle_user_settings_event[True]",
"tests/model/test_model.py::TestModel::test__handle_user_settings_event[False]",
"tests/model/test_model.py::TestModel::test_update_pm_content_in_desktop_notifications[True]",
"tests/model/test_model.py::TestModel::test_update_pm_content_in_desktop_notifications[False]",
"tests/model/test_model.py::TestModel::test_update_twenty_four_hour_format[True]",
"tests/model/test_model.py::TestModel::test_update_twenty_four_hour_format[False]",
"tests/model/test_model.py::TestModel::test_is_muted_stream[muted_stream]",
"tests/model/test_model.py::TestModel::test_is_muted_stream[unmuted_stream]",
"tests/model/test_model.py::TestModel::test_is_muted_stream[unmuted_stream_nostreamsmuted]",
"tests/model/test_model.py::TestModel::test_is_visual_notifications_enabled[notifications_enabled]",
"tests/model/test_model.py::TestModel::test_is_visual_notifications_enabled[notifications_disabled]",
"tests/model/test_model.py::TestModel::test_is_visual_notifications_enabled[notifications_disabled_no_streams_to_notify]",
"tests/model/test_model.py::TestModel::test_is_muted_topic[zulip_feature_level:None-topic0-False]",
"tests/model/test_model.py::TestModel::test_is_muted_topic[zulip_feature_level:None-topic1-True]",
"tests/model/test_model.py::TestModel::test_is_muted_topic[zulip_feature_level:None-topic2-True]",
"tests/model/test_model.py::TestModel::test_is_muted_topic[zulip_feature_level:None-topic3-False]",
"tests/model/test_model.py::TestModel::test_is_muted_topic[zulip_feature_level:1-topic0-False]",
"tests/model/test_model.py::TestModel::test_is_muted_topic[zulip_feature_level:1-topic1-True]",
"tests/model/test_model.py::TestModel::test_is_muted_topic[zulip_feature_level:1-topic2-True]",
"tests/model/test_model.py::TestModel::test_is_muted_topic[zulip_feature_level:1-topic3-False]",
"tests/model/test_model.py::TestModel::test_get_next_unread_pm",
"tests/model/test_model.py::TestModel::test_get_next_unread_pm_again",
"tests/model/test_model.py::TestModel::test_get_next_unread_pm_no_unread",
"tests/model/test_model.py::TestModel::test_is_user_subscribed_to_stream[subscribed_stream]",
"tests/model/test_model.py::TestModel::test_is_user_subscribed_to_stream[unsubscribed_stream]",
"tests/model/test_model.py::TestModel::test_fetch_message_history_success[unedited_message-response0]",
"tests/model/test_model.py::TestModel::test_fetch_message_history_success[edited_message-response0]",
"tests/model/test_model.py::TestModel::test_fetch_message_history_error[response0]",
"tests/model/test_model.py::TestModel::test_user_name_from_id_valid[1001-Human",
"tests/model/test_model.py::TestModel::test_user_name_from_id_invalid[-1]",
"tests/model/test_model.py::TestModel::test_generate_all_emoji_data",
"tests/model/test_model.py::TestModel::test__handle_update_emoji_event[realm_emoji_with_same_name_as_unicode_emoji_added]",
"tests/model/test_model.py::TestModel::test__handle_update_emoji_event[realm_emoji_with_same_name_as_unicode_emoji_removed]",
"tests/model/test_model.py::TestModel::test__handle_update_emoji_event[realm_emoji_with_name_as_zulip_added]",
"tests/model/test_model.py::TestModel::test__handle_update_emoji_event[realm_emoji_with_name_as_zulip_removed]",
"tests/model/test_model.py::TestModel::test__handle_update_emoji_event[realm_emoji_added]",
"tests/model/test_model.py::TestModel::test__handle_update_emoji_event[realm_emoji_removed]",
"tests/model/test_model.py::TestModel::test_poll_for_events__no_disconnect",
"tests/model/test_model.py::TestModel::test_poll_for_events__reconnect_ok[reconnect_on_1st_attempt]",
"tests/model/test_model.py::TestModel::test_poll_for_events__reconnect_ok[reconnect_on_2nd_attempt]",
"tests/model/test_model.py::TestModel::test_poll_for_events__reconnect_ok[reconnect_on_3rd_attempt]",
"tests/ui/test_ui_tools.py::TestModListWalker::test_extend[5-0]",
"tests/ui/test_ui_tools.py::TestModListWalker::test_extend[0-0]",
"tests/ui/test_ui_tools.py::TestModListWalker::test__set_focus",
"tests/ui/test_ui_tools.py::TestModListWalker::test_set_focus",
"tests/ui/test_ui_tools.py::TestMessageView::test_init",
"tests/ui/test_ui_tools.py::TestMessageView::test_main_view[None-1]",
"tests/ui/test_ui_tools.py::TestMessageView::test_main_view[0-0]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_empty_log[ids_in_narrow0-messages_fetched0]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_empty_log[ids_in_narrow0-messages_fetched1]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_empty_log[ids_in_narrow0-messages_fetched2]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_empty_log[ids_in_narrow1-messages_fetched0]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_empty_log[ids_in_narrow1-messages_fetched1]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_empty_log[ids_in_narrow1-messages_fetched2]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_mocked_log[99-other_ids_in_narrow0-messages_fetched0]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_mocked_log[99-other_ids_in_narrow0-messages_fetched1]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_mocked_log[99-other_ids_in_narrow0-messages_fetched2]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_mocked_log[99-other_ids_in_narrow1-messages_fetched0]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_mocked_log[99-other_ids_in_narrow1-messages_fetched1]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_mocked_log[99-other_ids_in_narrow1-messages_fetched2]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_mocked_log[99-other_ids_in_narrow2-messages_fetched0]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_mocked_log[99-other_ids_in_narrow2-messages_fetched1]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_mocked_log[99-other_ids_in_narrow2-messages_fetched2]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_new_messages_empty_log[ids_in_narrow0]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_new_messages_mocked_log[ids_in_narrow0]",
"tests/ui/test_ui_tools.py::TestMessageView::test_mouse_event[mouse_scroll_up]",
"tests/ui/test_ui_tools.py::TestMessageView::test_mouse_event[mouse_scroll_down]",
"tests/ui/test_ui_tools.py::TestMessageView::test_keypress_GO_DOWN[down]",
"tests/ui/test_ui_tools.py::TestMessageView::test_keypress_GO_DOWN[j]",
"tests/ui/test_ui_tools.py::TestMessageView::test_keypress_GO_DOWN_exception[down-True]",
"tests/ui/test_ui_tools.py::TestMessageView::test_keypress_GO_DOWN_exception[down-False]",
"tests/ui/test_ui_tools.py::TestMessageView::test_keypress_GO_DOWN_exception[j-True]",
"tests/ui/test_ui_tools.py::TestMessageView::test_keypress_GO_DOWN_exception[j-False]",
"tests/ui/test_ui_tools.py::TestMessageView::test_keypress_GO_UP[up]",
"tests/ui/test_ui_tools.py::TestMessageView::test_keypress_GO_UP[k]",
"tests/ui/test_ui_tools.py::TestMessageView::test_keypress_GO_UP_exception[up-True]",
"tests/ui/test_ui_tools.py::TestMessageView::test_keypress_GO_UP_exception[up-False]",
"tests/ui/test_ui_tools.py::TestMessageView::test_keypress_GO_UP_exception[k-True]",
"tests/ui/test_ui_tools.py::TestMessageView::test_keypress_GO_UP_exception[k-False]",
"tests/ui/test_ui_tools.py::TestMessageView::test_read_message",
"tests/ui/test_ui_tools.py::TestMessageView::test_message_calls_search_and_header_bar",
"tests/ui/test_ui_tools.py::TestMessageView::test_read_message_no_msgw",
"tests/ui/test_ui_tools.py::TestMessageView::test_read_message_in_explore_mode",
"tests/ui/test_ui_tools.py::TestMessageView::test_read_message_search_narrow",
"tests/ui/test_ui_tools.py::TestMessageView::test_read_message_last_unread_message_focused[stream_message]",
"tests/ui/test_ui_tools.py::TestMessageView::test_read_message_last_unread_message_focused[pm_message]",
"tests/ui/test_ui_tools.py::TestMessageView::test_read_message_last_unread_message_focused[group_pm_message]",
"tests/ui/test_ui_tools.py::TestStreamsViewDivider::test_init",
"tests/ui/test_ui_tools.py::TestStreamsView::test_init",
"tests/ui/test_ui_tools.py::TestStreamsView::test_update_streams[f-expected_log0-to_pin0]",
"tests/ui/test_ui_tools.py::TestStreamsView::test_update_streams[bar-expected_log1-to_pin1]",
"tests/ui/test_ui_tools.py::TestStreamsView::test_update_streams[foo-expected_log2-to_pin2]",
"tests/ui/test_ui_tools.py::TestStreamsView::test_update_streams[FOO-expected_log3-to_pin3]",
"tests/ui/test_ui_tools.py::TestStreamsView::test_update_streams[test-expected_log4-to_pin4]",
"tests/ui/test_ui_tools.py::TestStreamsView::test_update_streams[here-expected_log5-to_pin5]",
"tests/ui/test_ui_tools.py::TestStreamsView::test_update_streams[test",
"tests/ui/test_ui_tools.py::TestStreamsView::test_update_streams[f-expected_log7-to_pin7]",
"tests/ui/test_ui_tools.py::TestStreamsView::test_update_streams[FOO-expected_log8-to_pin8]",
"tests/ui/test_ui_tools.py::TestStreamsView::test_update_streams[bar-expected_log9-to_pin9]",
"tests/ui/test_ui_tools.py::TestStreamsView::test_update_streams[baar-search",
"tests/ui/test_ui_tools.py::TestStreamsView::test_mouse_event[mouse_scroll_up]",
"tests/ui/test_ui_tools.py::TestStreamsView::test_mouse_event[mouse_scroll_down]",
"tests/ui/test_ui_tools.py::TestStreamsView::test_keypress_SEARCH_STREAMS[q]",
"tests/ui/test_ui_tools.py::TestStreamsView::test_keypress_GO_BACK[esc]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_init",
"tests/ui/test_ui_tools.py::TestTopicsView::test_update_topics[f-expected_log0]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_update_topics[a-expected_log1]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_update_topics[bar-expected_log2]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_update_topics[foo-expected_log3]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_update_topics[FOO-expected_log4]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_update_topics[(no-expected_log5]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_update_topics[topic-expected_log6]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_update_topics[cc-search",
"tests/ui/test_ui_tools.py::TestTopicsView::test_update_topics_list[reorder_topic3]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_update_topics_list[topic1_discussion_continues]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_update_topics_list[new_topic4]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_update_topics_list[first_topic_1]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_keypress_SEARCH_TOPICS[q]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_keypress_GO_BACK[esc]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_mouse_event[mouse_scroll_up]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_mouse_event[mouse_scroll_down]",
"tests/ui/test_ui_tools.py::TestUsersView::test_mouse_event[mouse_scroll_up]",
"tests/ui/test_ui_tools.py::TestUsersView::test_mouse_event[mouse_scroll_down]",
"tests/ui/test_ui_tools.py::TestUsersView::test_mouse_event_left_click[ignore_mouse_click]",
"tests/ui/test_ui_tools.py::TestUsersView::test_mouse_event_left_click[handle_mouse_click]",
"tests/ui/test_ui_tools.py::TestUsersView::test_mouse_event_invalid[unsupported_mouse_release_action]",
"tests/ui/test_ui_tools.py::TestUsersView::test_mouse_event_invalid[unsupported_right_click_mouse_press_action]",
"tests/ui/test_ui_tools.py::TestUsersView::test_mouse_event_invalid[invalid_event_button_combination]",
"tests/ui/test_ui_tools.py::TestMiddleColumnView::test_init",
"tests/ui/test_ui_tools.py::TestMiddleColumnView::test_keypress_focus_header[/]",
"tests/ui/test_ui_tools.py::TestMiddleColumnView::test_keypress_SEARCH_MESSAGES[/]",
"tests/ui/test_ui_tools.py::TestMiddleColumnView::test_keypress_REPLY_MESSAGE[r]",
"tests/ui/test_ui_tools.py::TestMiddleColumnView::test_keypress_REPLY_MESSAGE[enter]",
"tests/ui/test_ui_tools.py::TestMiddleColumnView::test_keypress_STREAM_MESSAGE[c]",
"tests/ui/test_ui_tools.py::TestMiddleColumnView::test_keypress_REPLY_AUTHOR[R]",
"tests/ui/test_ui_tools.py::TestMiddleColumnView::test_keypress_NEXT_UNREAD_PM_stream[p]",
"tests/ui/test_ui_tools.py::TestMiddleColumnView::test_keypress_NEXT_UNREAD_PM_no_pm[p]",
"tests/ui/test_ui_tools.py::TestMiddleColumnView::test_keypress_PRIVATE_MESSAGE[x]",
"tests/ui/test_ui_tools.py::TestRightColumnView::test_init",
"tests/ui/test_ui_tools.py::TestRightColumnView::test_update_user_list_editor_mode",
"tests/ui/test_ui_tools.py::TestRightColumnView::test_update_user_list[user",
"tests/ui/test_ui_tools.py::TestRightColumnView::test_update_user_list[no",
"tests/ui/test_ui_tools.py::TestRightColumnView::test_update_user_presence",
"tests/ui/test_ui_tools.py::TestRightColumnView::test_users_view[None-1-False-active]",
"tests/ui/test_ui_tools.py::TestRightColumnView::test_users_view[users1-1-True-active]",
"tests/ui/test_ui_tools.py::TestRightColumnView::test_users_view[None-0-False-inactive]",
"tests/ui/test_ui_tools.py::TestRightColumnView::test_keypress_SEARCH_PEOPLE[w]",
"tests/ui/test_ui_tools.py::TestRightColumnView::test_keypress_GO_BACK[esc]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_menu_view",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned0]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned1]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned2]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned3]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned4]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned5]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned6]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned7]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned8]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned9]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned10]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned11]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned12]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned13]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned14]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned15]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned16]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned17]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned18]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned19]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned20]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned21]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned22]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned23]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned24]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned25]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned26]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned27]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned28]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned29]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned30]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned31]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_topics_view",
"tests/ui/test_ui_tools.py::TestTabView::test_tab_render[3-10-expected_output0]"
] | {
"failed_lite_validators": [
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-03-25T02:58:14Z" | apache-2.0 |
|
zulip__zulip-terminal-1382 | diff --git a/docs/hotkeys.md b/docs/hotkeys.md
index c9677e8..38ad92b 100644
--- a/docs/hotkeys.md
+++ b/docs/hotkeys.md
@@ -55,6 +55,7 @@
|Narrow to the stream of the current message|<kbd>s</kbd>|
|Narrow to the topic of the current message|<kbd>S</kbd>|
|Narrow to a topic/direct-chat, or stream/all-direct-messages|<kbd>z</kbd>|
+|Toggle first emoji reaction on selected message|<kbd>=</kbd>|
|Add/remove thumbs-up reaction to the current message|<kbd>+</kbd>|
|Add/remove star status of the current message|<kbd>ctrl</kbd> + <kbd>s</kbd> / <kbd>*</kbd>|
|Show/hide message information|<kbd>i</kbd>|
diff --git a/zulipterminal/config/keys.py b/zulipterminal/config/keys.py
index 27c9f35..f6f6c09 100644
--- a/zulipterminal/config/keys.py
+++ b/zulipterminal/config/keys.py
@@ -178,6 +178,11 @@ KEY_BINDINGS: Dict[str, KeyBinding] = {
'Narrow to a topic/direct-chat, or stream/all-direct-messages',
'key_category': 'msg_actions',
},
+ 'REACTION_AGREEMENT': {
+ 'keys': ['='],
+ 'help_text': 'Toggle first emoji reaction on selected message',
+ 'key_category': 'msg_actions',
+ },
'TOGGLE_TOPIC': {
'keys': ['t'],
'help_text': 'Toggle topics in a stream',
diff --git a/zulipterminal/model.py b/zulipterminal/model.py
index 82d809a..7073e4f 100644
--- a/zulipterminal/model.py
+++ b/zulipterminal/model.py
@@ -2,6 +2,7 @@
Defines the `Model`, fetching and storing data retrieved from the Zulip server
"""
+import bisect
import itertools
import json
import time
@@ -111,7 +112,6 @@ class Model:
self.stream_id: Optional[int] = None
self.recipients: FrozenSet[Any] = frozenset()
self.index = initial_index
- self._last_unread_topic = None
self.last_unread_pm = None
self.user_id = -1
@@ -886,23 +886,67 @@ class Model:
topic_to_search = (stream_name, topic)
return topic_to_search in self._muted_topics
- def get_next_unread_topic(self) -> Optional[Tuple[int, str]]:
+ def stream_topic_from_message_id(
+ self, message_id: int
+ ) -> Optional[Tuple[int, str]]:
+ """
+ Returns the stream and topic of a message of a given message id.
+ If the message is not a stream message or if it is not present in the index,
+ None is returned.
+ """
+ message = self.index["messages"].get(message_id, None)
+ if message is not None and message["type"] == "stream":
+ stream_id = message["stream_id"]
+ topic = message["subject"]
+ return (stream_id, topic)
+ return None
+
+ def next_unread_topic_from_message_id(
+ self, current_message: Optional[int]
+ ) -> Optional[Tuple[int, str]]:
+ if current_message:
+ current_topic = self.stream_topic_from_message_id(current_message)
+ else:
+ current_topic = (
+ self.stream_id_from_name(self.narrow[0][1]),
+ self.narrow[1][1],
+ )
unread_topics = sorted(self.unread_counts["unread_topics"].keys())
next_topic = False
- if self._last_unread_topic not in unread_topics:
+ stream_start: Optional[Tuple[int, str]] = None
+ if current_topic is None:
next_topic = True
+ elif current_topic not in unread_topics:
+ # insert current_topic in list of unread_topics for the case where
+ # current_topic is not in unread_topics, and the next unmuted topic
+ # is to be returned. This does not modify the original unread topics
+ # data, and is just used to compute the next unmuted topic to be returned.
+ bisect.insort(unread_topics, current_topic)
# loop over unread_topics list twice for the case that last_unread_topic was
# the last valid unread_topic in unread_topics list.
for unread_topic in unread_topics * 2:
stream_id, topic_name = unread_topic
- if (
- not self.is_muted_topic(stream_id, topic_name)
- and not self.is_muted_stream(stream_id)
- and next_topic
- ):
- self._last_unread_topic = unread_topic
- return unread_topic
- if unread_topic == self._last_unread_topic:
+ if not self.is_muted_topic(
+ stream_id, topic_name
+ ) and not self.is_muted_stream(stream_id):
+ if next_topic:
+ if unread_topic == current_topic:
+ return None
+ if (
+ current_topic is not None
+ and unread_topic[0] != current_topic[0]
+ and stream_start != current_topic
+ ):
+ return stream_start
+ return unread_topic
+
+ if (
+ stream_start is None
+ and current_topic is not None
+ and unread_topic[0] == current_topic[0]
+ ):
+ stream_start = unread_topic
+ if unread_topic == current_topic:
next_topic = True
return None
diff --git a/zulipterminal/ui_tools/views.py b/zulipterminal/ui_tools/views.py
index 64eebeb..1622114 100644
--- a/zulipterminal/ui_tools/views.py
+++ b/zulipterminal/ui_tools/views.py
@@ -236,6 +236,15 @@ class MessageView(urwid.ListBox):
message = self.focus.original_widget.message
self.model.toggle_message_star_status(message)
+ elif is_command_key("REACTION_AGREEMENT", key) and self.focus is not None:
+ message = self.focus.original_widget.message
+ message_reactions = message["reactions"]
+ if len(message_reactions) > 0:
+ for reaction in message_reactions:
+ emoji = reaction["emoji_name"]
+ self.model.toggle_message_reaction(message, emoji)
+ break
+
key = super().keypress(size, key)
return key
@@ -584,9 +593,20 @@ class MiddleColumnView(urwid.Frame):
elif is_command_key("NEXT_UNREAD_TOPIC", key):
# narrow to next unread topic
- stream_topic = self.model.get_next_unread_topic()
- if stream_topic is None:
+ focus = self.view.message_view.focus
+ narrow = self.model.narrow
+ if focus:
+ current_msg_id = focus.original_widget.message["id"]
+ stream_topic = self.model.next_unread_topic_from_message_id(
+ current_msg_id
+ )
+ if stream_topic is None:
+ return key
+ elif narrow[0][0] == "stream" and narrow[1][0] == "topic":
+ stream_topic = self.model.next_unread_topic_from_message_id(None)
+ else:
return key
+
stream_id, topic = stream_topic
self.controller.narrow_to_topic(
stream_name=self.model.stream_dict[stream_id]["name"],
| zulip/zulip-terminal | 2781e34514be0e606a3f88ebf8fd409781d9f625 | diff --git a/tests/model/test_model.py b/tests/model/test_model.py
index 2bf150a..fe2ba55 100644
--- a/tests/model/test_model.py
+++ b/tests/model/test_model.py
@@ -72,7 +72,6 @@ class TestModel:
assert model.stream_dict == stream_dict
assert model.recipients == frozenset()
assert model.index == initial_index
- assert model._last_unread_topic is None
assert model.last_unread_pm is None
model.get_messages.assert_called_once_with(
num_before=30, num_after=10, anchor=None
@@ -3900,7 +3899,7 @@ class TestModel:
assert return_value == is_muted
@pytest.mark.parametrize(
- "unread_topics, last_unread_topic, next_unread_topic",
+ "unread_topics, current_topic, next_unread_topic",
[
case(
{(1, "topic"), (2, "topic2")},
@@ -3920,10 +3919,10 @@ class TestModel:
(1, "topic"),
id="unread_present_before_previous_topic",
),
- case( # TODO Should be None? (2 other cases)
+ case(
{(1, "topic")},
(1, "topic"),
- (1, "topic"),
+ None,
id="unread_still_present_in_topic",
),
case(
@@ -3993,16 +3992,42 @@ class TestModel:
(2, "topic2"),
id="unread_present_after_previous_topic_muted",
),
+ case(
+ {(1, "topic1"), (2, "topic2"), (2, "topic2 muted")},
+ (2, "topic1"),
+ (2, "topic2"),
+ id="unmuted_unread_present_in_same_stream_as_current_topic_not_in_unread_list",
+ ),
+ case(
+ {(1, "topic1"), (2, "topic2 muted"), (4, "topic4")},
+ (2, "topic1"),
+ (4, "topic4"),
+ id="unmuted_unread_present_in_next_stream_as_current_topic_not_in_unread_list",
+ ),
+ case(
+ {(1, "topic1"), (2, "topic2 muted"), (3, "topic3")},
+ (2, "topic1"),
+ (1, "topic1"),
+ id="unmuted_unread_not_present_in_next_stream_as_current_topic_not_in_unread_list",
+ ),
+ case(
+ {(1, "topic1"), (1, "topic11"), (2, "topic2")},
+ (1, "topic11"),
+ (1, "topic1"),
+ id="unread_present_in_same_stream_wrap_around",
+ ),
],
)
- def test_get_next_unread_topic(
- self, model, unread_topics, last_unread_topic, next_unread_topic
+ def test_next_unread_topic_from_message(
+ self, mocker, model, unread_topics, current_topic, next_unread_topic
):
# NOTE Not important how many unreads per topic, so just use '1'
model.unread_counts = {
"unread_topics": {stream_topic: 1 for stream_topic in unread_topics}
}
- model._last_unread_topic = last_unread_topic
+
+ current_message_id = 10 # Arbitrary value due to mock below
+ model.stream_topic_from_message_id = mocker.Mock(return_value=current_topic)
# Minimal extra streams for muted stream testing (should not exist otherwise)
assert {3, 4} & set(model.stream_dict) == set()
@@ -4020,7 +4045,38 @@ class TestModel:
]
}
- unread_topic = model.get_next_unread_topic()
+ unread_topic = model.next_unread_topic_from_message_id(current_message_id)
+
+ assert unread_topic == next_unread_topic
+
+ @pytest.mark.parametrize(
+ "unread_topics, empty_narrow, narrow_stream_id, next_unread_topic",
+ [
+ case(
+ {(1, "topic1"), (1, "topic2"), (2, "topic3")},
+ [["stream", "Stream 1"], ["topic", "topic1.5"]],
+ 1,
+ (1, "topic2"),
+ ),
+ ],
+ )
+ def test_next_unread_topic_from_message__empty_narrow(
+ self,
+ mocker,
+ model,
+ unread_topics,
+ empty_narrow,
+ narrow_stream_id,
+ next_unread_topic,
+ ):
+ # NOTE Not important how many unreads per topic, so just use '1'
+ model.unread_counts = {
+ "unread_topics": {stream_topic: 1 for stream_topic in unread_topics}
+ }
+ model.stream_id_from_name = mocker.Mock(return_value=narrow_stream_id)
+ model.narrow = empty_narrow
+
+ unread_topic = model.next_unread_topic_from_message_id(None)
assert unread_topic == next_unread_topic
@@ -4043,6 +4099,21 @@ class TestModel:
assert return_value is None
assert model.last_unread_pm is None
+ @pytest.mark.parametrize(
+ "message_id, expected_value",
+ [
+ case(537286, (205, "Test"), id="stream_message"),
+ case(537287, None, id="direct_message"),
+ case(537289, None, id="non-existent message"),
+ ],
+ )
+ def test_stream_topic_from_message_id(
+ self, mocker, model, message_id, expected_value, empty_index
+ ):
+ model.index = empty_index
+ current_topic = model.stream_topic_from_message_id(message_id)
+ assert current_topic == expected_value
+
@pytest.mark.parametrize(
"stream_id, expected_response",
[
diff --git a/tests/ui/test_ui_tools.py b/tests/ui/test_ui_tools.py
index c04c9c3..324ee04 100644
--- a/tests/ui/test_ui_tools.py
+++ b/tests/ui/test_ui_tools.py
@@ -887,9 +887,10 @@ class TestMiddleColumnView:
):
size = widget_size(mid_col_view)
mocker.patch(MIDCOLVIEW + ".focus_position")
+ mocker.patch.object(self.view, "message_view")
mid_col_view.model.stream_dict = {1: {"name": "stream"}}
- mid_col_view.model.get_next_unread_topic.return_value = (1, "topic")
+ mid_col_view.model.next_unread_topic_from_message_id.return_value = (1, "topic")
return_value = mid_col_view.keypress(size, key)
@@ -904,7 +905,8 @@ class TestMiddleColumnView:
):
size = widget_size(mid_col_view)
mocker.patch(MIDCOLVIEW + ".focus_position")
- mid_col_view.model.get_next_unread_topic.return_value = None
+ mocker.patch.object(self.view, "message_view")
+ mid_col_view.model.next_unread_topic_from_message_id.return_value = None
return_value = mid_col_view.keypress(size, key)
| Support new `=` keyboard shortcut for 'reaction agreement'
This is the equivalent of zulip/zulip#24266 for this project.
Also see zulip/zulip#24828 for the related documentation, which should accompany this. | 0 | 2401580b6f41fe72f1360493ee46e8a842bd04ba | [
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_after_no_state]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_after_previous_topic]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_before_previous_topic]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_still_present_in_topic]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[no_unreads_with_previous_topic_state]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[no_unreads_with_no_previous_topic_state]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_before_previous_topic_skipping_muted_stream]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_after_previous_topic_skipping_muted_stream]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_only_in_muted_stream]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_starting_in_muted_stream]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_skipping_first_muted_stream_unread]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_only_in_muted_topic]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_starting_in_muted_topic]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_only_in_muted_topic_in_muted_stream]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_after_previous_topic_skipping_muted_topic]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_after_previous_topic_muted]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unmuted_unread_present_in_same_stream_as_current_topic_not_in_unread_list]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unmuted_unread_present_in_next_stream_as_current_topic_not_in_unread_list]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unmuted_unread_not_present_in_next_stream_as_current_topic_not_in_unread_list]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message[unread_present_in_same_stream_wrap_around]",
"tests/model/test_model.py::TestModel::test_next_unread_topic_from_message__empty_narrow[unread_topics0-empty_narrow0-1-next_unread_topic0]",
"tests/model/test_model.py::TestModel::test_stream_topic_from_message_id[stream_message]",
"tests/model/test_model.py::TestModel::test_stream_topic_from_message_id[direct_message]",
"tests/model/test_model.py::TestModel::test_stream_topic_from_message_id[non-existent",
"tests/ui/test_ui_tools.py::TestMiddleColumnView::test_keypress_NEXT_UNREAD_TOPIC_stream[n]",
"tests/ui/test_ui_tools.py::TestMiddleColumnView::test_keypress_NEXT_UNREAD_TOPIC_no_stream[n]"
] | [
"tests/model/test_model.py::TestModel::test_init",
"tests/model/test_model.py::TestModel::test_init_user_settings[None-True]",
"tests/model/test_model.py::TestModel::test_init_user_settings[True-True]",
"tests/model/test_model.py::TestModel::test_init_user_settings[False-False]",
"tests/model/test_model.py::TestModel::test_user_settings_expected_contents",
"tests/model/test_model.py::TestModel::test_init_muted_topics[zulip_feature_level:None]",
"tests/model/test_model.py::TestModel::test_init_muted_topics[zulip_feature_level:1]",
"tests/model/test_model.py::TestModel::test_init_InvalidAPIKey_response",
"tests/model/test_model.py::TestModel::test_init_ZulipError_exception",
"tests/model/test_model.py::TestModel::test_register_initial_desired_events",
"tests/model/test_model.py::TestModel::test_normalize_and_cache_message_retention_text[ZFL=None_no_stream_retention_realm_retention=None]",
"tests/model/test_model.py::TestModel::test_normalize_and_cache_message_retention_text[ZFL=16_no_stream_retention_realm_retention=-1]",
"tests/model/test_model.py::TestModel::test_normalize_and_cache_message_retention_text[ZFL=17_stream_retention_days=30]",
"tests/model/test_model.py::TestModel::test_normalize_and_cache_message_retention_text[ZFL=18_stream_retention_days=[None,",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow0-1]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow0-5]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow0-None]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow1-1]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow1-5]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow1-None]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow2-1]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow2-5]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow2-None]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow3-1]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow3-5]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow3-None]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow4-1]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow4-5]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow4-None]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow5-1]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow5-5]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow5-None]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow6-1]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow6-5]",
"tests/model/test_model.py::TestModel::test_get_focus_in_current_narrow_individually[narrow6-None]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow0-1]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow0-5]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow1-1]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow1-5]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow2-1]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow2-5]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow3-1]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow3-5]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow4-1]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow4-5]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow5-1]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow5-5]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow6-1]",
"tests/model/test_model.py::TestModel::test_set_focus_in_current_narrow[narrow6-5]",
"tests/model/test_model.py::TestModel::test_is_search_narrow[narrow0-False]",
"tests/model/test_model.py::TestModel::test_is_search_narrow[narrow1-True]",
"tests/model/test_model.py::TestModel::test_is_search_narrow[narrow2-False]",
"tests/model/test_model.py::TestModel::test_is_search_narrow[narrow3-True]",
"tests/model/test_model.py::TestModel::test_is_search_narrow[narrow4-True]",
"tests/model/test_model.py::TestModel::test_is_search_narrow[narrow5-False]",
"tests/model/test_model.py::TestModel::test_is_search_narrow[narrow6-True]",
"tests/model/test_model.py::TestModel::test_is_search_narrow[narrow7-False]",
"tests/model/test_model.py::TestModel::test_is_search_narrow[narrow8-True]",
"tests/model/test_model.py::TestModel::test_is_search_narrow[narrow9-True]",
"tests/model/test_model.py::TestModel::test_is_search_narrow[narrow10-True]",
"tests/model/test_model.py::TestModel::test_set_narrow_bad_input[bad_args0]",
"tests/model/test_model.py::TestModel::test_set_narrow_bad_input[bad_args1]",
"tests/model/test_model.py::TestModel::test_set_narrow_bad_input[bad_args2]",
"tests/model/test_model.py::TestModel::test_set_narrow_bad_input[bad_args3]",
"tests/model/test_model.py::TestModel::test_set_narrow_already_set[narrow0-good_args0]",
"tests/model/test_model.py::TestModel::test_set_narrow_already_set[narrow1-good_args1]",
"tests/model/test_model.py::TestModel::test_set_narrow_already_set[narrow2-good_args2]",
"tests/model/test_model.py::TestModel::test_set_narrow_already_set[narrow3-good_args3]",
"tests/model/test_model.py::TestModel::test_set_narrow_already_set[narrow4-good_args4]",
"tests/model/test_model.py::TestModel::test_set_narrow_already_set[narrow5-good_args5]",
"tests/model/test_model.py::TestModel::test_set_narrow_already_set[narrow6-good_args6]",
"tests/model/test_model.py::TestModel::test_set_narrow_not_already_set[initial_narrow0-narrow0-good_args0]",
"tests/model/test_model.py::TestModel::test_set_narrow_not_already_set[initial_narrow1-narrow1-good_args1]",
"tests/model/test_model.py::TestModel::test_set_narrow_not_already_set[initial_narrow2-narrow2-good_args2]",
"tests/model/test_model.py::TestModel::test_set_narrow_not_already_set[initial_narrow3-narrow3-good_args3]",
"tests/model/test_model.py::TestModel::test_set_narrow_not_already_set[initial_narrow4-narrow4-good_args4]",
"tests/model/test_model.py::TestModel::test_set_narrow_not_already_set[initial_narrow5-narrow5-good_args5]",
"tests/model/test_model.py::TestModel::test_set_narrow_not_already_set[initial_narrow6-narrow6-good_args6]",
"tests/model/test_model.py::TestModel::test_get_message_ids_in_current_narrow[narrow0-index0-current_ids0]",
"tests/model/test_model.py::TestModel::test_get_message_ids_in_current_narrow[narrow1-index1-current_ids1]",
"tests/model/test_model.py::TestModel::test_get_message_ids_in_current_narrow[narrow2-index2-current_ids2]",
"tests/model/test_model.py::TestModel::test_get_message_ids_in_current_narrow[narrow3-index3-current_ids3]",
"tests/model/test_model.py::TestModel::test_get_message_ids_in_current_narrow[narrow4-index4-current_ids4]",
"tests/model/test_model.py::TestModel::test_get_message_ids_in_current_narrow[narrow5-index5-current_ids5]",
"tests/model/test_model.py::TestModel::test_get_message_ids_in_current_narrow[narrow6-index6-current_ids6]",
"tests/model/test_model.py::TestModel::test_get_message_ids_in_current_narrow[narrow7-index7-current_ids7]",
"tests/model/test_model.py::TestModel::test_get_message_ids_in_current_narrow[narrow8-index8-current_ids8]",
"tests/model/test_model.py::TestModel::test_get_message_ids_in_current_narrow[narrow9-index9-current_ids9]",
"tests/model/test_model.py::TestModel::test_get_message_ids_in_current_narrow[narrow10-index10-current_ids10]",
"tests/model/test_model.py::TestModel::test__fetch_topics_in_streams[response0-expected_index0-]",
"tests/model/test_model.py::TestModel::test__fetch_topics_in_streams[response1-expected_index1-]",
"tests/model/test_model.py::TestModel::test__fetch_topics_in_streams[response2-expected_index2-Some",
"tests/model/test_model.py::TestModel::test_topics_in_stream[topics_index0-False]",
"tests/model/test_model.py::TestModel::test_topics_in_stream[topics_index1-True]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_unicode_original_no_existing_emoji-user_id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_unicode_original_no_existing_emoji-id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_unicode_original_no_existing_emoji-None]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_realm_original_no_existing_emoji-user_id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_realm_original_no_existing_emoji-id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_realm_original_no_existing_emoji-None]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_unicode_original_mine_existing_different_emoji-user_id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_unicode_original_mine_existing_different_emoji-id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_unicode_original_mine_existing_different_emoji-None]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_zulip_original_mine_existing_different_emoji-user_id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_zulip_original_mine_existing_different_emoji-id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_zulip_original_mine_existing_different_emoji-None]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_unicode_original_others_existing_same_emoji-user_id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_unicode_original_others_existing_same_emoji-id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_unicode_original_others_existing_same_emoji-None]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_unicode_alias_others_existing_same_emoji-user_id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_unicode_alias_others_existing_same_emoji-id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[add_unicode_alias_others_existing_same_emoji-None]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[remove_unicode_original_mine_existing_same_emoji-user_id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[remove_unicode_original_mine_existing_same_emoji-id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[remove_unicode_original_mine_existing_same_emoji-None]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[remove_unicode_alias_mine_existing_same_emoji-user_id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[remove_unicode_alias_mine_existing_same_emoji-id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[remove_unicode_alias_mine_existing_same_emoji-None]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[remove_zulip_original_mine_existing_same_emoji-user_id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[remove_zulip_original_mine_existing_same_emoji-id]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_valid_emoji[remove_zulip_original_mine_existing_same_emoji-None]",
"tests/model/test_model.py::TestModel::test_toggle_message_reaction_with_invalid_emoji",
"tests/model/test_model.py::TestModel::test_has_user_reacted_to_message[id_inside_user_field__user_not_reacted]",
"tests/model/test_model.py::TestModel::test_has_user_reacted_to_message[user_id_inside_user_field__user_has_reacted]",
"tests/model/test_model.py::TestModel::test_has_user_reacted_to_message[no_user_field_with_user_id__user_has_reacted]",
"tests/model/test_model.py::TestModel::test_has_user_reacted_to_message[no_user_field_with_user_id__user_not_reacted]",
"tests/model/test_model.py::TestModel::test_send_typing_status_by_user_ids[start-recipient_user_ids0]",
"tests/model/test_model.py::TestModel::test_send_typing_status_by_user_ids[start-recipient_user_ids1]",
"tests/model/test_model.py::TestModel::test_send_typing_status_by_user_ids[stop-recipient_user_ids0]",
"tests/model/test_model.py::TestModel::test_send_typing_status_by_user_ids[stop-recipient_user_ids1]",
"tests/model/test_model.py::TestModel::test_send_typing_status_with_no_recipients[start]",
"tests/model/test_model.py::TestModel::test_send_typing_status_with_no_recipients[stop]",
"tests/model/test_model.py::TestModel::test_send_typing_status_avoided_due_to_user_setting[start-recipient_user_ids0]",
"tests/model/test_model.py::TestModel::test_send_typing_status_avoided_due_to_user_setting[start-recipient_user_ids1]",
"tests/model/test_model.py::TestModel::test_send_typing_status_avoided_due_to_user_setting[stop-recipient_user_ids0]",
"tests/model/test_model.py::TestModel::test_send_typing_status_avoided_due_to_user_setting[stop-recipient_user_ids1]",
"tests/model/test_model.py::TestModel::test_send_private_message[recipients0-response0-True]",
"tests/model/test_model.py::TestModel::test_send_private_message[recipients0-response1-False]",
"tests/model/test_model.py::TestModel::test_send_private_message[recipients1-response0-True]",
"tests/model/test_model.py::TestModel::test_send_private_message[recipients1-response1-False]",
"tests/model/test_model.py::TestModel::test_send_private_message_with_no_recipients",
"tests/model/test_model.py::TestModel::test_send_stream_message[response0-True]",
"tests/model/test_model.py::TestModel::test_send_stream_message[response1-False]",
"tests/model/test_model.py::TestModel::test_update_private_message[response0-True]",
"tests/model/test_model.py::TestModel::test_update_private_message[response1-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_passed_but_same_so_not_changed:content_changed-API_success]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_passed_but_same_so_not_changed:content_changed-API_error]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_changed[one]-API_success]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_changed[one]-API_error]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_passed_but_same_so_not_changed[all]-API_success]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_passed_but_same_so_not_changed[all]-API_error]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_passed_but_same_so_not_changed[later]:content_changed-API_success]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_passed_but_same_so_not_changed[later]:content_changed-API_error]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_changed[later]:content_changed-API_success]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_changed[later]:content_changed-API_error]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_changed[one]:content_changed-API_success]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_changed[one]:content_changed-API_error]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_changed[all]:content_changed-API_success]",
"tests/model/test_model.py::TestModel::test_update_stream_message[topic_changed[all]:content_changed-API_error]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args0-False-False-None-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args0-False-False-8-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args0-False-False-9-True]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args0-False-False-152-True]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args1-False-False-None-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args1-False-False-8-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args1-False-False-9-True]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args1-False-False-152-True]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args2-False-False-None-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args2-False-False-8-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args2-False-False-9-True]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args2-False-False-152-True]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args3-True-False-None-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args3-True-False-8-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args3-True-False-9-True]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args3-True-False-152-True]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args4-False-True-None-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args4-False-True-8-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args4-False-True-9-True]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args4-False-True-152-True]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args5-True-True-None-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args5-True-True-8-False]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args5-True-True-9-True]",
"tests/model/test_model.py::TestModel::test_update_stream_message__notify_thread_vs_ZFL[notify_args5-True-True-152-True]",
"tests/model/test_model.py::TestModel::test_get_latest_message_in_topic[response0-return_value0]",
"tests/model/test_model.py::TestModel::test_get_latest_message_in_topic[response1-None]",
"tests/model/test_model.py::TestModel::test_get_latest_message_in_topic[response2-None]",
"tests/model/test_model.py::TestModel::test_get_latest_message_in_topic[response3-None]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_msg_disabled:PreZulip4.0-None-_]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_msg_disabled:PreZulip4.0-user_role1-_owner]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_msg_disabled:PreZulip4.0-user_role2-_admin]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_msg_disabled:PreZulip4.0-user_role3-_moderator]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_msg_disabled:PreZulip4.0-user_role4-_member]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_msg_disabled:PreZulip4.0-user_role5-_guest]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_topic_disabled:PreZulip4.0-None-_]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_topic_disabled:PreZulip4.0-user_role1-_owner]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_topic_disabled:PreZulip4.0-user_role2-_admin]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_topic_disabled:PreZulip4.0-user_role3-_moderator]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_topic_disabled:PreZulip4.0-user_role4-_member]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_topic_disabled:PreZulip4.0-user_role5-_guest]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_topic_and_msg_enabled:PreZulip4.0-None-_]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_topic_and_msg_enabled:PreZulip4.0-user_role1-_owner]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_topic_and_msg_enabled:PreZulip4.0-user_role2-_admin]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_topic_and_msg_enabled:PreZulip4.0-user_role3-_moderator]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_topic_and_msg_enabled:PreZulip4.0-user_role4-_member]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[editing_topic_and_msg_enabled:PreZulip4.0-user_role5-_guest]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[all_but_no_editing:Zulip4.0+:ZFL75-None-_]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[all_but_no_editing:Zulip4.0+:ZFL75-user_role1-_owner]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[all_but_no_editing:Zulip4.0+:ZFL75-user_role2-_admin]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[all_but_no_editing:Zulip4.0+:ZFL75-user_role3-_moderator]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[all_but_no_editing:Zulip4.0+:ZFL75-user_role4-_member]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[all_but_no_editing:Zulip4.0+:ZFL75-user_role5-_guest]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[members:Zulip4.0+:ZFL75-None-_]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[members:Zulip4.0+:ZFL75-user_role1-_owner]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[members:Zulip4.0+:ZFL75-user_role2-_admin]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[members:Zulip4.0+:ZFL75-user_role3-_moderator]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[members:Zulip4.0+:ZFL75-user_role4-_member]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[members:Zulip4.0+:ZFL75-user_role5-_guest]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[admins:Zulip4.0+:ZFL75-None-_]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[admins:Zulip4.0+:ZFL75-user_role1-_owner]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[admins:Zulip4.0+:ZFL75-user_role2-_admin]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[admins:Zulip4.0+:ZFL75-user_role3-_moderator]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[admins:Zulip4.0+:ZFL75-user_role4-_member]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[admins:Zulip4.0+:ZFL75-user_role5-_guest]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[full_members:Zulip4.0+:ZFL75-None-_]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[full_members:Zulip4.0+:ZFL75-user_role1-_owner]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[full_members:Zulip4.0+:ZFL75-user_role2-_admin]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[full_members:Zulip4.0+:ZFL75-user_role3-_moderator]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[full_members:Zulip4.0+:ZFL75-user_role4-_member]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[full_members:Zulip4.0+:ZFL75-user_role5-_guest]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[moderators:Zulip4.0+:ZFL75-None-_]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[moderators:Zulip4.0+:ZFL75-user_role1-_owner]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[moderators:Zulip4.0+:ZFL75-user_role2-_admin]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[moderators:Zulip4.0+:ZFL75-user_role3-_moderator]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[moderators:Zulip4.0+:ZFL75-user_role4-_member]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[moderators:Zulip4.0+:ZFL75-user_role5-_guest]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[guests:Zulip4.0+:ZFL75-None-_]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[guests:Zulip4.0+:ZFL75-user_role1-_owner]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[guests:Zulip4.0+:ZFL75-user_role2-_admin]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[guests:Zulip4.0+:ZFL75-user_role3-_moderator]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[guests:Zulip4.0+:ZFL75-user_role4-_member]",
"tests/model/test_model.py::TestModel::test_can_user_edit_topic[guests:Zulip4.0+:ZFL75-user_role5-_guest]",
"tests/model/test_model.py::TestModel::test_success_get_messages",
"tests/model/test_model.py::TestModel::test_modernize_message_response[Zulip_4.0+_ZFL46_response_with_topic_links]",
"tests/model/test_model.py::TestModel::test_modernize_message_response[Zulip_3.0+_ZFL1_response_with_topic_links]",
"tests/model/test_model.py::TestModel::test_modernize_message_response[Zulip_3.0+_ZFL1_response_empty_topic_links]",
"tests/model/test_model.py::TestModel::test_modernize_message_response[Zulip_2.1+_response_with_subject_links]",
"tests/model/test_model.py::TestModel::test_modernize_message_response[Zulip_2.1+_response_empty_subject_links]",
"tests/model/test_model.py::TestModel::test__store_content_length_restrictions[Zulip_2.1.x_ZFL_None_no_restrictions]",
"tests/model/test_model.py::TestModel::test__store_content_length_restrictions[Zulip_3.1.x_ZFL_27_no_restrictions]",
"tests/model/test_model.py::TestModel::test__store_content_length_restrictions[Zulip_4.0.x_ZFL_52_no_restrictions]",
"tests/model/test_model.py::TestModel::test__store_content_length_restrictions[Zulip_4.0.x_ZFL_53_with_restrictions]",
"tests/model/test_model.py::TestModel::test_get_message_false_first_anchor",
"tests/model/test_model.py::TestModel::test_fail_get_messages",
"tests/model/test_model.py::TestModel::test_fetch_raw_message_content[response0-Feels",
"tests/model/test_model.py::TestModel::test_fetch_raw_message_content[response1-None-True]",
"tests/model/test_model.py::TestModel::test_toggle_stream_muted_status[muting_205]",
"tests/model/test_model.py::TestModel::test_toggle_stream_muted_status[unmuting_205]",
"tests/model/test_model.py::TestModel::test_toggle_stream_muted_status[first_muted_205]",
"tests/model/test_model.py::TestModel::test_toggle_stream_muted_status[last_unmuted_205]",
"tests/model/test_model.py::TestModel::test_stream_access_type",
"tests/model/test_model.py::TestModel::test_toggle_message_star_status[flags_before0-add]",
"tests/model/test_model.py::TestModel::test_toggle_message_star_status[flags_before1-remove]",
"tests/model/test_model.py::TestModel::test_toggle_message_star_status[flags_before2-add]",
"tests/model/test_model.py::TestModel::test_toggle_message_star_status[flags_before3-remove]",
"tests/model/test_model.py::TestModel::test_toggle_message_star_status[flags_before4-remove]",
"tests/model/test_model.py::TestModel::test_mark_message_ids_as_read",
"tests/model/test_model.py::TestModel::test_mark_message_ids_as_read_empty_message_view",
"tests/model/test_model.py::TestModel::test__update_initial_data",
"tests/model/test_model.py::TestModel::test__group_info_from_realm_user_groups",
"tests/model/test_model.py::TestModel::test__clean_and_order_custom_profile_data",
"tests/model/test_model.py::TestModel::test_get_user_info[user_full_name]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_empty_full_name]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_email]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_empty_email]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_date_joined]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_empty_date_joined]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_timezone]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_empty_timezone]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_bot_type]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_empty_bot_type]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_is_owner:Zulip_4.0+_ZFL59]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_is_admin:Zulip_4.0+_ZFL59]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_is_moderator:Zulip_4.0+_ZFL60]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_is_guest:Zulip_4.0+_ZFL59]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_is_member]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_is_owner:Zulip_3.0+]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_is_admin:preZulip_4.0]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_is_guest:preZulip_4.0]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_is_bot]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_bot_has_owner:Zulip_3.0+_ZFL1]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_bot_has_owner:preZulip_3.0]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_bot_has_no_owner]",
"tests/model/test_model.py::TestModel::test_get_user_info[user_has_custom_profile_data]",
"tests/model/test_model.py::TestModel::test_get_user_info_USER_NOT_FOUND",
"tests/model/test_model.py::TestModel::test_get_user_info_sample_response",
"tests/model/test_model.py::TestModel::test__update_users_data_from_initial_data",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled0-muted0]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled0-muted1]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled0-muted2]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled0-muted3]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled1-muted0]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled1-muted1]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled1-muted2]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled1-muted3]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled2-muted0]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled2-muted1]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled2-muted2]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled2-muted3]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled3-muted0]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled3-muted1]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled3-muted2]",
"tests/model/test_model.py::TestModel::test__subscribe_to_streams[visual_notification_enabled3-muted3]",
"tests/model/test_model.py::TestModel::test__handle_message_event_with_Falsey_log[stream_message]",
"tests/model/test_model.py::TestModel::test__handle_message_event_with_Falsey_log[pm_message]",
"tests/model/test_model.py::TestModel::test__handle_message_event_with_Falsey_log[group_pm_message]",
"tests/model/test_model.py::TestModel::test__handle_message_event_with_valid_log[stream_message]",
"tests/model/test_model.py::TestModel::test__handle_message_event_with_valid_log[pm_message]",
"tests/model/test_model.py::TestModel::test__handle_message_event_with_valid_log[group_pm_message]",
"tests/model/test_model.py::TestModel::test__handle_message_event_with_flags[stream_message]",
"tests/model/test_model.py::TestModel::test__handle_message_event_with_flags[pm_message]",
"tests/model/test_model.py::TestModel::test__handle_message_event_with_flags[group_pm_message]",
"tests/model/test_model.py::TestModel::test__handle_message_event[stream_to_all_messages]",
"tests/model/test_model.py::TestModel::test__handle_message_event[private_to_all_private]",
"tests/model/test_model.py::TestModel::test__handle_message_event[stream_to_stream]",
"tests/model/test_model.py::TestModel::test__handle_message_event[stream_to_topic]",
"tests/model/test_model.py::TestModel::test__handle_message_event[stream_to_different_stream_same_topic]",
"tests/model/test_model.py::TestModel::test__handle_message_event[user_pm_x_appears_in_narrow_with_x]",
"tests/model/test_model.py::TestModel::test__handle_message_event[search]",
"tests/model/test_model.py::TestModel::test__handle_message_event[user_pm_x_does_not_appear_in_narrow_without_x]",
"tests/model/test_model.py::TestModel::test__handle_message_event[mentioned_msg_in_mentioned_msg_narrow]",
"tests/model/test_model.py::TestModel::test__update_topic_index[reorder_topic3]",
"tests/model/test_model.py::TestModel::test__update_topic_index[topic1_discussion_continues]",
"tests/model/test_model.py::TestModel::test__update_topic_index[new_topic4]",
"tests/model/test_model.py::TestModel::test__update_topic_index[first_topic_1]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[stream_message-not_notified_since_self_message]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[stream_message-notified_stream_and_private_since_directly_mentioned]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[stream_message-notified_stream_and_private_since_wildcard_mentioned]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[stream_message-notified_stream_since_stream_has_desktop_notifications]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[stream_message-notified_private_since_private_message]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[pm_message-not_notified_since_self_message]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[pm_message-notified_stream_and_private_since_directly_mentioned]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[pm_message-notified_stream_and_private_since_wildcard_mentioned]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[pm_message-notified_stream_since_stream_has_desktop_notifications]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[pm_message-notified_private_since_private_message]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[group_pm_message-not_notified_since_self_message]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[group_pm_message-notified_stream_and_private_since_directly_mentioned]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[group_pm_message-notified_stream_and_private_since_wildcard_mentioned]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[group_pm_message-notified_stream_since_stream_has_desktop_notifications]",
"tests/model/test_model.py::TestModel::test_notify_users_calling_msg_type[group_pm_message-notified_private_since_private_message]",
"tests/model/test_model.py::TestModel::test_notify_user_transformed_content[stream_message-simple_text]",
"tests/model/test_model.py::TestModel::test_notify_user_transformed_content[stream_message-spoiler_with_title]",
"tests/model/test_model.py::TestModel::test_notify_user_transformed_content[stream_message-spoiler_no_title]",
"tests/model/test_model.py::TestModel::test_notify_user_transformed_content[pm_message-simple_text]",
"tests/model/test_model.py::TestModel::test_notify_user_transformed_content[pm_message-spoiler_with_title]",
"tests/model/test_model.py::TestModel::test_notify_user_transformed_content[pm_message-spoiler_no_title]",
"tests/model/test_model.py::TestModel::test_notify_user_transformed_content[group_pm_message-simple_text]",
"tests/model/test_model.py::TestModel::test_notify_user_transformed_content[group_pm_message-spoiler_with_title]",
"tests/model/test_model.py::TestModel::test_notify_user_transformed_content[group_pm_message-spoiler_no_title]",
"tests/model/test_model.py::TestModel::test_notify_users_enabled[stream_message-True-True]",
"tests/model/test_model.py::TestModel::test_notify_users_enabled[stream_message-False-False]",
"tests/model/test_model.py::TestModel::test_notify_users_enabled[pm_message-True-True]",
"tests/model/test_model.py::TestModel::test_notify_users_enabled[pm_message-False-False]",
"tests/model/test_model.py::TestModel::test_notify_users_enabled[group_pm_message-True-True]",
"tests/model/test_model.py::TestModel::test_notify_users_enabled[group_pm_message-False-False]",
"tests/model/test_model.py::TestModel::test_notify_users_hides_PM_content_based_on_user_setting[pm_template-True-New",
"tests/model/test_model.py::TestModel::test_notify_users_hides_PM_content_based_on_user_setting[pm_template-False-private",
"tests/model/test_model.py::TestModel::test_notify_users_hides_PM_content_based_on_user_setting[group_pm_template-True-New",
"tests/model/test_model.py::TestModel::test_notify_users_hides_PM_content_based_on_user_setting[group_pm_template-False-private",
"tests/model/test_model.py::TestModel::test__handle_update_message_event[Only",
"tests/model/test_model.py::TestModel::test__handle_update_message_event[Subject",
"tests/model/test_model.py::TestModel::test__handle_update_message_event[Message",
"tests/model/test_model.py::TestModel::test__handle_update_message_event[Both",
"tests/model/test_model.py::TestModel::test__handle_update_message_event[Some",
"tests/model/test_model.py::TestModel::test__handle_update_message_event[message_id",
"tests/model/test_model.py::TestModel::test__update_rendered_view[msgbox_updated_in_topic_narrow]",
"tests/model/test_model.py::TestModel::test__update_rendered_view[msgbox_removed_due_to_topic_narrow_mismatch]",
"tests/model/test_model.py::TestModel::test__update_rendered_view[msgbox_updated_in_all_messages_narrow]",
"tests/model/test_model.py::TestModel::test__update_rendered_view_change_narrow[same_topic_narrow]",
"tests/model/test_model.py::TestModel::test__update_rendered_view_change_narrow[previous_topic_narrow_empty_so_change_narrow]",
"tests/model/test_model.py::TestModel::test__update_rendered_view_change_narrow[same_all_messages_narrow]",
"tests/model/test_model.py::TestModel::test__handle_reaction_event_not_in_index[add]",
"tests/model/test_model.py::TestModel::test__handle_reaction_event_not_in_index[remove]",
"tests/model/test_model.py::TestModel::test__handle_reaction_event_for_msg_in_index[add-2]",
"tests/model/test_model.py::TestModel::test__handle_reaction_event_for_msg_in_index[remove-1]",
"tests/model/test_model.py::TestModel::test_update_star_status_no_index[update_message_flags_operation0]",
"tests/model/test_model.py::TestModel::test_update_star_status_no_index[update_message_flags_operation1]",
"tests/model/test_model.py::TestModel::test_update_star_status_no_index[update_message_flags_operation2]",
"tests/model/test_model.py::TestModel::test_update_star_status_invalid_operation[update_message_flags_operation0]",
"tests/model/test_model.py::TestModel::test_update_star_status_invalid_operation[update_message_flags_operation1]",
"tests/model/test_model.py::TestModel::test_update_star_status_invalid_operation[update_message_flags_operation2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before0-flags_after0-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before0-flags_after0-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before0-flags_after0-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before0-flags_after0-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before0-flags_after0-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before0-flags_after0-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before1-flags_after1-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before1-flags_after1-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before1-flags_after1-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before1-flags_after1-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before1-flags_after1-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before1-flags_after1-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before2-flags_after2-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before2-flags_after2-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before2-flags_after2-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before2-flags_after2-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before2-flags_after2-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before2-flags_after2-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before3-flags_after3-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before3-flags_after3-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before3-flags_after3-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before3-flags_after3-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before3-flags_after3-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-add-1-flags_before3-flags_after3-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before4-flags_after4-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before4-flags_after4-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before4-flags_after4-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before4-flags_after4-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before4-flags_after4-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before4-flags_after4-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before5-flags_after5-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before5-flags_after5-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before5-flags_after5-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before5-flags_after5-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before5-flags_after5-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before5-flags_after5-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before6-flags_after6-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before6-flags_after6-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before6-flags_after6-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before6-flags_after6-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before6-flags_after6-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before6-flags_after6-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before7-flags_after7-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before7-flags_after7-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before7-flags_after7-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before7-flags_after7-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before7-flags_after7-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before7-flags_after7-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before8-flags_after8-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before8-flags_after8-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before8-flags_after8-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before8-flags_after8-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before8-flags_after8-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation0-remove--1-flags_before8-flags_after8-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before0-flags_after0-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before0-flags_after0-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before0-flags_after0-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before0-flags_after0-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before0-flags_after0-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before0-flags_after0-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before1-flags_after1-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before1-flags_after1-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before1-flags_after1-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before1-flags_after1-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before1-flags_after1-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before1-flags_after1-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before2-flags_after2-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before2-flags_after2-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before2-flags_after2-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before2-flags_after2-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before2-flags_after2-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before2-flags_after2-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before3-flags_after3-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before3-flags_after3-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before3-flags_after3-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before3-flags_after3-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before3-flags_after3-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-add-1-flags_before3-flags_after3-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before4-flags_after4-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before4-flags_after4-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before4-flags_after4-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before4-flags_after4-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before4-flags_after4-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before4-flags_after4-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before5-flags_after5-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before5-flags_after5-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before5-flags_after5-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before5-flags_after5-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before5-flags_after5-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before5-flags_after5-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before6-flags_after6-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before6-flags_after6-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before6-flags_after6-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before6-flags_after6-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before6-flags_after6-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before6-flags_after6-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before7-flags_after7-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before7-flags_after7-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before7-flags_after7-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before7-flags_after7-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before7-flags_after7-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before7-flags_after7-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before8-flags_after8-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before8-flags_after8-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before8-flags_after8-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before8-flags_after8-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before8-flags_after8-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation1-remove--1-flags_before8-flags_after8-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before0-flags_after0-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before0-flags_after0-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before0-flags_after0-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before0-flags_after0-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before0-flags_after0-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before0-flags_after0-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before1-flags_after1-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before1-flags_after1-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before1-flags_after1-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before1-flags_after1-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before1-flags_after1-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before1-flags_after1-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before2-flags_after2-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before2-flags_after2-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before2-flags_after2-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before2-flags_after2-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before2-flags_after2-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before2-flags_after2-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before3-flags_after3-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before3-flags_after3-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before3-flags_after3-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before3-flags_after3-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before3-flags_after3-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-add-1-flags_before3-flags_after3-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before4-flags_after4-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before4-flags_after4-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before4-flags_after4-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before4-flags_after4-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before4-flags_after4-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before4-flags_after4-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before5-flags_after5-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before5-flags_after5-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before5-flags_after5-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before5-flags_after5-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before5-flags_after5-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before5-flags_after5-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before6-flags_after6-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before6-flags_after6-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before6-flags_after6-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before6-flags_after6-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before6-flags_after6-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before6-flags_after6-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before7-flags_after7-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before7-flags_after7-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before7-flags_after7-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before7-flags_after7-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before7-flags_after7-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before7-flags_after7-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before8-flags_after8-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before8-flags_after8-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before8-flags_after8-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before8-flags_after8-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before8-flags_after8-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_star_status[update_message_flags_operation2-remove--1-flags_before8-flags_after8-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before0-flags_after0-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before0-flags_after0-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before0-flags_after0-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before0-flags_after0-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before0-flags_after0-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before0-flags_after0-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before1-flags_after1-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before1-flags_after1-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before1-flags_after1-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before1-flags_after1-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before1-flags_after1-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before1-flags_after1-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before2-flags_after2-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before2-flags_after2-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before2-flags_after2-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before2-flags_after2-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before2-flags_after2-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before2-flags_after2-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before3-flags_after3-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before3-flags_after3-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before3-flags_after3-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before3-flags_after3-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before3-flags_after3-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-add-flags_before3-flags_after3-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before4-flags_after4-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before4-flags_after4-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before4-flags_after4-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before4-flags_after4-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before4-flags_after4-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before4-flags_after4-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before5-flags_after5-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before5-flags_after5-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before5-flags_after5-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before5-flags_after5-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before5-flags_after5-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before5-flags_after5-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before6-flags_after6-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before6-flags_after6-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before6-flags_after6-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before6-flags_after6-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before6-flags_after6-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before6-flags_after6-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before7-flags_after7-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before7-flags_after7-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before7-flags_after7-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before7-flags_after7-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before7-flags_after7-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before7-flags_after7-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before8-flags_after8-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before8-flags_after8-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before8-flags_after8-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before8-flags_after8-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before8-flags_after8-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation0-remove-flags_before8-flags_after8-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before0-flags_after0-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before0-flags_after0-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before0-flags_after0-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before0-flags_after0-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before0-flags_after0-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before0-flags_after0-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before1-flags_after1-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before1-flags_after1-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before1-flags_after1-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before1-flags_after1-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before1-flags_after1-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before1-flags_after1-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before2-flags_after2-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before2-flags_after2-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before2-flags_after2-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before2-flags_after2-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before2-flags_after2-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before2-flags_after2-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before3-flags_after3-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before3-flags_after3-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before3-flags_after3-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before3-flags_after3-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before3-flags_after3-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-add-flags_before3-flags_after3-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before4-flags_after4-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before4-flags_after4-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before4-flags_after4-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before4-flags_after4-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before4-flags_after4-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before4-flags_after4-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before5-flags_after5-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before5-flags_after5-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before5-flags_after5-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before5-flags_after5-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before5-flags_after5-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before5-flags_after5-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before6-flags_after6-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before6-flags_after6-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before6-flags_after6-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before6-flags_after6-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before6-flags_after6-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before6-flags_after6-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before7-flags_after7-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before7-flags_after7-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before7-flags_after7-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before7-flags_after7-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before7-flags_after7-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before7-flags_after7-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before8-flags_after8-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before8-flags_after8-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before8-flags_after8-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before8-flags_after8-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before8-flags_after8-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation1-remove-flags_before8-flags_after8-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before0-flags_after0-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before0-flags_after0-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before0-flags_after0-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before0-flags_after0-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before0-flags_after0-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before0-flags_after0-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before1-flags_after1-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before1-flags_after1-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before1-flags_after1-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before1-flags_after1-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before1-flags_after1-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before1-flags_after1-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before2-flags_after2-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before2-flags_after2-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before2-flags_after2-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before2-flags_after2-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before2-flags_after2-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before2-flags_after2-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before3-flags_after3-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before3-flags_after3-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before3-flags_after3-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before3-flags_after3-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before3-flags_after3-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-add-flags_before3-flags_after3-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before4-flags_after4-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before4-flags_after4-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before4-flags_after4-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before4-flags_after4-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before4-flags_after4-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before4-flags_after4-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before5-flags_after5-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before5-flags_after5-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before5-flags_after5-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before5-flags_after5-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before5-flags_after5-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before5-flags_after5-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before6-flags_after6-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before6-flags_after6-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before6-flags_after6-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before6-flags_after6-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before6-flags_after6-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before6-flags_after6-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before7-flags_after7-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before7-flags_after7-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before7-flags_after7-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before7-flags_after7-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before7-flags_after7-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before7-flags_after7-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before8-flags_after8-event_message_ids0-indexed_ids0]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before8-flags_after8-event_message_ids1-indexed_ids1]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before8-flags_after8-event_message_ids2-indexed_ids2]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before8-flags_after8-event_message_ids3-indexed_ids3]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before8-flags_after8-event_message_ids4-indexed_ids4]",
"tests/model/test_model.py::TestModel::test_update_read_status[update_message_flags_operation2-remove-flags_before8-flags_after8-event_message_ids5-indexed_ids5]",
"tests/model/test_model.py::TestModel::test_toggle_stream_pinned_status[pinning]",
"tests/model/test_model.py::TestModel::test_toggle_stream_pinned_status[unpinning]",
"tests/model/test_model.py::TestModel::test_toggle_stream_pinned_status[first_pinned]",
"tests/model/test_model.py::TestModel::test_toggle_stream_pinned_status[last_unpinned]",
"tests/model/test_model.py::TestModel::test_toggle_stream_visual_notifications[visual_notification_enable_205]",
"tests/model/test_model.py::TestModel::test_toggle_stream_visual_notifications[visual_notification_disable_205]",
"tests/model/test_model.py::TestModel::test_toggle_stream_visual_notifications[first_notification_enable_205]",
"tests/model/test_model.py::TestModel::test_toggle_stream_visual_notifications[last_notification_disable_205]",
"tests/model/test_model.py::TestModel::test__handle_typing_event[not_in_pm_narrow]",
"tests/model/test_model.py::TestModel::test__handle_typing_event[not_in_pm_narrow_with_sender]",
"tests/model/test_model.py::TestModel::test__handle_typing_event[in_pm_narrow_with_sender_typing:start]",
"tests/model/test_model.py::TestModel::test__handle_typing_event[in_pm_narrow_with_sender_typing:start_while_animation_in_progress]",
"tests/model/test_model.py::TestModel::test__handle_typing_event[in_pm_narrow_with_sender_typing:stop]",
"tests/model/test_model.py::TestModel::test__handle_typing_event[in_pm_narrow_with_other_myself_typing:start]",
"tests/model/test_model.py::TestModel::test__handle_typing_event[in_pm_narrow_with_other_myself_typing:stop]",
"tests/model/test_model.py::TestModel::test__handle_typing_event[in_pm_narrow_with_oneself:start]",
"tests/model/test_model.py::TestModel::test__handle_typing_event[in_pm_narrow_with_oneself:stop]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_mute_streams[remove_18_in_home_view:already_unmuted:ZFLNone]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_mute_streams[remove_19_in_home_view:muted:ZFLNone]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_mute_streams[add_19_in_home_view:already_muted:ZFLNone]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_mute_streams[add_30_in_home_view:unmuted:ZFLNone]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_mute_streams[remove_30_is_muted:already_unmutedZFL139]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_mute_streams[remove_19_is_muted:muted:ZFL139]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_mute_streams[add_15_is_muted:already_muted:ZFL139]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_mute_streams[add_30_is_muted:unmuted:ZFL139]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_pin_streams[pin_stream]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_pin_streams[unpin_stream]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_visual_notifications[remove_visual_notified_stream_15:present]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_visual_notifications[add_visual_notified_stream_19:not_present]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_visual_notifications[remove_visual_notified_stream_15:not_present]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_visual_notifications[add_visual_notified_stream_19:present]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers[user_subscribed_to_stream:ZFLNone]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers[user_subscribed_to_stream:ZFL34]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers[user_subscribed_to_stream:ZFL34_should_be_35]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers[user_subscribed_to_stream:ZFL35]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers[user_unsubscribed_from_stream:ZFLNone]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers[user_unsubscribed_from_stream:ZFL34]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers[user_unsubscribed_from_stream:ZFL34_should_be_35]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers[user_unsubscribed_from_stream:ZFL35]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers_to_unsubscribed_streams[peer_subscribed_to_stream_that_user_is_unsubscribed_to]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers_to_unsubscribed_streams[peer_subscribed_to_stream_that_user_is_unsubscribed_to:ZFL35+]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers_to_unsubscribed_streams[peer_unsubscribed_from_stream_that_user_is_unsubscribed_to]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers_to_unsubscribed_streams[peer_unsubscribed_from_stream_that_user_is_unsubscribed_to:ZFL35+]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers_multiple_users_one_stream[users_subscribed_to_stream:ZFL34_should_be_35]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers_multiple_users_one_stream[users_subscribed_to_stream:ZFL35]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers_multiple_users_one_stream[users_unsubscribed_from_stream:ZFL34_should_be_35]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers_multiple_users_one_stream[users_unsubscribed_from_stream:ZFL35]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers_one_user_multiple_streams[user_subscribed_to_streams:ZFL34_should_be_35]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers_one_user_multiple_streams[user_subscribed_to_streams:ZFL35]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers_one_user_multiple_streams[user_unsubscribed_from_streams:ZFL34_should_be_35]",
"tests/model/test_model.py::TestModel::test__handle_subscription_event_subscribers_one_user_multiple_streams[user_unsubscribed_from_streams:ZFL35]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__general[full_name]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__general[timezone]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__general[billing_admin_role]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__general[role]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__general[avatar]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__general[display_email]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__general[delivery_email]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__custom_profile_data__update_data[Short",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__custom_profile_data__update_data[Long",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__custom_profile_data__update_data[List",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__custom_profile_data__update_data[Date",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__custom_profile_data__update_data[Link-no_custom]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__custom_profile_data__update_data[Link-many_custom]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__custom_profile_data__update_data[Person",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__custom_profile_data__update_data[External",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__custom_profile_data__update_data[Pronouns-no_custom]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__custom_profile_data__update_data[Pronouns-many_custom]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__custom_profile_data__remove_data[update_data0-8-no_custom]",
"tests/model/test_model.py::TestModel::test__handle_realm_user_event__custom_profile_data__remove_data[update_data0-8-many_custom]",
"tests/model/test_model.py::TestModel::test__handle_user_settings_event[True]",
"tests/model/test_model.py::TestModel::test__handle_user_settings_event[False]",
"tests/model/test_model.py::TestModel::test_update_pm_content_in_desktop_notifications[True]",
"tests/model/test_model.py::TestModel::test_update_pm_content_in_desktop_notifications[False]",
"tests/model/test_model.py::TestModel::test_update_twenty_four_hour_format[True]",
"tests/model/test_model.py::TestModel::test_update_twenty_four_hour_format[False]",
"tests/model/test_model.py::TestModel::test_is_muted_stream[muted_stream]",
"tests/model/test_model.py::TestModel::test_is_muted_stream[unmuted_stream]",
"tests/model/test_model.py::TestModel::test_is_muted_stream[unmuted_stream_nostreamsmuted]",
"tests/model/test_model.py::TestModel::test_is_visual_notifications_enabled[notifications_enabled]",
"tests/model/test_model.py::TestModel::test_is_visual_notifications_enabled[notifications_disabled]",
"tests/model/test_model.py::TestModel::test_is_visual_notifications_enabled[notifications_disabled_no_streams_to_notify]",
"tests/model/test_model.py::TestModel::test_is_muted_topic[zulip_feature_level:None-topic0-False]",
"tests/model/test_model.py::TestModel::test_is_muted_topic[zulip_feature_level:None-topic1-True]",
"tests/model/test_model.py::TestModel::test_is_muted_topic[zulip_feature_level:None-topic2-True]",
"tests/model/test_model.py::TestModel::test_is_muted_topic[zulip_feature_level:None-topic3-False]",
"tests/model/test_model.py::TestModel::test_is_muted_topic[zulip_feature_level:1-topic0-False]",
"tests/model/test_model.py::TestModel::test_is_muted_topic[zulip_feature_level:1-topic1-True]",
"tests/model/test_model.py::TestModel::test_is_muted_topic[zulip_feature_level:1-topic2-True]",
"tests/model/test_model.py::TestModel::test_is_muted_topic[zulip_feature_level:1-topic3-False]",
"tests/model/test_model.py::TestModel::test_get_next_unread_pm",
"tests/model/test_model.py::TestModel::test_get_next_unread_pm_again",
"tests/model/test_model.py::TestModel::test_get_next_unread_pm_no_unread",
"tests/model/test_model.py::TestModel::test_is_user_subscribed_to_stream[subscribed_stream]",
"tests/model/test_model.py::TestModel::test_is_user_subscribed_to_stream[unsubscribed_stream]",
"tests/model/test_model.py::TestModel::test_fetch_message_history_success[unedited_message-response0]",
"tests/model/test_model.py::TestModel::test_fetch_message_history_success[edited_message-response0]",
"tests/model/test_model.py::TestModel::test_fetch_message_history_error[response0]",
"tests/model/test_model.py::TestModel::test_user_name_from_id_valid[1001-Human",
"tests/model/test_model.py::TestModel::test_user_name_from_id_invalid[-1]",
"tests/model/test_model.py::TestModel::test_generate_all_emoji_data",
"tests/model/test_model.py::TestModel::test__handle_update_emoji_event[realm_emoji_with_same_name_as_unicode_emoji_added]",
"tests/model/test_model.py::TestModel::test__handle_update_emoji_event[realm_emoji_with_same_name_as_unicode_emoji_removed]",
"tests/model/test_model.py::TestModel::test__handle_update_emoji_event[realm_emoji_with_name_as_zulip_added]",
"tests/model/test_model.py::TestModel::test__handle_update_emoji_event[realm_emoji_with_name_as_zulip_removed]",
"tests/model/test_model.py::TestModel::test__handle_update_emoji_event[realm_emoji_added]",
"tests/model/test_model.py::TestModel::test__handle_update_emoji_event[realm_emoji_removed]",
"tests/model/test_model.py::TestModel::test_poll_for_events__no_disconnect",
"tests/model/test_model.py::TestModel::test_poll_for_events__reconnect_ok[reconnect_on_1st_attempt]",
"tests/model/test_model.py::TestModel::test_poll_for_events__reconnect_ok[reconnect_on_2nd_attempt]",
"tests/model/test_model.py::TestModel::test_poll_for_events__reconnect_ok[reconnect_on_3rd_attempt]",
"tests/ui/test_ui_tools.py::TestModListWalker::test_extend[5-0]",
"tests/ui/test_ui_tools.py::TestModListWalker::test_extend[0-0]",
"tests/ui/test_ui_tools.py::TestModListWalker::test__set_focus",
"tests/ui/test_ui_tools.py::TestModListWalker::test_set_focus",
"tests/ui/test_ui_tools.py::TestMessageView::test_init",
"tests/ui/test_ui_tools.py::TestMessageView::test_main_view[None-1]",
"tests/ui/test_ui_tools.py::TestMessageView::test_main_view[0-0]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_empty_log[ids_in_narrow0-messages_fetched0]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_empty_log[ids_in_narrow0-messages_fetched1]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_empty_log[ids_in_narrow0-messages_fetched2]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_empty_log[ids_in_narrow1-messages_fetched0]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_empty_log[ids_in_narrow1-messages_fetched1]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_empty_log[ids_in_narrow1-messages_fetched2]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_mocked_log[99-other_ids_in_narrow0-messages_fetched0]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_mocked_log[99-other_ids_in_narrow0-messages_fetched1]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_mocked_log[99-other_ids_in_narrow0-messages_fetched2]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_mocked_log[99-other_ids_in_narrow1-messages_fetched0]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_mocked_log[99-other_ids_in_narrow1-messages_fetched1]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_mocked_log[99-other_ids_in_narrow1-messages_fetched2]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_mocked_log[99-other_ids_in_narrow2-messages_fetched0]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_mocked_log[99-other_ids_in_narrow2-messages_fetched1]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_old_messages_mocked_log[99-other_ids_in_narrow2-messages_fetched2]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_new_messages_empty_log[ids_in_narrow0]",
"tests/ui/test_ui_tools.py::TestMessageView::test_load_new_messages_mocked_log[ids_in_narrow0]",
"tests/ui/test_ui_tools.py::TestMessageView::test_mouse_event[mouse_scroll_up]",
"tests/ui/test_ui_tools.py::TestMessageView::test_mouse_event[mouse_scroll_down]",
"tests/ui/test_ui_tools.py::TestMessageView::test_keypress_GO_DOWN[down]",
"tests/ui/test_ui_tools.py::TestMessageView::test_keypress_GO_DOWN[j]",
"tests/ui/test_ui_tools.py::TestMessageView::test_keypress_GO_DOWN_exception[down-True]",
"tests/ui/test_ui_tools.py::TestMessageView::test_keypress_GO_DOWN_exception[down-False]",
"tests/ui/test_ui_tools.py::TestMessageView::test_keypress_GO_DOWN_exception[j-True]",
"tests/ui/test_ui_tools.py::TestMessageView::test_keypress_GO_DOWN_exception[j-False]",
"tests/ui/test_ui_tools.py::TestMessageView::test_keypress_GO_UP[up]",
"tests/ui/test_ui_tools.py::TestMessageView::test_keypress_GO_UP[k]",
"tests/ui/test_ui_tools.py::TestMessageView::test_keypress_GO_UP_exception[up-True]",
"tests/ui/test_ui_tools.py::TestMessageView::test_keypress_GO_UP_exception[up-False]",
"tests/ui/test_ui_tools.py::TestMessageView::test_keypress_GO_UP_exception[k-True]",
"tests/ui/test_ui_tools.py::TestMessageView::test_keypress_GO_UP_exception[k-False]",
"tests/ui/test_ui_tools.py::TestMessageView::test_read_message",
"tests/ui/test_ui_tools.py::TestMessageView::test_message_calls_search_and_header_bar",
"tests/ui/test_ui_tools.py::TestMessageView::test_read_message_no_msgw",
"tests/ui/test_ui_tools.py::TestMessageView::test_read_message_in_explore_mode",
"tests/ui/test_ui_tools.py::TestMessageView::test_read_message_search_narrow",
"tests/ui/test_ui_tools.py::TestMessageView::test_read_message_last_unread_message_focused[stream_message]",
"tests/ui/test_ui_tools.py::TestMessageView::test_read_message_last_unread_message_focused[pm_message]",
"tests/ui/test_ui_tools.py::TestMessageView::test_read_message_last_unread_message_focused[group_pm_message]",
"tests/ui/test_ui_tools.py::TestStreamsViewDivider::test_init",
"tests/ui/test_ui_tools.py::TestStreamsView::test_init",
"tests/ui/test_ui_tools.py::TestStreamsView::test_update_streams[f-expected_log0-to_pin0]",
"tests/ui/test_ui_tools.py::TestStreamsView::test_update_streams[bar-expected_log1-to_pin1]",
"tests/ui/test_ui_tools.py::TestStreamsView::test_update_streams[foo-expected_log2-to_pin2]",
"tests/ui/test_ui_tools.py::TestStreamsView::test_update_streams[FOO-expected_log3-to_pin3]",
"tests/ui/test_ui_tools.py::TestStreamsView::test_update_streams[test-expected_log4-to_pin4]",
"tests/ui/test_ui_tools.py::TestStreamsView::test_update_streams[here-expected_log5-to_pin5]",
"tests/ui/test_ui_tools.py::TestStreamsView::test_update_streams[test",
"tests/ui/test_ui_tools.py::TestStreamsView::test_update_streams[f-expected_log7-to_pin7]",
"tests/ui/test_ui_tools.py::TestStreamsView::test_update_streams[FOO-expected_log8-to_pin8]",
"tests/ui/test_ui_tools.py::TestStreamsView::test_update_streams[bar-expected_log9-to_pin9]",
"tests/ui/test_ui_tools.py::TestStreamsView::test_update_streams[baar-search",
"tests/ui/test_ui_tools.py::TestStreamsView::test_mouse_event[mouse_scroll_up]",
"tests/ui/test_ui_tools.py::TestStreamsView::test_mouse_event[mouse_scroll_down]",
"tests/ui/test_ui_tools.py::TestStreamsView::test_keypress_SEARCH_STREAMS[q]",
"tests/ui/test_ui_tools.py::TestStreamsView::test_keypress_GO_BACK[esc]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_init",
"tests/ui/test_ui_tools.py::TestTopicsView::test_update_topics[f-expected_log0]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_update_topics[a-expected_log1]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_update_topics[bar-expected_log2]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_update_topics[foo-expected_log3]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_update_topics[FOO-expected_log4]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_update_topics[(no-expected_log5]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_update_topics[topic-expected_log6]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_update_topics[cc-search",
"tests/ui/test_ui_tools.py::TestTopicsView::test_update_topics_list[reorder_topic3]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_update_topics_list[topic1_discussion_continues]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_update_topics_list[new_topic4]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_update_topics_list[first_topic_1]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_keypress_SEARCH_TOPICS[q]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_keypress_GO_BACK[esc]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_mouse_event[mouse_scroll_up]",
"tests/ui/test_ui_tools.py::TestTopicsView::test_mouse_event[mouse_scroll_down]",
"tests/ui/test_ui_tools.py::TestUsersView::test_mouse_event[mouse_scroll_up]",
"tests/ui/test_ui_tools.py::TestUsersView::test_mouse_event[mouse_scroll_down]",
"tests/ui/test_ui_tools.py::TestUsersView::test_mouse_event_left_click[ignore_mouse_click]",
"tests/ui/test_ui_tools.py::TestUsersView::test_mouse_event_left_click[handle_mouse_click]",
"tests/ui/test_ui_tools.py::TestUsersView::test_mouse_event_invalid[unsupported_mouse_release_action]",
"tests/ui/test_ui_tools.py::TestUsersView::test_mouse_event_invalid[unsupported_right_click_mouse_press_action]",
"tests/ui/test_ui_tools.py::TestUsersView::test_mouse_event_invalid[invalid_event_button_combination]",
"tests/ui/test_ui_tools.py::TestMiddleColumnView::test_init",
"tests/ui/test_ui_tools.py::TestMiddleColumnView::test_keypress_focus_header[/]",
"tests/ui/test_ui_tools.py::TestMiddleColumnView::test_keypress_SEARCH_MESSAGES[/]",
"tests/ui/test_ui_tools.py::TestMiddleColumnView::test_keypress_REPLY_MESSAGE[r]",
"tests/ui/test_ui_tools.py::TestMiddleColumnView::test_keypress_REPLY_MESSAGE[enter]",
"tests/ui/test_ui_tools.py::TestMiddleColumnView::test_keypress_STREAM_MESSAGE[c]",
"tests/ui/test_ui_tools.py::TestMiddleColumnView::test_keypress_REPLY_AUTHOR[R]",
"tests/ui/test_ui_tools.py::TestMiddleColumnView::test_keypress_NEXT_UNREAD_PM_stream[p]",
"tests/ui/test_ui_tools.py::TestMiddleColumnView::test_keypress_NEXT_UNREAD_PM_no_pm[p]",
"tests/ui/test_ui_tools.py::TestMiddleColumnView::test_keypress_PRIVATE_MESSAGE[x]",
"tests/ui/test_ui_tools.py::TestRightColumnView::test_init",
"tests/ui/test_ui_tools.py::TestRightColumnView::test_update_user_list_editor_mode",
"tests/ui/test_ui_tools.py::TestRightColumnView::test_update_user_list[user",
"tests/ui/test_ui_tools.py::TestRightColumnView::test_update_user_list[no",
"tests/ui/test_ui_tools.py::TestRightColumnView::test_update_user_presence",
"tests/ui/test_ui_tools.py::TestRightColumnView::test_users_view[None-1-False-active]",
"tests/ui/test_ui_tools.py::TestRightColumnView::test_users_view[users1-1-True-active]",
"tests/ui/test_ui_tools.py::TestRightColumnView::test_users_view[None-0-False-inactive]",
"tests/ui/test_ui_tools.py::TestRightColumnView::test_keypress_SEARCH_PEOPLE[w]",
"tests/ui/test_ui_tools.py::TestRightColumnView::test_keypress_GO_BACK[esc]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_menu_view",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned0]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned1]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned2]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned3]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned4]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned5]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned6]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned7]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned8]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned9]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned10]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned11]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned12]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned13]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned14]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned15]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned16]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned17]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned18]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned19]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned20]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned21]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned22]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned23]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned24]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned25]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned26]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned27]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned28]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned29]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned30]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_streams_view[pinned31]",
"tests/ui/test_ui_tools.py::TestLeftColumnView::test_topics_view",
"tests/ui/test_ui_tools.py::TestTabView::test_tab_render[3-10-expected_output0]"
] | {
"failed_lite_validators": [
"has_short_problem_statement",
"has_many_modified_files",
"has_many_hunks"
],
"has_test_patch": true,
"is_lite": false
} | "2023-04-17T23:11:24Z" | apache-2.0 |