instance_id
stringlengths
10
57
text
stringlengths
1.86k
8.73M
repo
stringlengths
7
53
base_commit
stringlengths
40
40
problem_statement
stringlengths
23
37.7k
hints_text
stringclasses
300 values
created_at
stringdate
2015-10-21 22:58:11
2024-04-30 21:59:25
patch
stringlengths
278
37.8k
test_patch
stringlengths
212
2.22M
version
stringclasses
1 value
FAIL_TO_PASS
listlengths
1
4.94k
PASS_TO_PASS
listlengths
0
7.82k
environment_setup_commit
stringlengths
40
40
facebookincubator__ptr-109
You will be provided with a partial code base and an issue statement explaining a problem to resolve. <issue> If no `required_coverage` set in setup.* files `--print-cov` does not print coverage ## How is `ptr` not doing what you expect? Expected `--print-cov` to show me the coverage even if the setup.* files do no have ``. ## What is your suggestion to make this better? Fix the code to print coverage if the argument is true ## Code/Bug example? If we have no `required_coverage` `--print-cov` is not taken into account. ```python ptr_params = { "entry_point_module": "ansible_shed/main", "test_suite": "ansible_shed.tests.base", "test_suite_timeout": 300, # "required_coverage": { # "aioexabgp/announcer/__init__.py": 50, # }, "run_flake8": True, "run_black": True, "run_mypy": True, } ``` ## How can a developer reproduce this? Comment out `required_coverage` and try getting coverage to print. </issue> <code> [start of README.md] 1 # 🏃‍♀️ `ptr` - Python Test Runner 🏃‍♂️ 2 3 [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/ambv/black) 4 [![Actions Status](https://github.com/facebookincubator/ptr/workflows/ptr_ci/badge.svg)](https://github.com/facebookincubator/ptr/actions) 5 [![PyPI](https://img.shields.io/pypi/v/ptr)](https://pypi.org/project/ptr/) 6 [![Downloads](https://pepy.tech/badge/ptr/week)](https://pepy.tech/project/ptr/week) 7 8 Python Test Runner (ptr) was born to run tests in an opinionated way, within arbitrary code repositories. 9 `ptr` supports many Python projects with unit tests defined in their `setup.(cfg|py)` files per repository. 10 `ptr` allows developers to test multiple projects/modules in one Python environment through the use of a single test virtual environment. 11 12 - `ptr` requires `>=` **python 3.6** 13 - `ptr` itself uses `ptr` to run its tests 👌🏼 14 - `ptr` is supported and tested on *Linux*, *MacOS* + *Windows* Operating Systems 15 16 By adding `ptr` configuration to your `setup.cfg` or `setup.py` you can have `ptr` perform the following, per test suite, in parallel: 17 - run your test suite 18 - check and enforce coverage requirements (via [coverage](https://pypi.org/project/coverage/)), 19 - format code (via [black](https://pypi.org/project/black/)) 20 - perform static type analysis (via [mypy](http://mypy-lang.org/)) 21 22 23 ## Quickstart 24 - Install `ptr` into you virtualenv 25 - `pip install ptr` 26 - Ensure your tests have a base file that can be executed directly 27 - i.e. `python3 test.py` (possibly using `unittest.main()`) 28 - After adding `ptr_params` to setup.py (see example below), run: 29 ``` 30 cd repo 31 ptr 32 ``` 33 34 ## How does `ptr` perform this magic? 🎩 35 36 I'm glad you ask. Under the covers `ptr` performs: 37 - Recursively searches for `setup.(cfg|py)` files from `BASE_DIR` (defaults to your "current working directory" (CWD)) 38 - [AST](https://docs.python.org/3/library/ast.html) parses out the config for each `setup.py` test requirements 39 - If a `setup.cfg` exists, load via configparser and prefer if a `[ptr]` section exists 40 - Creates a [Python Virtual Environment](https://docs.python.org/3/tutorial/venv.html) (*OPTIONALLY* pointed at an internal PyPI mirror) 41 - Runs `ATONCE` tests suites in parallel (i.e. per setup.(cfg|ptr)) 42 - All steps will be run for each suite and ONLY *FAILED* runs will have output written to stdout 43 44 ## Usage 🤓 45 46 To use `ptr` all you need to do is cd to your project or set the base dir via `-b` and execute: 47 48 $ ptr [-dk] [-b some/path] [--venv /tmp/existing_venv] 49 50 For **faster runs** when testing, it is recommended to reuse a Virtual Environment: 51 - `-k` - To keep the virtualenv created by `ptr`. 52 - Use `--venv VENV_PATH` to reuse to an existing virtualenv created by the user. 53 54 ### Help Output 🙋‍♀️ 🙋‍♂️ 55 56 ```shell 57 usage: ptr.py [-h] [-a ATONCE] [-b BASE_DIR] [-d] [-e] [-k] [-m MIRROR] 58 [--print-cov] [--print-non-configured] 59 [--progress-interval PROGRESS_INTERVAL] [--run-disabled] 60 [--stats-file STATS_FILE] [--system-site-packages] [--venv VENV] 61 [--venv-timeout VENV_TIMEOUT] 62 63 optional arguments: 64 -h, --help show this help message and exit 65 -a ATONCE, --atonce ATONCE 66 How many tests to run at once [Default: 6] 67 -b BASE_DIR, --base-dir BASE_DIR 68 Path to recursively look for setup.py files [Default: 69 /Users/cooper/repos/ptr] 70 -d, --debug Verbose debug output 71 -e, --error-on-warnings 72 Have Python warnings raise DeprecationWarning on tests 73 run 74 -k, --keep-venv Do not remove created venv 75 -m MIRROR, --mirror MIRROR 76 URL for pip to use for Simple API [Default: 77 https://pypi.org/simple/] 78 --print-cov Print modules coverage report 79 --print-non-configured 80 Print modules not configured to run ptr 81 --progress-interval PROGRESS_INTERVAL 82 Seconds between status update on test running 83 [Default: Disabled] 84 --run-disabled Force any disabled tests suites to run 85 --stats-file STATS_FILE 86 JSON statistics file [Default: /var/folders/tc/hbwxh76 87 j1hn6gqjd2n2sjn4j9k1glp/T/ptr_stats_12510] 88 --system-site-packages 89 Give the virtual environment access to the system 90 site-packages dir 91 --venv VENV Path to venv to reuse 92 --venv-timeout VENV_TIMEOUT 93 Timeout in seconds for venv creation + deps install 94 [Default: 120] 95 ``` 96 97 ## Configuration 🧰 98 99 `ptr` is configured by placing directives in one or more of the following files. `.ptrconfig` provides 100 base configuration and default values for all projects in the repository, while each `setup.(cfg|py)` 101 overrides the base configuration for the respective packages they define. 102 103 ### `.ptrconfig` 104 105 `ptr` supports a general config in `ini` ([ConfigParser](https://docs.python.org/3/library/configparser.html)) format. 106 A `.ptrconfig` file can be placed at the root of any repository or in any directory within your repository. 107 The first `.ptrconfig` file found via a recursive walk to the root ("/" in POSIX systems) will be used. 108 109 Please refer to [`ptrconfig.sample`](http://github.com/facebookincubator/ptr/blob/master/ptrconfig.sample) for the options available. 110 111 ### `setup.py` 112 113 This is per project in your repository. A simple example, based on `ptr` itself: 114 115 ```python 116 # Specific Python Test Runner (ptr) params for Unit Testing Enforcement 117 ptr_params = { 118 # Where mypy will run to type check your program 119 "entry_point_module": "ptr", 120 # Base Unittest file 121 "test_suite": "ptr_tests", 122 "test_suite_timeout": 300, 123 # Relative path from setup.py to module (e.g. ptr == ptr.py) 124 "required_coverage": {"ptr.py": 99, "TOTAL": 99}, 125 # Run `black --check` or not 126 "run_black": False, 127 # Run mypy or not 128 "run_mypy": True, 129 } 130 ``` 131 132 ### `setup.cfg` 133 134 This is per project in your repository and if exists is preferred over `setup.py`. 135 136 Please refer to [`setup.cfg.sample`](http://github.com/facebookincubator/ptr/blob/master/setup.cfg.sample) for the options available + format. 137 138 ### mypy Specifics 139 140 When enabled, (in `setup.(cfg|py)`) **mypy** can support using a custom `mypy.ini` for each setup.py (module) defined. 141 142 To have `ptr` run mypy using you config: 143 - create a `mypy.ini` in the same directory as your `setup.py` 144 - OR add **[mypy]** section to your `setup.cfg` 145 146 `mypy` Configuration Documentation can be found [here](https://mypy.readthedocs.io/en/stable/config_file.html) 147 - An example `setup.cfg` can be seen [here](http://github.com/facebookincubator/ptr/blob/master/mypy.ini). 148 149 # Example Output 📝 150 151 Here are some example runs. 152 153 ## Successful `ptr` Run: 154 155 Here is what you want to see in your CI logs! 156 ``` 157 [2019-02-06 21:51:45,442] INFO: Starting ptr.py (ptr.py:782) 158 [2019-02-06 21:51:59,471] INFO: Successfully created venv @ /var/folders/tc/hbwxh76j1hn6gqjd2n2sjn4j9k1glp/T/ptr_venv_24397 to run tests (14s) (ptr.py:547) 159 [2019-02-06 21:51:59,472] INFO: Installing /Users/cooper/repos/ptr/setup.py + deps (ptr.py:417) 160 [2019-02-06 21:52:00,726] INFO: Running /Users/cooper/repos/ptr/ptr_tests.py tests via coverage (ptr.py:417) 161 [2019-02-06 21:52:04,153] INFO: Analyzing coverage report for /Users/cooper/repos/ptr/setup.py (ptr.py:417) 162 [2019-02-06 21:52:04,368] INFO: Running mypy for /Users/cooper/repos/ptr/setup.py (ptr.py:417) 163 [2019-05-03 14:54:09,915] INFO: Running flake8 for /Users/cooper/repos/ptr/setup.py (ptr.py:417) 164 [2019-05-03 14:54:10,422] INFO: Running pylint for /Users/cooper/repos/ptr/setup.py (ptr.py:417) 165 [2019-05-03 14:54:14,020] INFO: Running pyre for /Users/cooper/repos/ptr/setup.py (ptr.py:417) 166 [2019-02-06 21:52:07,733] INFO: /Users/cooper/repos/ptr/setup.py has passed all configured tests (ptr.py:509) 167 -- Summary (total time 22s): 168 169 ✅ PASS: 1 170 ❌ FAIL: 0 171 ⌛️ TIMEOUT: 0 172 💩 TOTAL: 1 173 174 -- 1 / 1 (100%) `setup.py`'s have `ptr` tests running 175 ``` 176 ## Unsuccessful `ptr` Run Examples: 177 178 Here are some examples of runs failing. Any "step" can fail. All output is predominately the underlying tool. 179 180 ### Unit Test Failure 181 182 ``` 183 [2019-02-06 21:53:58,121] INFO: Starting ptr.py (ptr.py:782) 184 [2019-02-06 21:53:58,143] INFO: Installing /Users/cooper/repos/ptr/setup.py + deps (ptr.py:417) 185 [2019-02-06 21:53:59,698] INFO: Running /Users/cooper/repos/ptr/ptr_tests.py tests via coverage (ptr.py:417) 186 -- Summary (total time 5s): 187 188 ✅ PASS: 0 189 ❌ FAIL: 1 190 ⌛️ TIMEOUT: 0 191 💩 TOTAL: 1 192 193 -- 1 / 1 (100%) `setup.py`'s have `ptr` tests running 194 195 -- Failure Output -- 196 197 /Users/cooper/repos/ptr/setup.py (failed 'tests_run' step): 198 ...F.................... 199 ====================================================================== 200 FAIL: test_config (__main__.TestPtr) 201 ---------------------------------------------------------------------- 202 Traceback (most recent call last): 203 File "/Users/cooper/repos/ptr/ptr_tests.py", line 125, in test_config 204 self.assertEqual(len(sc["ptr"]["venv_pkgs"].split()), 4) 205 AssertionError: 5 != 4 206 207 ---------------------------------------------------------------------- 208 Ran 24 tests in 3.221s 209 210 FAILED (failures=1) 211 ``` 212 213 ### coverage 214 215 ``` 216 [2019-02-06 21:55:42,947] INFO: Starting ptr.py (ptr.py:782) 217 [2019-02-06 21:55:42,969] INFO: Installing /Users/cooper/repos/ptr/setup.py + deps (ptr.py:417) 218 [2019-02-06 21:55:44,920] INFO: Running /Users/cooper/repos/ptr/ptr_tests.py tests via coverage (ptr.py:417) 219 [2019-02-06 21:55:49,628] INFO: Analyzing coverage report for /Users/cooper/repos/ptr/setup.py (ptr.py:417) 220 -- Summary (total time 7s): 221 222 ✅ PASS: 0 223 ❌ FAIL: 1 224 ⌛️ TIMEOUT: 0 225 💩 TOTAL: 1 226 227 -- 1 / 1 (100%) `setup.py`'s have `ptr` tests running 228 229 -- Failure Output -- 230 231 /Users/cooper/repos/ptr/setup.py (failed 'analyze_coverage' step): 232 The following files did not meet coverage requirements: 233 ptr.py: 84 < 99 - Missing: 146-147, 175, 209, 245, 269, 288-291, 334-336, 414-415, 425-446, 466, 497, 506, 541-543, 562, 611-614, 639-688 234 ``` 235 236 ### black 237 238 ``` 239 [2019-02-06 22:34:20,029] INFO: Starting ptr.py (ptr.py:804) 240 [2019-02-06 22:34:20,060] INFO: Installing /Users/cooper/repos/ptr/setup.py + deps (ptr.py:430) 241 [2019-02-06 22:34:21,614] INFO: Running /Users/cooper/repos/ptr/ptr_tests.py tests via coverage (ptr.py:430) 242 [2019-02-06 22:34:25,208] INFO: Analyzing coverage report for /Users/cooper/repos/ptr/setup.py (ptr.py:430) 243 [2019-02-06 22:34:25,450] INFO: Running mypy for /Users/cooper/repos/ptr/setup.py (ptr.py:430) 244 [2019-02-06 22:34:26,422] INFO: Running black for /Users/cooper/repos/ptr/setup.py (ptr.py:430) 245 -- Summary (total time 7s): 246 247 ✅ PASS: 0 248 ❌ FAIL: 1 249 ⌛️ TIMEOUT: 0 250 💩 TOTAL: 1 251 252 -- 1 / 1 (100%) `setup.py`'s have `ptr` tests running 253 254 -- Failure Output -- 255 256 /Users/cooper/repos/ptr/setup.py (failed 'black_run' step): 257 would reformat /Users/cooper/repos/ptr/ptr.py 258 All done! 💥 💔 💥 259 1 file would be reformatted, 4 files would be left unchanged. 260 ``` 261 262 ### mypy 263 264 ``` 265 [2019-02-06 22:35:39,480] INFO: Starting ptr.py (ptr.py:802) 266 [2019-02-06 22:35:39,531] INFO: Installing /Users/cooper/repos/ptr/setup.py + deps (ptr.py:428) 267 [2019-02-06 22:35:41,203] INFO: Running /Users/cooper/repos/ptr/ptr_tests.py tests via coverage (ptr.py:428) 268 [2019-02-06 22:35:45,156] INFO: Analyzing coverage report for /Users/cooper/repos/ptr/setup.py (ptr.py:428) 269 [2019-02-06 22:35:45,413] INFO: Running mypy for /Users/cooper/repos/ptr/setup.py (ptr.py:428) 270 -- Summary (total time 6s): 271 272 ✅ PASS: 0 273 ❌ FAIL: 1 274 ⌛️ TIMEOUT: 0 275 💩 TOTAL: 1 276 277 -- 1 / 1 (100%) `setup.py`'s have `ptr` tests running 278 279 -- Failure Output -- 280 281 /Users/cooper/repos/ptr/setup.py (failed 'mypy_run' step): 282 /Users/cooper/repos/ptr/ptr.py: note: In function "_write_stats_file": 283 /Users/cooper/repos/ptr/ptr.py:179: error: Argument 1 to "open" has incompatible type "Path"; expected "Union[str, bytes, int]" 284 /Users/cooper/repos/ptr/ptr.py: note: In function "run_tests": 285 /Users/cooper/repos/ptr/ptr.py:700: error: Argument 1 to "_write_stats_file" has incompatible type "str"; expected "Path" 286 ``` 287 288 ### pyre 289 290 ``` 291 cooper-mbp1:ptr cooper$ /tmp/tp/bin/ptr --venv /var/folders/tc/hbwxh76j1hn6gqjd2n2sjn4j9k1glp/T/ptr_venv_49117 292 [2019-05-03 14:51:43,623] INFO: Starting /tmp/tp/bin/ptr (ptr.py:1023) 293 [2019-05-03 14:51:43,657] INFO: Installing /Users/cooper/repos/ptr/setup.py + deps (ptr.py:565) 294 [2019-05-03 14:51:44,840] INFO: Running ptr_tests tests via coverage (ptr.py:565) 295 [2019-05-03 14:51:47,361] INFO: Analyzing coverage report for /Users/cooper/repos/ptr/setup.py (ptr.py:565) 296 [2019-05-03 14:51:47,559] INFO: Running mypy for /Users/cooper/repos/ptr/setup.py (ptr.py:565) 297 [2019-05-03 14:51:47,827] INFO: Running black for /Users/cooper/repos/ptr/setup.py (ptr.py:565) 298 [2019-05-03 14:51:47,996] INFO: Running flake8 for /Users/cooper/repos/ptr/setup.py (ptr.py:565) 299 [2019-05-03 14:51:48,566] INFO: Running pylint for /Users/cooper/repos/ptr/setup.py (ptr.py:565) 300 [2019-05-03 14:51:52,301] INFO: Running pyre for /Users/cooper/repos/ptr/setup.py (ptr.py:565) 301 [2019-05-03 14:51:54,983] INFO: /Users/cooper/repos/ptr/setup.py has passed all configured tests (ptr.py:668) 302 -- Summary (total time 11s): 303 304 ✅ PASS: 1 305 ❌ FAIL: 0 306 ⌛️ TIMEOUT: 0 307 💩 TOTAL: 1 308 309 -- 1 / 1 (100%) `setup.py`'s have `ptr` tests running 310 311 -- Failure Output -- 312 313 /Users/cooper/repos/ptr/setup.py (failed 'pyre_run' step): 314 2019-05-03 14:54:14,173 INFO No binary specified, looking for `pyre.bin` in PATH 315 2019-05-03 14:54:14,174 INFO Found: `/var/folders/tc/hbwxh76j1hn6gqjd2n2sjn4j9k1glp/T/ptr_venv_49117/bin/pyre.bin` 316 ... *(truncated)* ... 317 ptr.py:602:25 Undefined name [18]: Global name `stdout` is not defined, or there is at least one control flow path that doesn't define `stdout`. 318 ``` 319 320 # FAQ ⁉️ 321 322 ### Q. How do I debug? I need output! 323 324 - `ptr` developers recommend that if you want output, please cause a test to fail 325 - e.g. `raise ZeroDivisionError` 326 - Another recommended way is to run your tests with the default `setup.py test` using a `ptr` created venv: 327 - `cd to/my/code` 328 - `/tmp/venv/bin/python setup.py test` 329 330 ### Q. How do I get specific version of black, coverage, mypy etc.? 331 332 - Just simply hard set the version in the .ptrconfig in your repo or use `requirements.txt` to pre-install before running `ptr` 333 - All `pip` [PEP 440 version specifiers](https://www.python.org/dev/peps/pep-0440/) are supported 334 335 ### Q. Why is the venv creation so slow? 336 337 - `ptr` attempts to update from a PyPI compatible mirror (PEP 381) or PyPI itself 338 - Running a package cache or local mirror can greatly increase speed. Example software to do this: 339 - [bandersnatch](https://pypi.org/project/bandersnatch): Can do selected or FULL PyPI mirrors. The maintainer is also devilishly good looking. 340 - [devpi](https://pypi.org/project/devpi/): Can be ran and used to *proxy* packages locally when pip goes out to grab your dependencies. 341 - Please ensure you're using the `-k` or `--venv` option to no recreate a virtualenv each run when debugging your tests! 342 343 ### Q. Why is ptr not able to run `pyre` on Windows? 344 345 - `pyre` (pyre-check on PyPI) does not ship a Windows wheel with the ocaml pyre.bin 346 347 348 ### Q. Why do you depend on >= coverage 5.0.1 349 350 - `coverage` 5.0 introduced using sqlite and we don't want to have a mix of 4.x and 5.x for ptr 351 - < 5.0 could possibly still work as we now ensure to run each projects tests from setup_py.parent CWD with subprocess 352 353 354 # Contact or join the ptr community 💬 355 356 To chat in real time, hit us up on IRC. Otherwise, GitHub issues are always welcome! 357 IRC: `#pythontestrunner` on *FreeNode* 358 359 See the [CONTRIBUTING](CONTRIBUTING.md) file for how to help out. 360 361 ## License 362 `ptr` is MIT licensed, as found in the [LICENSE file](LICENSE). 363 364 ## Terms of Use + Privacy Policy 365 366 - [Terms of Use](https://opensource.facebook.com/legal/terms) 367 - [Privacy Policy](https://opensource.facebook.com/legal/privacy) 368 [end of README.md] [start of ptr.py] 1 #!/usr/bin/env python3 2 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 3 4 # This source code is licensed under the MIT license found in the 5 # LICENSE file in the root directory of this source tree. 6 # coding=utf8 7 8 import argparse 9 import ast 10 import asyncio 11 import logging 12 import sys 13 from collections import defaultdict, namedtuple 14 from configparser import ConfigParser 15 from enum import Enum 16 from json import dump 17 from os import chdir, cpu_count, environ, getcwd, getpid 18 from os.path import sep 19 from pathlib import Path 20 from platform import system 21 from shutil import rmtree 22 from subprocess import CalledProcessError 23 from tempfile import gettempdir 24 from time import time 25 from typing import Any, Dict, List, Optional, Sequence, Set, Tuple, Union 26 27 28 LOG = logging.getLogger(__name__) 29 MACOSX = system() == "Darwin" 30 WINDOWS = system() == "Windows" 31 # Windows needs to use a ProactorEventLoop for subprocesses 32 # Need to use sys.platform for mypy to understand 33 # https://mypy.readthedocs.io/en/latest/common_issues.html#python-version-and-system-platform-checks # noqa: B950 # pylint: disable=C0301 34 if sys.platform == "win32": 35 asyncio.set_event_loop(asyncio.ProactorEventLoop()) 36 37 38 def _config_default() -> ConfigParser: 39 if WINDOWS: 40 venv_pkgs = "black coverage flake8 mypy pip pylint setuptools" 41 else: 42 venv_pkgs = "black coverage flake8 mypy pip pylint pyre-check setuptools" 43 44 LOG.info("Using default config settings") 45 cp = ConfigParser() 46 cp["ptr"] = {} 47 cp["ptr"]["atonce"] = str(int((cpu_count() or 20) / 2) or 1) 48 cp["ptr"]["exclude_patterns"] = "build* yocto" 49 cp["ptr"]["pypi_url"] = "https://pypi.org/simple/" 50 cp["ptr"]["venv_pkgs"] = venv_pkgs 51 return cp 52 53 54 def _config_read( 55 cwd: str, conf_name: str = ".ptrconfig", cp: Optional[ConfigParser] = None 56 ) -> ConfigParser: 57 """ Look from cwd to / for a "conf_name" file - If so read it in """ 58 if cp is None: 59 cp = _config_default() 60 61 cwd_path = Path(cwd) # type: Path 62 root_path = Path(f"{cwd_path.drive}\\") if WINDOWS else Path("/") 63 64 while cwd_path: 65 ptrconfig_path = cwd_path / conf_name 66 if ptrconfig_path.exists(): 67 cp.read(str(ptrconfig_path)) 68 69 LOG.info(f"Loading found config @ {ptrconfig_path}") 70 break 71 72 if cwd_path == root_path: 73 break 74 75 cwd_path = cwd_path.parent 76 77 return cp 78 79 80 CWD = getcwd() 81 CONFIG = _config_read(CWD) 82 PIP_CONF_TEMPLATE = """\ 83 [global] 84 index-url = {} 85 timeout = {}""" 86 # Windows venv + pip are super slow 87 VENV_TIMEOUT = 120 88 89 90 class StepName(Enum): 91 pip_install = 1 92 tests_run = 2 93 analyze_coverage = 3 94 mypy_run = 4 95 black_run = 5 96 pylint_run = 6 97 flake8_run = 7 98 pyre_run = 8 99 100 101 coverage_line = namedtuple("coverage_line", ["stmts", "miss", "cover", "missing"]) 102 step = namedtuple( 103 "step", ["step_name", "run_condition", "cmds", "log_message", "timeout"] 104 ) 105 test_result = namedtuple( 106 "test_result", ["setup_py_path", "returncode", "output", "runtime", "timeout"] 107 ) 108 109 110 def _get_site_packages_path(venv_path: Path) -> Optional[Path]: 111 lib_path = venv_path / ("Lib" if WINDOWS else "lib") 112 for apath in lib_path.iterdir(): 113 if apath.is_dir() and apath.match("python*"): 114 return apath / "site-packages" 115 if apath.is_dir() and apath.name == "site-packages": 116 return apath 117 118 LOG.error(f"Unable to find a python lib dir in {lib_path}") 119 return None 120 121 122 def _remove_pct_symbol(pct_str: str) -> str: 123 return pct_str.strip().replace("%", "") 124 125 126 def _analyze_coverage( 127 venv_path: Path, 128 setup_py_path: Path, 129 required_cov: Dict[str, float], 130 coverage_report: str, 131 stats: Dict[str, int], 132 test_run_start_time: float, 133 ) -> Optional[test_result]: 134 module_path = setup_py_path.parent 135 site_packages_path = _get_site_packages_path(venv_path) 136 if not site_packages_path: 137 LOG.error("Analyze coverage is unable to find site-packages path") 138 return None 139 relative_site_packages = str(site_packages_path.relative_to(venv_path)) + sep 140 141 if not coverage_report: 142 LOG.error( 143 f"No coverage report for {setup_py_path} - Unable to enforce coverage" 144 " requirements" 145 ) 146 return None 147 if not required_cov: 148 LOG.error(f"No required coverage to enforce for {setup_py_path}") 149 return None 150 151 coverage_lines = {} 152 for line in coverage_report.splitlines(): 153 if not line or line.startswith("-") or line.startswith("Name"): 154 continue 155 156 module_path_str = None 157 sl_path = None 158 159 sl = line.split(maxsplit=4) 160 if sl[0] != "TOTAL": 161 sl_path = _max_osx_private_handle(sl[0], site_packages_path) 162 163 if sl_path and sl_path.is_absolute() and site_packages_path: 164 for possible_abs_path in (module_path, site_packages_path): 165 try: 166 module_path_str = str(sl_path.relative_to(possible_abs_path)) 167 except ValueError as ve: 168 LOG.debug(ve) 169 elif sl_path: 170 module_path_str = str(sl_path).replace(relative_site_packages, "") 171 else: 172 module_path_str = sl[0] 173 174 if not module_path_str: 175 LOG.error( 176 f"[{setup_py_path}] Unable to find path relative path for {sl[0]}" 177 ) 178 continue 179 180 if len(sl) == 4: 181 coverage_lines[module_path_str] = coverage_line( 182 float(sl[1]), float(sl[2]), float(_remove_pct_symbol(sl[3])), "" 183 ) 184 else: 185 coverage_lines[module_path_str] = coverage_line( 186 float(sl[1]), float(sl[2]), float(_remove_pct_symbol(sl[3])), sl[4] 187 ) 188 189 if sl[0] != "TOTAL": 190 stats[ 191 f"suite.{module_path.name}_coverage.file.{module_path_str}" 192 ] = coverage_lines[module_path_str].cover 193 else: 194 stats[f"suite.{module_path.name}_coverage.total"] = coverage_lines[ 195 module_path_str 196 ].cover 197 198 failed_output = "The following files did not meet coverage requirements:\n" 199 failed_coverage = False 200 201 for afile, cov_req in required_cov.items(): 202 try: 203 cover = coverage_lines[afile].cover 204 except KeyError: 205 err = ( 206 "{} has not reported any coverage. Does the file exist? " 207 "Does it get ran during tests? Remove from setup config.".format(afile) 208 ) 209 keyerror_runtime = int(time() - test_run_start_time) 210 return test_result( 211 setup_py_path, 212 StepName.analyze_coverage.value, 213 err, 214 keyerror_runtime, 215 False, 216 ) 217 218 if cover < cov_req: 219 failed_coverage = True 220 failed_output += " {}: {} < {} - Missing: {}\n".format( 221 afile, 222 coverage_lines[afile].cover, 223 cov_req, 224 coverage_lines[afile].missing, 225 ) 226 227 if failed_coverage: 228 failed_cov_runtime = int(time() - test_run_start_time) 229 return test_result( 230 setup_py_path, 231 StepName.analyze_coverage.value, 232 failed_output, 233 failed_cov_runtime, 234 False, 235 ) 236 237 return None 238 239 240 def _max_osx_private_handle( 241 potenital_path: str, site_packages_path: Path 242 ) -> Optional[Path]: 243 """On Mac OS X `coverage` seems to always resolve /private for anything stored in /var. 244 ptr's usage of gettempdir() seems to result in using dirs within there 245 This function strips /private if it exists on the path supplied from coverage 246 ONLY IF site_packages_path is not based in /private""" 247 if not MACOSX: 248 return Path(potenital_path) 249 250 private_path = Path("/private") 251 try: 252 site_packages_path.relative_to(private_path) 253 return Path(potenital_path) 254 except ValueError: 255 pass 256 257 return Path(potenital_path.replace("/private", "")) 258 259 260 def _write_stats_file(stats_file: str, stats: Dict[str, int]) -> None: 261 stats_file_path = Path(stats_file) 262 if not stats_file_path.is_absolute(): 263 stats_file_path = Path(CWD) / stats_file_path 264 try: 265 with stats_file_path.open("w", encoding="utf8") as sfp: 266 dump(stats, sfp, indent=2, sort_keys=True) 267 except OSError as ose: 268 LOG.exception( 269 f"Unable to write out JSON statistics file to {stats_file} ({ose})" 270 ) 271 272 273 def _generate_black_cmd(module_dir: Path, black_exe: Path) -> Tuple[str, ...]: 274 return (str(black_exe), "--check", ".") 275 276 277 def _generate_install_cmd( 278 pip_exe: str, module_dir: str, config: Dict[str, Any] 279 ) -> Tuple[str, ...]: 280 cmds = [pip_exe, "-v", "install", module_dir] 281 if "tests_require" in config and config["tests_require"]: 282 for dep in config["tests_require"]: 283 cmds.append(dep) 284 285 return tuple(cmds) 286 287 288 def _generate_test_suite_cmd(coverage_exe: Path, config: Dict) -> Tuple[str, ...]: 289 if config.get("test_suite", False): 290 return (str(coverage_exe), "run", "-m", config["test_suite"]) 291 return () 292 293 294 def _generate_mypy_cmd( 295 module_dir: Path, mypy_exe: Path, config: Dict 296 ) -> Tuple[str, ...]: 297 if config.get("run_mypy", False): 298 mypy_entry_point = module_dir / f"{config['entry_point_module']}.py" 299 else: 300 return () 301 302 cmds = [str(mypy_exe)] 303 mypy_ini_path = module_dir / "mypy.ini" 304 if mypy_ini_path.exists(): 305 cmds.extend(["--config", str(mypy_ini_path)]) 306 cmds.append(str(mypy_entry_point)) 307 return tuple(cmds) 308 309 310 def _generate_flake8_cmd( 311 module_dir: Path, flake8_exe: Path, config: Dict 312 ) -> Tuple[str, ...]: 313 if not config.get("run_flake8", False): 314 return () 315 316 cmds = [str(flake8_exe)] 317 flake8_config = module_dir / ".flake8" 318 if flake8_config.exists(): 319 cmds.extend(["--config", str(flake8_config)]) 320 return tuple(cmds) 321 322 323 def _generate_pylint_cmd( 324 module_dir: Path, pylint_exe: Path, config: Dict 325 ) -> Tuple[str, ...]: 326 if not config.get("run_pylint", False): 327 return () 328 329 py_files = set() # type: Set[str] 330 find_py_files(py_files, module_dir) 331 332 cmds = [str(pylint_exe)] 333 pylint_config = module_dir / ".pylint" 334 if pylint_config.exists(): 335 cmds.extend(["--rcfile", str(pylint_config)]) 336 return (*cmds, *sorted(py_files)) 337 338 339 def _generate_pyre_cmd( 340 module_dir: Path, pyre_exe: Path, config: Dict 341 ) -> Tuple[str, ...]: 342 if not config.get("run_pyre", False) or WINDOWS: 343 return () 344 345 return (str(pyre_exe), "--source-directory", str(module_dir), "check") 346 347 348 def _parse_setup_params(setup_py: Path) -> Dict[str, Any]: 349 with setup_py.open("r", encoding="utf8") as sp: 350 setup_tree = ast.parse(sp.read()) 351 352 LOG.debug(f"AST visiting {setup_py}") 353 for node in ast.walk(setup_tree): 354 if isinstance(node, ast.Assign): 355 for target in node.targets: 356 target_id = getattr(target, "id", None) 357 if not target_id: 358 continue 359 360 if target_id == "ptr_params": 361 LOG.debug(f"Found ptr_params in {setup_py}") 362 return dict(ast.literal_eval(node.value)) 363 return {} 364 365 366 def _get_test_modules( 367 base_path: Path, 368 stats: Dict[str, int], 369 run_disabled: bool, 370 print_non_configured: bool, 371 ) -> Dict[Path, Dict]: 372 get_tests_start_time = time() 373 all_setup_pys = find_setup_pys( 374 base_path, 375 set(CONFIG["ptr"]["exclude_patterns"].split()) 376 if CONFIG["ptr"]["exclude_patterns"] 377 else set(), 378 ) 379 stats["total.setup_pys"] = len(all_setup_pys) 380 381 non_configured_modules = [] # type: List[Path] 382 test_modules = {} # type: Dict[Path, Dict] 383 for setup_py in all_setup_pys: 384 disabled_err_msg = f"Not running {setup_py} as ptr is disabled via config" 385 # If a setup.cfg exists lets prefer it, if there is a [ptr] section 386 ptr_params = parse_setup_cfg(setup_py) 387 if not ptr_params: 388 ptr_params = _parse_setup_params(setup_py) 389 390 if ptr_params: 391 if ptr_params.get("disabled", False) and not run_disabled: 392 LOG.info(disabled_err_msg) 393 stats["total.disabled"] += 1 394 else: 395 test_modules[setup_py] = ptr_params 396 397 if setup_py not in test_modules: 398 non_configured_modules.append(setup_py) 399 400 if print_non_configured and non_configured_modules: 401 print_non_configured_modules(non_configured_modules) 402 403 stats["total.non_ptr_setup_pys"] = len(non_configured_modules) 404 stats["total.ptr_setup_pys"] = len(test_modules) 405 stats["runtime.parse_setup_pys"] = int(time() - get_tests_start_time) 406 return test_modules 407 408 409 def _handle_debug(debug: bool) -> bool: 410 """Turn on debugging if asked otherwise INFO default""" 411 log_level = logging.DEBUG if debug else logging.INFO 412 logging.basicConfig( 413 format="[%(asctime)s] %(levelname)s: %(message)s (%(filename)s:%(lineno)d)", 414 level=log_level, 415 ) 416 return debug 417 418 419 def _validate_base_dir(base_dir: str) -> Path: 420 base_dir_path = Path(base_dir) 421 if not base_dir_path.is_absolute(): 422 base_dir_path = Path(CWD) / base_dir_path 423 424 if not base_dir_path.exists(): 425 LOG.error(f"{base_dir} does not exit. Not running tests") 426 sys.exit(69) 427 428 return base_dir_path 429 430 431 async def _gen_check_output( 432 cmd: Sequence[str], 433 timeout: Union[int, float] = 30, 434 env: Optional[Dict[str, str]] = None, 435 cwd: Optional[Path] = None, 436 ) -> Tuple[bytes, bytes]: 437 process = await asyncio.create_subprocess_exec( 438 *cmd, 439 stdout=asyncio.subprocess.PIPE, 440 stderr=asyncio.subprocess.STDOUT, 441 env=env, 442 cwd=cwd, 443 ) 444 try: 445 (stdout, stderr) = await asyncio.wait_for(process.communicate(), timeout) 446 except asyncio.TimeoutError: 447 process.kill() 448 await process.wait() 449 raise 450 451 if process.returncode != 0: 452 cmd_str = " ".join(cmd) 453 raise CalledProcessError( 454 process.returncode or -1, cmd_str, output=stdout, stderr=stderr 455 ) 456 457 return (stdout, stderr) 458 459 460 async def _progress_reporter( 461 progress_interval: float, queue: asyncio.Queue, total_tests: int 462 ) -> None: 463 while queue.qsize() > 0: 464 done_count = total_tests - queue.qsize() 465 LOG.info( 466 "{} / {} test suites ran ({}%)".format( 467 done_count, total_tests, int((done_count / total_tests) * 100) 468 ) 469 ) 470 await asyncio.sleep(progress_interval) 471 472 LOG.debug("progress_reporter finished") 473 474 475 def _set_build_env(build_base_path: Optional[Path]) -> Dict[str, str]: 476 build_environ = environ.copy() 477 478 if not build_base_path or not build_base_path.exists(): 479 if build_base_path: 480 LOG.error( 481 f"Configured local build env path {build_base_path} does not exist" 482 ) 483 return build_environ 484 485 if build_base_path.exists(): 486 build_env_vars = [ 487 ( 488 ("PATH", build_base_path / "Scripts") 489 if WINDOWS 490 else ("PATH", build_base_path / "sbin") 491 ), 492 ("C_INCLUDE_PATH", build_base_path / "include"), 493 ("CPLUS_INCLUDE_PATH", build_base_path / "include"), 494 ] 495 if not WINDOWS: 496 build_env_vars.append(("PATH", build_base_path / "bin")) 497 498 for var_name, value in build_env_vars: 499 if var_name in build_environ: 500 build_environ[var_name] = f"{value}:{build_environ[var_name]}" 501 else: 502 build_environ[var_name] = str(value) 503 else: 504 LOG.error( 505 "{} does not exist. Not add int PATH + INCLUDE Env variables".format( 506 build_base_path 507 ) 508 ) 509 510 return build_environ 511 512 513 def _set_pip_mirror( 514 venv_path: Path, mirror: str = CONFIG["ptr"]["pypi_url"], timeout: int = 2 515 ) -> None: 516 pip_conf_path = venv_path / "pip.conf" 517 with pip_conf_path.open("w", encoding="utf8") as pcfp: 518 print(PIP_CONF_TEMPLATE.format(mirror, timeout), file=pcfp) 519 520 521 async def _test_steps_runner( # pylint: disable=R0914 522 test_run_start_time: int, 523 tests_to_run: Dict[Path, Dict], 524 setup_py_path: Path, 525 venv_path: Path, 526 env: Dict, 527 stats: Dict[str, int], 528 error_on_warnings: bool, 529 print_cov: bool = False, 530 ) -> Tuple[Optional[test_result], int]: 531 bin_dir = "Scripts" if WINDOWS else "bin" 532 exe = ".exe" if WINDOWS else "" 533 black_exe = venv_path / bin_dir / f"black{exe}" 534 coverage_exe = venv_path / bin_dir / f"coverage{exe}" 535 flake8_exe = venv_path / bin_dir / f"flake8{exe}" 536 mypy_exe = venv_path / bin_dir / f"mypy{exe}" 537 pip_exe = venv_path / bin_dir / f"pip{exe}" 538 pylint_exe = venv_path / bin_dir / f"pylint{exe}" 539 pyre_exe = venv_path / bin_dir / f"pyre{exe}" 540 config = tests_to_run[setup_py_path] 541 542 steps = ( 543 step( 544 StepName.pip_install, 545 True, 546 _generate_install_cmd(str(pip_exe), str(setup_py_path.parent), config), 547 f"Installing {setup_py_path} + deps", 548 config["test_suite_timeout"], 549 ), 550 step( 551 StepName.tests_run, 552 bool("test_suite" in config and config["test_suite"]), 553 _generate_test_suite_cmd(coverage_exe, config), 554 f"Running {config.get('test_suite', '')} tests via coverage", 555 config["test_suite_timeout"], 556 ), 557 step( 558 StepName.analyze_coverage, 559 bool( 560 "required_coverage" in config 561 and config["required_coverage"] 562 and len(config["required_coverage"]) > 0 563 ), 564 (str(coverage_exe), "report", "-m"), 565 f"Analyzing coverage report for {setup_py_path}", 566 config["test_suite_timeout"], 567 ), 568 step( 569 StepName.mypy_run, 570 bool("run_mypy" in config and config["run_mypy"]), 571 _generate_mypy_cmd(setup_py_path.parent, mypy_exe, config), 572 f"Running mypy for {setup_py_path}", 573 config["test_suite_timeout"], 574 ), 575 step( 576 StepName.black_run, 577 bool("run_black" in config and config["run_black"]), 578 _generate_black_cmd(setup_py_path.parent, black_exe), 579 f"Running black for {setup_py_path}", 580 config["test_suite_timeout"], 581 ), 582 step( 583 StepName.flake8_run, 584 bool("run_flake8" in config and config["run_flake8"]), 585 _generate_flake8_cmd(setup_py_path.parent, flake8_exe, config), 586 f"Running flake8 for {setup_py_path}", 587 config["test_suite_timeout"], 588 ), 589 step( 590 StepName.pylint_run, 591 bool("run_pylint" in config and config["run_pylint"]), 592 _generate_pylint_cmd(setup_py_path.parent, pylint_exe, config), 593 f"Running pylint for {setup_py_path}", 594 config["test_suite_timeout"], 595 ), 596 step( 597 StepName.pyre_run, 598 bool("run_pyre" in config and config["run_pyre"] and not WINDOWS), 599 _generate_pyre_cmd(setup_py_path.parent, pyre_exe, config), 600 f"Running pyre for {setup_py_path}", 601 config["test_suite_timeout"], 602 ), 603 ) 604 605 steps_ran = 0 606 for a_step in steps: 607 a_test_result = None 608 # Skip test if disabled 609 if not a_step.run_condition: 610 LOG.info(f"Not running {a_step.log_message} step") 611 continue 612 613 LOG.info(a_step.log_message) 614 stdout = b"" 615 steps_ran += 1 616 try: 617 if a_step.cmds: 618 LOG.debug(f"CMD: {' '.join(a_step.cmds)}") 619 620 # If we're running tests and we want warnings to be errors 621 step_env = env 622 if a_step.step_name in [StepName.tests_run, StepName.pyre_run]: 623 step_env = env.copy() 624 step_env["PYTHONPATH"] = getcwd() 625 626 if a_step.step_name == StepName.tests_run and error_on_warnings: 627 step_env["PYTHONWARNINGS"] = "error" 628 LOG.debug("Setting PYTHONWARNINGS to error") 629 630 stdout, _stderr = await _gen_check_output( 631 a_step.cmds, a_step.timeout, env=step_env, cwd=setup_py_path.parent 632 ) 633 else: 634 LOG.debug(f"Skipping running a cmd for {a_step} step") 635 except CalledProcessError as cpe: 636 err_output = cpe.stdout.decode("utf8") 637 638 LOG.debug(f"{a_step.log_message} FAILED for {setup_py_path}") 639 a_test_result = test_result( 640 setup_py_path, 641 a_step.step_name.value, 642 err_output, 643 int(time() - test_run_start_time), 644 False, 645 ) 646 except asyncio.TimeoutError as toe: 647 LOG.debug(f"{setup_py_path} timed out running {a_step.log_message} ({toe})") 648 a_test_result = test_result( 649 setup_py_path, 650 a_step.step_name.value, 651 f"Timeout during {a_step.log_message}", 652 a_step.timeout, 653 True, 654 ) 655 656 if a_step.step_name is StepName.analyze_coverage: 657 cov_report = stdout.decode("utf8") if stdout else "" 658 if print_cov: 659 print(f"{setup_py_path}:\n{cov_report}") 660 661 if a_step.run_condition: 662 a_test_result = _analyze_coverage( 663 venv_path, 664 setup_py_path, 665 config["required_coverage"], 666 cov_report, 667 stats, 668 test_run_start_time, 669 ) 670 # If we've had a failure return 671 if a_test_result: 672 return a_test_result, steps_ran 673 674 return None, steps_ran 675 676 677 async def _test_runner( 678 queue: asyncio.Queue, 679 tests_to_run: Dict[Path, Dict], 680 test_results: List[test_result], 681 venv_path: Path, 682 print_cov: bool, 683 stats: Dict[str, int], 684 error_on_warnings: bool, 685 idx: int, 686 ) -> None: 687 extra_build_env_path = ( 688 Path(CONFIG["ptr"]["extra_build_env_prefix"]) 689 if "extra_build_env_prefix" in CONFIG["ptr"] 690 else None 691 ) 692 env = _set_build_env(extra_build_env_path) 693 694 while True: 695 try: 696 setup_py_path = queue.get_nowait() 697 except asyncio.QueueEmpty: 698 LOG.debug("test_runner {} exiting".format(idx)) 699 return 700 701 test_run_start_time = int(time()) 702 test_fail_result, steps_ran = await _test_steps_runner( 703 test_run_start_time, 704 tests_to_run, 705 setup_py_path, 706 venv_path, 707 env, 708 stats, 709 error_on_warnings, 710 print_cov, 711 ) 712 total_success_runtime = int(time() - test_run_start_time) 713 if test_fail_result: 714 test_results.append(test_fail_result) 715 else: 716 success_output = f"{setup_py_path} has passed all configured tests" 717 LOG.info(success_output) 718 test_results.append( 719 test_result( 720 setup_py_path, 0, success_output, total_success_runtime, False 721 ) 722 ) 723 724 stats_name = setup_py_path.parent.name 725 stats[f"suite.{stats_name}_runtime"] = total_success_runtime 726 stats[f"suite.{stats_name}_completed_steps"] = steps_ran 727 728 queue.task_done() 729 730 731 async def create_venv( 732 mirror: str, 733 py_exe: str = sys.executable, 734 install_pkgs: bool = True, 735 timeout: float = VENV_TIMEOUT, 736 system_site_packages: bool = False, 737 ) -> Optional[Path]: 738 start_time = time() 739 venv_path = Path(gettempdir()) / f"ptr_venv_{getpid()}" 740 if WINDOWS: 741 pip_exe = venv_path / "Scripts" / "pip.exe" 742 else: 743 pip_exe = venv_path / "bin" / "pip" 744 745 install_cmd: List[str] = [] 746 try: 747 cmd = [py_exe, "-m", "venv", str(venv_path)] 748 if system_site_packages: 749 cmd.append("--system-site-packages") 750 751 await _gen_check_output(cmd, timeout=timeout) 752 _set_pip_mirror(venv_path, mirror) 753 if install_pkgs: 754 install_cmd = [str(pip_exe), "install"] 755 install_cmd.extend(CONFIG["ptr"]["venv_pkgs"].split()) 756 await _gen_check_output(install_cmd, timeout=timeout) 757 except CalledProcessError as cpe: 758 LOG.exception(f"Failed to setup venv @ {venv_path} - '{install_cmd}'' ({cpe})") 759 if cpe.stderr: 760 LOG.debug(f"venv stderr:\n{cpe.stderr.decode('utf8')}") 761 if cpe.output: 762 LOG.debug(f"venv stdout:\n{cpe.output.decode('utf8')}") 763 return None 764 765 runtime = int(time() - start_time) 766 LOG.info(f"Successfully created venv @ {venv_path} to run tests ({runtime}s)") 767 return venv_path 768 769 770 def find_py_files(py_files: Set[str], base_dir: Path) -> None: 771 dirs = [d for d in base_dir.iterdir() if d.is_dir() and not d.name.startswith(".")] 772 py_files.update( 773 {str(x) for x in base_dir.iterdir() if x.is_file() and x.suffix == ".py"} 774 ) 775 for directory in dirs: 776 find_py_files(py_files, directory) 777 778 779 def _recursive_find_files( 780 files: Set[Path], base_dir: Path, exclude_patterns: Set[str], follow_symlinks: bool 781 ) -> None: 782 dirs = [d for d in base_dir.iterdir() if d.is_dir()] 783 files.update( 784 {x for x in base_dir.iterdir() if x.is_file() and x.name == "setup.py"} 785 ) 786 for directory in dirs: 787 if not follow_symlinks and directory.is_symlink(): 788 continue 789 790 skip_dir = False 791 for exclude_pattern in exclude_patterns: 792 if directory.match(exclude_pattern): 793 skip_dir = True 794 LOG.debug( 795 f"Skipping {directory} due to exclude pattern {exclude_pattern}" 796 ) 797 if not skip_dir: 798 _recursive_find_files(files, directory, exclude_patterns, follow_symlinks) 799 800 801 def find_setup_pys( 802 base_path: Path, exclude_patterns: Set[str], follow_symlinks: bool = False 803 ) -> Set[Path]: 804 setup_pys = set() # type: Set[Path] 805 _recursive_find_files(setup_pys, base_path, exclude_patterns, follow_symlinks) 806 return setup_pys 807 808 809 def parse_setup_cfg(setup_py: Path) -> Dict[str, Any]: 810 req_cov_key_strip = "required_coverage_" 811 ptr_params = {} # type: Dict[str, Any] 812 setup_cfg = setup_py.parent / "setup.cfg" 813 if not setup_cfg.exists(): 814 return ptr_params 815 816 cp = ConfigParser() 817 # Have configparser maintain key case - T484 error = callable 818 cp.optionxform = str # type: ignore 819 cp.read(setup_cfg) 820 if "ptr" not in cp: 821 LOG.info("{} does not have a ptr section") 822 return ptr_params 823 824 # Create a setup.py like ptr_params to return 825 ptr_params["required_coverage"] = {} 826 for key, value in cp["ptr"].items(): 827 if key.startswith(req_cov_key_strip): 828 key = key.strip(req_cov_key_strip) 829 ptr_params["required_coverage"][key] = int(value) 830 elif key.startswith("run_") or key == "disabled": 831 ptr_params[key] = cp.getboolean("ptr", key) 832 elif key == "test_suite_timeout": 833 ptr_params[key] = cp.getint("ptr", key) 834 else: 835 ptr_params[key] = value 836 837 return ptr_params 838 839 840 def print_non_configured_modules(modules: List[Path]) -> None: 841 print(f"== {len(modules)} non ptr configured modules ==") 842 for module in sorted(modules): 843 print(f" - {str(module)}") 844 845 846 def print_test_results( 847 test_results: Sequence[test_result], stats: Optional[Dict[str, int]] = None 848 ) -> Dict[str, int]: 849 if not stats: 850 stats = defaultdict(int) 851 852 stats["total.test_suites"] = len(test_results) 853 854 fail_output = "" 855 for result in sorted(test_results): 856 if result.returncode: 857 if result.timeout: 858 stats["total.timeouts"] += 1 859 else: 860 stats["total.fails"] += 1 861 fail_output += "{} (failed '{}' step):\n{}\n".format( 862 result.setup_py_path, StepName(result.returncode).name, result.output 863 ) 864 else: 865 stats["total.passes"] += 1 866 867 total_time = -1 if "runtime.all_tests" not in stats else stats["runtime.all_tests"] 868 print(f"-- Summary (total time {total_time}s):\n") 869 # TODO: Hardcode some workaround to ensure Windows always prints UTF8 870 # https://github.com/facebookincubator/ptr/issues/34 871 print( 872 "✅ PASS: {}\n❌ FAIL: {}\n️⌛ TIMEOUT: {}\n🔒 DISABLED: {}\n💩 TOTAL: {}\n".format( 873 stats["total.passes"], 874 stats["total.fails"], 875 stats["total.timeouts"], 876 stats["total.disabled"], 877 stats["total.test_suites"], 878 ) 879 ) 880 if "total.setup_pys" in stats: 881 stats["pct.setup_py_ptr_enabled"] = int( 882 (stats["total.test_suites"] / stats["total.setup_pys"]) * 100 883 ) 884 print( 885 "-- {} / {} ({}%) `setup.py`'s have `ptr` tests running\n".format( 886 stats["total.test_suites"], 887 stats["total.setup_pys"], 888 stats["pct.setup_py_ptr_enabled"], 889 ) 890 ) 891 if fail_output: 892 print("-- Failure Output --\n") 893 print(fail_output) 894 895 return stats 896 897 898 async def run_tests( 899 atonce: int, 900 mirror: str, 901 tests_to_run: Dict[Path, Dict], 902 progress_interval: Union[float, int], 903 venv_path: Optional[Path], 904 venv_keep: bool, 905 print_cov: bool, 906 stats: Dict[str, int], 907 stats_file: str, 908 venv_timeout: float, 909 error_on_warnings: bool, 910 system_site_packages: bool, 911 ) -> int: 912 tests_start_time = time() 913 914 if not venv_path or not venv_path.exists(): 915 venv_create_start_time = time() 916 venv_path = await create_venv( 917 mirror=mirror, 918 timeout=venv_timeout, 919 system_site_packages=system_site_packages, 920 ) 921 stats["venv_create_time"] = int(time() - venv_create_start_time) 922 else: 923 venv_keep = True 924 if not venv_path or not venv_path.exists(): 925 LOG.error("Unable to make a venv to run tests in. Exiting") 926 return 3 927 928 # Be at the base of the venv to ensure we have a known neutral cwd 929 chdir(str(venv_path)) 930 931 queue: asyncio.Queue = asyncio.Queue() 932 for test_setup_py in sorted(tests_to_run.keys()): 933 await queue.put(test_setup_py) 934 935 test_results = [] # type: List[test_result] 936 consumers = [ 937 _test_runner( 938 queue, 939 tests_to_run, 940 test_results, 941 venv_path, 942 print_cov, 943 stats, 944 error_on_warnings, 945 i + 1, 946 ) 947 for i in range(atonce) 948 ] 949 if progress_interval: 950 LOG.debug(f"Adding progress reporter to report every {progress_interval}s") 951 consumers.append( 952 _progress_reporter(progress_interval, queue, len(tests_to_run)) 953 ) 954 955 LOG.debug("Starting to run tests") 956 await asyncio.gather(*consumers) 957 958 stats["runtime.all_tests"] = int(time() - tests_start_time) 959 stats = print_test_results(test_results, stats) 960 _write_stats_file(stats_file, stats) 961 962 if not venv_keep: 963 chdir(gettempdir()) 964 rmtree(str(venv_path)) 965 else: 966 LOG.info(f"Not removing venv @ {venv_path} due to CLI arguments") 967 968 return stats["total.fails"] + stats["total.timeouts"] 969 970 971 async def async_main( 972 atonce: int, 973 base_path: Path, 974 mirror: str, 975 progress_interval: float, 976 venv: str, 977 venv_keep: bool, 978 print_cov: bool, 979 print_non_configured: bool, 980 run_disabled: bool, 981 stats_file: str, 982 venv_timeout: float, 983 error_on_warnings: bool, 984 system_site_packages: bool, 985 ) -> int: 986 stats = defaultdict(int) # type: Dict[str, int] 987 tests_to_run = _get_test_modules( 988 base_path, stats, run_disabled, print_non_configured 989 ) 990 if not tests_to_run: 991 LOG.error( 992 f"{str(base_path)} has no setup.py files with unit tests defined. Exiting" 993 ) 994 return 1 995 996 if print_non_configured: 997 return 0 998 999 try: 1000 venv_path = Path(venv) # type: Optional[Path] 1001 if venv_path and not venv_path.exists(): 1002 LOG.error(f"{venv_path} venv does not exist. Please correct!") 1003 return 2 1004 except TypeError: 1005 venv_path = None 1006 1007 return await run_tests( 1008 atonce, 1009 mirror, 1010 tests_to_run, 1011 progress_interval, 1012 venv_path, 1013 venv_keep, 1014 print_cov, 1015 stats, 1016 stats_file, 1017 venv_timeout, 1018 error_on_warnings, 1019 system_site_packages, 1020 ) 1021 1022 1023 def main() -> None: 1024 default_stats_file = Path(gettempdir()) / f"ptr_stats_{getpid()}" 1025 parser = argparse.ArgumentParser() 1026 parser.add_argument( 1027 "-a", 1028 "--atonce", 1029 default=int(CONFIG["ptr"]["atonce"]), 1030 type=int, 1031 help=f"How many tests to run at once [Default: {int(CONFIG['ptr']['atonce'])}]", 1032 ) 1033 parser.add_argument( 1034 "-b", 1035 "--base-dir", 1036 default=CWD, 1037 help=f"Path to recursively look for setup.py files [Default: {CWD}]", 1038 ) 1039 parser.add_argument( 1040 "-d", "--debug", action="store_true", help="Verbose debug output" 1041 ) 1042 parser.add_argument( 1043 "-e", 1044 "--error-on-warnings", 1045 action="store_true", 1046 help="Have Python warnings raise DeprecationWarning on tests run", 1047 ) 1048 parser.add_argument( 1049 "-k", "--keep-venv", action="store_true", help="Do not remove created venv" 1050 ) 1051 parser.add_argument( 1052 "-m", 1053 "--mirror", 1054 default=CONFIG["ptr"]["pypi_url"], 1055 help="URL for pip to use for Simple API [Default: {}]".format( 1056 CONFIG["ptr"]["pypi_url"] 1057 ), 1058 ) 1059 parser.add_argument( 1060 "--print-cov", action="store_true", help="Print modules coverage report" 1061 ) 1062 parser.add_argument( 1063 "--print-non-configured", 1064 action="store_true", 1065 help="Print modules not configured to run ptr", 1066 ) 1067 parser.add_argument( 1068 "--progress-interval", 1069 default=0, 1070 type=float, 1071 help="Seconds between status update on test running [Default: Disabled]", 1072 ) 1073 parser.add_argument( 1074 "--run-disabled", 1075 action="store_true", 1076 help="Force any disabled tests suites to run", 1077 ) 1078 parser.add_argument( 1079 "--stats-file", 1080 default=str(default_stats_file), 1081 help=f"JSON statistics file [Default: {default_stats_file}]", 1082 ) 1083 parser.add_argument( 1084 "--system-site-packages", 1085 action="store_true", 1086 help="Give the virtual environment access to the system site-packages dir", 1087 ) 1088 parser.add_argument("--venv", help="Path to venv to reuse") 1089 parser.add_argument( 1090 "--venv-timeout", 1091 type=int, 1092 default=VENV_TIMEOUT, 1093 help=( 1094 "Timeout in seconds for venv creation + deps install [Default:" 1095 f" {VENV_TIMEOUT}]" 1096 ), 1097 ) 1098 args = parser.parse_args() 1099 _handle_debug(args.debug) 1100 1101 LOG.info(f"Starting {sys.argv[0]}") 1102 loop = asyncio.get_event_loop() 1103 try: 1104 sys.exit( 1105 loop.run_until_complete( 1106 async_main( 1107 args.atonce, 1108 _validate_base_dir(args.base_dir), 1109 args.mirror, 1110 args.progress_interval, 1111 args.venv, 1112 args.keep_venv, 1113 args.print_cov, 1114 args.print_non_configured, 1115 args.run_disabled, 1116 args.stats_file, 1117 args.venv_timeout, 1118 args.error_on_warnings, 1119 args.system_site_packages, 1120 ) 1121 ) 1122 ) 1123 finally: 1124 loop.close() 1125 1126 1127 if __name__ == "__main__": 1128 main() # pragma: no cover 1129 [end of ptr.py] [start of setup.cfg.sample] 1 [ptr] 2 entry_point_module = ptr 3 test_suite = ptr_tests 4 test_suite_timeout = 120 5 # `required_coverage_` will be stripped for use 6 required_coverage_ptr.py = 85.0 7 required_coverage_TOTAL = 90 8 run_black = true 9 run_mypy = true 10 run_flake8 = true 11 run_pylint = false 12 run_pyre = true 13 [end of setup.cfg.sample] [start of setup.py] 1 #!/usr/bin/env python3 2 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved 3 # coding=utf8 4 # pyre-ignore-all-errors 5 6 # This source code is licensed under the MIT license found in the 7 # LICENSE file in the root directory of this source tree. 8 9 from pathlib import Path 10 from setuptools import setup 11 12 13 # Specific Python Test Runner (ptr) params for Unit Testing Enforcement 14 ptr_params = { 15 # Disable auto running if found - Requires --run-disabled to run 16 "disabled": True, 17 # Where mypy will run to type check your program 18 "entry_point_module": "ptr", 19 # Base Unittest File 20 "test_suite": "ptr_tests", 21 "test_suite_timeout": 120, 22 # Relative path from setup.py to module (e.g. ptr == ptr.py) 23 "required_coverage": {"ptr.py": 85.0, "TOTAL": 90}, 24 # Run black or not 25 "run_black": True, 26 # Run mypy or not 27 "run_mypy": True, 28 # Run flake8 or not 29 "run_flake8": True, 30 # Run pylint or not - Disabled until 3.9 Support 31 "run_pylint": False, 32 # Run pyre or not 33 "run_pyre": True, 34 } 35 36 37 def get_long_desc() -> str: 38 repo_base = Path(__file__).parent 39 long_desc = "" 40 for info_file in (repo_base / "README.md", repo_base / "CHANGES.md"): 41 with info_file.open("r", encoding="utf8") as ifp: 42 long_desc += ifp.read() 43 long_desc += "\n\n" 44 45 return long_desc 46 47 48 setup( 49 name=ptr_params["entry_point_module"], 50 version="20.2.26", 51 description="Parallel asyncio Python setup.(cfg|py) Test Runner", 52 long_description=get_long_desc(), 53 long_description_content_type="text/markdown", 54 py_modules=["ptr"], 55 url="http://github.com/facebookincubator/ptr", 56 author="Cooper Lees", 57 author_email="[email protected]", 58 license="MIT", 59 classifiers=[ 60 "Development Status :: 3 - Alpha", 61 "License :: OSI Approved :: MIT License", 62 "Programming Language :: Python :: 3", 63 "Programming Language :: Python :: 3 :: Only", 64 "Programming Language :: Python :: 3.6", 65 "Programming Language :: Python :: 3.7", 66 "Programming Language :: Python :: 3.8", 67 "Programming Language :: Python :: 3.9", 68 ], 69 python_requires=">=3.6", 70 install_requires=None, 71 entry_points={"console_scripts": ["ptr = ptr:main"]}, 72 test_suite=ptr_params["test_suite"], 73 ) 74 [end of setup.py] </code> I need you to solve this issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the following format. <patch> --- a/file.py +++ b/file.py @@ -1,27 +1,35 @@ def euclidean(a, b): - while b: - a, b = b, a % b - return a + if b == 0: + return a + return euclidean(b, a % b) def bresenham(x0, y0, x1, y1): points = [] dx = abs(x1 - x0) dy = abs(y1 - y0) - sx = 1 if x0 < x1 else -1 - sy = 1 if y0 < y1 else -1 - err = dx - dy + x, y = x0, y0 + sx = -1 if x0 > x1 else 1 + sy = -1 if y0 > y1 else 1 - while True: - points.append((x0, y0)) - if x0 == x1 and y0 == y1: - break - e2 = 2 * err - if e2 > -dy: + if dx > dy: + err = dx / 2.0 + while x != x1: + points.append((x, y)) err -= dy - x0 += sx - if e2 < dx: - err += dx - y0 += sy + if err < 0: + y += sy + err += dx + x += sx + else: + err = dy / 2.0 + while y != y1: + points.append((x, y)) + err -= dx + if err < 0: + x += sx + err += dy + y += sy + points.append((x, y)) return points </patch>
facebookincubator/ptr
3d45beed42f35134b0431dca32c3c24c886ced58
If no `required_coverage` set in setup.* files `--print-cov` does not print coverage ## How is `ptr` not doing what you expect? Expected `--print-cov` to show me the coverage even if the setup.* files do no have ``. ## What is your suggestion to make this better? Fix the code to print coverage if the argument is true ## Code/Bug example? If we have no `required_coverage` `--print-cov` is not taken into account. ```python ptr_params = { "entry_point_module": "ansible_shed/main", "test_suite": "ansible_shed.tests.base", "test_suite_timeout": 300, # "required_coverage": { # "aioexabgp/announcer/__init__.py": 50, # }, "run_flake8": True, "run_black": True, "run_mypy": True, } ``` ## How can a developer reproduce this? Comment out `required_coverage` and try getting coverage to print.
2021-03-16 05:42:50+00:00
<patch> diff --git a/ptr.py b/ptr.py index 94aa657..bc53ca2 100755 --- a/ptr.py +++ b/ptr.py @@ -557,9 +557,12 @@ async def _test_steps_runner( # pylint: disable=R0914 step( StepName.analyze_coverage, bool( - "required_coverage" in config - and config["required_coverage"] - and len(config["required_coverage"]) > 0 + print_cov + or ( + "required_coverage" in config + and config["required_coverage"] + and len(config["required_coverage"]) > 0 + ) ), (str(coverage_exe), "report", "-m"), f"Analyzing coverage report for {setup_py_path}", @@ -657,6 +660,9 @@ async def _test_steps_runner( # pylint: disable=R0914 cov_report = stdout.decode("utf8") if stdout else "" if print_cov: print(f"{setup_py_path}:\n{cov_report}") + if "required_coverage" not in config: + # Add fake 0% TOTAL coverage required so step passes + config["required_coverage"] = {"TOTAL": 0} if a_step.run_condition: a_test_result = _analyze_coverage( @@ -667,6 +673,7 @@ async def _test_steps_runner( # pylint: disable=R0914 stats, test_run_start_time, ) + # If we've had a failure return if a_test_result: return a_test_result, steps_ran diff --git a/setup.cfg.sample b/setup.cfg.sample index 9909ef0..ae8ec67 100644 --- a/setup.cfg.sample +++ b/setup.cfg.sample @@ -4,7 +4,7 @@ test_suite = ptr_tests test_suite_timeout = 120 # `required_coverage_` will be stripped for use required_coverage_ptr.py = 85.0 -required_coverage_TOTAL = 90 +required_coverage_TOTAL = 89 run_black = true run_mypy = true run_flake8 = true diff --git a/setup.py b/setup.py index 1655dcb..60ec59e 100644 --- a/setup.py +++ b/setup.py @@ -20,7 +20,7 @@ ptr_params = { "test_suite": "ptr_tests", "test_suite_timeout": 120, # Relative path from setup.py to module (e.g. ptr == ptr.py) - "required_coverage": {"ptr.py": 85.0, "TOTAL": 90}, + "required_coverage": {"ptr.py": 85.0, "TOTAL": 89}, # Run black or not "run_black": True, # Run mypy or not </patch>
diff --git a/ptr_tests.py b/ptr_tests.py index e6e24f2..cfd25d0 100644 --- a/ptr_tests.py +++ b/ptr_tests.py @@ -521,15 +521,28 @@ class TestPtr(unittest.TestCase): (None, 6) if no_pyre else (None, 7), ) - # Run everything but black + no print cov + # Test we run coverage when required_coverage does not exist + # but we have print_cov True etp = deepcopy(ptr_tests_fixtures.EXPECTED_TEST_PARAMS) - del etp["run_black"] + del etp["required_coverage"] tsr_params[1] = {fake_setup_py: etp} - tsr_params[7] = False + tsr_params[7] = True self.assertEqual( self.loop.run_until_complete( ptr._test_steps_runner(*tsr_params) # pyre-ignore ), + (None, 6) if no_pyre else (None, 7), + ) + + return None # COOPER + + # Run everything but black + no print cov + etp = deepcopy(ptr_tests_fixtures.EXPECTED_TEST_PARAMS) + del etp["run_black"] + tsr_params[1] = {fake_setup_py: etp} + tsr_params[7] = False + self.assertEqual( + self.loop.run_until_complete(ptr._test_steps_runner(*tsr_params)), (None, 5) if no_pyre else (None, 6), ) @@ -541,9 +554,7 @@ class TestPtr(unittest.TestCase): tsr_params[1] = {fake_setup_py: etp} tsr_params[7] = True self.assertEqual( - self.loop.run_until_complete( - ptr._test_steps_runner(*tsr_params) # pyre-ignore - ), + self.loop.run_until_complete(ptr._test_steps_runner(*tsr_params)), expected_no_pyre_tests, ) diff --git a/ptr_tests_fixtures.py b/ptr_tests_fixtures.py index cb6f344..30d2f8c 100644 --- a/ptr_tests_fixtures.py +++ b/ptr_tests_fixtures.py @@ -30,7 +30,7 @@ EXPECTED_TEST_PARAMS = { "entry_point_module": "ptr", "test_suite": "ptr_tests", "test_suite_timeout": 120, - "required_coverage": {"ptr.py": 85, "TOTAL": 90}, + "required_coverage": {"ptr.py": 85, "TOTAL": 89}, "run_black": True, "run_mypy": True, "run_flake8": True, @@ -218,7 +218,7 @@ entry_point_module = ptr test_suite = ptr_tests test_suite_timeout = 120 required_coverage_ptr.py = 85 -required_coverage_TOTAL = 90 +required_coverage_TOTAL = 89 run_black = true run_mypy = true run_flake8 = true
0.0
[ "ptr_tests.py::TestPtr::test_get_test_modules", "ptr_tests.py::TestPtr::test_test_steps_runner" ]
[ "ptr_tests.py::TestPtr::test_analyze_coverage", "ptr_tests.py::TestPtr::test_analyze_coverage_errors", "ptr_tests.py::TestPtr::test_async_main", "ptr_tests.py::TestPtr::test_config", "ptr_tests.py::TestPtr::test_create_venv", "ptr_tests.py::TestPtr::test_create_venv_site_packages", "ptr_tests.py::TestPtr::test_find_setup_py", "ptr_tests.py::TestPtr::test_find_setup_py_exclude_default", "ptr_tests.py::TestPtr::test_gen_output", "ptr_tests.py::TestPtr::test_generate_black_command", "ptr_tests.py::TestPtr::test_generate_flake8_command", "ptr_tests.py::TestPtr::test_generate_install_cmd", "ptr_tests.py::TestPtr::test_generate_mypy_cmd", "ptr_tests.py::TestPtr::test_generate_pylint_command", "ptr_tests.py::TestPtr::test_generate_pyre_cmd", "ptr_tests.py::TestPtr::test_generate_test_suite_cmd", "ptr_tests.py::TestPtr::test_get_site_packages_path_error", "ptr_tests.py::TestPtr::test_handle_debug", "ptr_tests.py::TestPtr::test_mac_osx_slash_private", "ptr_tests.py::TestPtr::test_main", "ptr_tests.py::TestPtr::test_parse_setup_cfg", "ptr_tests.py::TestPtr::test_print_non_configured_modules", "ptr_tests.py::TestPtr::test_print_test_results", "ptr_tests.py::TestPtr::test_process_reporter", "ptr_tests.py::TestPtr::test_set_build_env", "ptr_tests.py::TestPtr::test_set_pip_mirror", "ptr_tests.py::TestPtr::test_test_runner", "ptr_tests.py::TestPtr::test_validate_base_dir", "ptr_tests.py::TestPtr::test_validate_base_dir_fail", "ptr_tests.py::TestPtr::test_write_stats_file" ]
3d45beed42f35134b0431dca32c3c24c886ced58
pydantic__pydantic-3452
You will be provided with a partial code base and an issue statement explaining a problem to resolve. <issue> "none is not an allowed value" when using Union with Any ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug # Bug It seems that `None` is allowed when a field's type is `Any` (as is expected, stated in the docs), but `None` is not allowed when a field's type is `Union[SomeType, Any]`. Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8.2 pydantic compiled: True install path: C:\Users\TobyHarradine\PycharmProjects\orchestration\.venv\Lib\site-packages\pydantic python version: 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] platform: Windows-10-10.0.19041-SP0 optional deps. installed: ['typing-extensions'] ``` Code which reproduces the issue: ```pycon >>> import pydantic >>> class M(pydantic.BaseModel): ... a: Any ... >>> M(a=1) M(a=1) >>> M(a=None) M(a=None) >>> class M(pydantic.BaseModel): ... a: Union[int, Any] ... >>> M(a=1) M(a=1) >>> M(a="abcd") M(a='abcd') >>> M(a=None) Traceback (most recent call last): File "<input>", line 1, in <module> File "pydantic\main.py", line 406, in pydantic.main.BaseModel.__init__ pydantic.error_wrappers.ValidationError: 1 validation error for M a none is not an allowed value (type=type_error.none.not_allowed) ``` This may be somewhat related to #1624. </issue> <code> [start of README.md] 1 # pydantic 2 3 [![CI](https://github.com/samuelcolvin/pydantic/workflows/CI/badge.svg?event=push)](https://github.com/samuelcolvin/pydantic/actions?query=event%3Apush+branch%3Amaster+workflow%3ACI) 4 [![Coverage](https://coverage-badge.samuelcolvin.workers.dev/samuelcolvin/pydantic.svg?v=1)](https://coverage-badge.samuelcolvin.workers.dev/redirect/samuelcolvin/pydantic) 5 [![pypi](https://img.shields.io/pypi/v/pydantic.svg)](https://pypi.python.org/pypi/pydantic) 6 [![CondaForge](https://img.shields.io/conda/v/conda-forge/pydantic.svg)](https://anaconda.org/conda-forge/pydantic) 7 [![downloads](https://pepy.tech/badge/pydantic/month)](https://pepy.tech/project/pydantic) 8 [![versions](https://img.shields.io/pypi/pyversions/pydantic.svg)](https://github.com/samuelcolvin/pydantic) 9 [![license](https://img.shields.io/github/license/samuelcolvin/pydantic.svg)](https://github.com/samuelcolvin/pydantic/blob/master/LICENSE) 10 11 Data validation and settings management using Python type hinting. 12 13 Fast and extensible, *pydantic* plays nicely with your linters/IDE/brain. 14 Define how data should be in pure, canonical Python 3.6+; validate it with *pydantic*. 15 16 ## Help 17 18 See [documentation](https://pydantic-docs.helpmanual.io/) for more details. 19 20 ## Installation 21 22 Install using `pip install -U pydantic` or `conda install pydantic -c conda-forge`. 23 For more installation options to make *pydantic* even faster, 24 see the [Install](https://pydantic-docs.helpmanual.io/install/) section in the documentation. 25 26 ## A Simple Example 27 28 ```py 29 from datetime import datetime 30 from typing import List, Optional 31 from pydantic import BaseModel 32 33 class User(BaseModel): 34 id: int 35 name = 'John Doe' 36 signup_ts: Optional[datetime] = None 37 friends: List[int] = [] 38 39 external_data = {'id': '123', 'signup_ts': '2017-06-01 12:22', 'friends': [1, '2', b'3']} 40 user = User(**external_data) 41 print(user) 42 #> User id=123 name='John Doe' signup_ts=datetime.datetime(2017, 6, 1, 12, 22) friends=[1, 2, 3] 43 print(user.id) 44 #> 123 45 ``` 46 47 ## Contributing 48 49 For guidance on setting up a development environment and how to make a 50 contribution to *pydantic*, see 51 [Contributing to Pydantic](https://pydantic-docs.helpmanual.io/contributing/). 52 53 ## Reporting a Security Vulnerability 54 55 See our [security policy](https://github.com/samuelcolvin/pydantic/security/policy). 56 [end of README.md] [start of pydantic/fields.py] 1 from collections import Counter as CollectionCounter, defaultdict, deque 2 from collections.abc import Hashable as CollectionsHashable, Iterable as CollectionsIterable 3 from typing import ( 4 TYPE_CHECKING, 5 Any, 6 Counter, 7 DefaultDict, 8 Deque, 9 Dict, 10 FrozenSet, 11 Generator, 12 Iterable, 13 Iterator, 14 List, 15 Mapping, 16 Optional, 17 Pattern, 18 Sequence, 19 Set, 20 Tuple, 21 Type, 22 TypeVar, 23 Union, 24 ) 25 26 from typing_extensions import Annotated 27 28 from . import errors as errors_ 29 from .class_validators import Validator, make_generic_validator, prep_validators 30 from .error_wrappers import ErrorWrapper 31 from .errors import ConfigError, NoneIsNotAllowedError 32 from .types import Json, JsonWrapper 33 from .typing import ( 34 Callable, 35 ForwardRef, 36 NoArgAnyCallable, 37 NoneType, 38 display_as_type, 39 get_args, 40 get_origin, 41 is_literal_type, 42 is_new_type, 43 is_none_type, 44 is_typeddict, 45 is_union, 46 new_type_supertype, 47 ) 48 from .utils import PyObjectStr, Representation, ValueItems, lenient_issubclass, sequence_like, smart_deepcopy 49 from .validators import constant_validator, dict_validator, find_validators, validate_json 50 51 Required: Any = Ellipsis 52 53 T = TypeVar('T') 54 55 56 class UndefinedType: 57 def __repr__(self) -> str: 58 return 'PydanticUndefined' 59 60 def __copy__(self: T) -> T: 61 return self 62 63 def __reduce__(self) -> str: 64 return 'Undefined' 65 66 def __deepcopy__(self: T, _: Any) -> T: 67 return self 68 69 70 Undefined = UndefinedType() 71 72 if TYPE_CHECKING: 73 from .class_validators import ValidatorsList 74 from .config import BaseConfig 75 from .error_wrappers import ErrorList 76 from .types import ModelOrDc 77 from .typing import AbstractSetIntStr, MappingIntStrAny, ReprArgs 78 79 ValidateReturn = Tuple[Optional[Any], Optional[ErrorList]] 80 LocStr = Union[Tuple[Union[int, str], ...], str] 81 BoolUndefined = Union[bool, UndefinedType] 82 83 84 class FieldInfo(Representation): 85 """ 86 Captures extra information about a field. 87 """ 88 89 __slots__ = ( 90 'default', 91 'default_factory', 92 'alias', 93 'alias_priority', 94 'title', 95 'description', 96 'exclude', 97 'include', 98 'const', 99 'gt', 100 'ge', 101 'lt', 102 'le', 103 'multiple_of', 104 'min_items', 105 'max_items', 106 'min_length', 107 'max_length', 108 'allow_mutation', 109 'repr', 110 'regex', 111 'extra', 112 ) 113 114 # field constraints with the default value, it's also used in update_from_config below 115 __field_constraints__ = { 116 'min_length': None, 117 'max_length': None, 118 'regex': None, 119 'gt': None, 120 'lt': None, 121 'ge': None, 122 'le': None, 123 'multiple_of': None, 124 'min_items': None, 125 'max_items': None, 126 'allow_mutation': True, 127 } 128 129 def __init__(self, default: Any = Undefined, **kwargs: Any) -> None: 130 self.default = default 131 self.default_factory = kwargs.pop('default_factory', None) 132 self.alias = kwargs.pop('alias', None) 133 self.alias_priority = kwargs.pop('alias_priority', 2 if self.alias else None) 134 self.title = kwargs.pop('title', None) 135 self.description = kwargs.pop('description', None) 136 self.exclude = kwargs.pop('exclude', None) 137 self.include = kwargs.pop('include', None) 138 self.const = kwargs.pop('const', None) 139 self.gt = kwargs.pop('gt', None) 140 self.ge = kwargs.pop('ge', None) 141 self.lt = kwargs.pop('lt', None) 142 self.le = kwargs.pop('le', None) 143 self.multiple_of = kwargs.pop('multiple_of', None) 144 self.min_items = kwargs.pop('min_items', None) 145 self.max_items = kwargs.pop('max_items', None) 146 self.min_length = kwargs.pop('min_length', None) 147 self.max_length = kwargs.pop('max_length', None) 148 self.allow_mutation = kwargs.pop('allow_mutation', True) 149 self.regex = kwargs.pop('regex', None) 150 self.repr = kwargs.pop('repr', True) 151 self.extra = kwargs 152 153 def __repr_args__(self) -> 'ReprArgs': 154 155 field_defaults_to_hide: Dict[str, Any] = { 156 'repr': True, 157 **self.__field_constraints__, 158 } 159 160 attrs = ((s, getattr(self, s)) for s in self.__slots__) 161 return [(a, v) for a, v in attrs if v != field_defaults_to_hide.get(a, None)] 162 163 def get_constraints(self) -> Set[str]: 164 """ 165 Gets the constraints set on the field by comparing the constraint value with its default value 166 167 :return: the constraints set on field_info 168 """ 169 return {attr for attr, default in self.__field_constraints__.items() if getattr(self, attr) != default} 170 171 def update_from_config(self, from_config: Dict[str, Any]) -> None: 172 """ 173 Update this FieldInfo based on a dict from get_field_info, only fields which have not been set are dated. 174 """ 175 for attr_name, value in from_config.items(): 176 try: 177 current_value = getattr(self, attr_name) 178 except AttributeError: 179 # attr_name is not an attribute of FieldInfo, it should therefore be added to extra 180 self.extra[attr_name] = value 181 else: 182 if current_value is self.__field_constraints__.get(attr_name, None): 183 setattr(self, attr_name, value) 184 elif attr_name == 'exclude': 185 self.exclude = ValueItems.merge(value, current_value) 186 elif attr_name == 'include': 187 self.include = ValueItems.merge(value, current_value, intersect=True) 188 189 def _validate(self) -> None: 190 if self.default is not Undefined and self.default_factory is not None: 191 raise ValueError('cannot specify both default and default_factory') 192 193 194 def Field( 195 default: Any = Undefined, 196 *, 197 default_factory: Optional[NoArgAnyCallable] = None, 198 alias: str = None, 199 title: str = None, 200 description: str = None, 201 exclude: Union['AbstractSetIntStr', 'MappingIntStrAny', Any] = None, 202 include: Union['AbstractSetIntStr', 'MappingIntStrAny', Any] = None, 203 const: bool = None, 204 gt: float = None, 205 ge: float = None, 206 lt: float = None, 207 le: float = None, 208 multiple_of: float = None, 209 min_items: int = None, 210 max_items: int = None, 211 min_length: int = None, 212 max_length: int = None, 213 allow_mutation: bool = True, 214 regex: str = None, 215 repr: bool = True, 216 **extra: Any, 217 ) -> Any: 218 """ 219 Used to provide extra information about a field, either for the model schema or complex validation. Some arguments 220 apply only to number fields (``int``, ``float``, ``Decimal``) and some apply only to ``str``. 221 222 :param default: since this is replacing the field’s default, its first argument is used 223 to set the default, use ellipsis (``...``) to indicate the field is required 224 :param default_factory: callable that will be called when a default value is needed for this field 225 If both `default` and `default_factory` are set, an error is raised. 226 :param alias: the public name of the field 227 :param title: can be any string, used in the schema 228 :param description: can be any string, used in the schema 229 :param exclude: exclude this field while dumping. 230 Takes same values as the ``include`` and ``exclude`` arguments on the ``.dict`` method. 231 :param include: include this field while dumping. 232 Takes same values as the ``include`` and ``exclude`` arguments on the ``.dict`` method. 233 :param const: this field is required and *must* take it's default value 234 :param gt: only applies to numbers, requires the field to be "greater than". The schema 235 will have an ``exclusiveMinimum`` validation keyword 236 :param ge: only applies to numbers, requires the field to be "greater than or equal to". The 237 schema will have a ``minimum`` validation keyword 238 :param lt: only applies to numbers, requires the field to be "less than". The schema 239 will have an ``exclusiveMaximum`` validation keyword 240 :param le: only applies to numbers, requires the field to be "less than or equal to". The 241 schema will have a ``maximum`` validation keyword 242 :param multiple_of: only applies to numbers, requires the field to be "a multiple of". The 243 schema will have a ``multipleOf`` validation keyword 244 :param min_length: only applies to strings, requires the field to have a minimum length. The 245 schema will have a ``maximum`` validation keyword 246 :param max_length: only applies to strings, requires the field to have a maximum length. The 247 schema will have a ``maxLength`` validation keyword 248 :param allow_mutation: a boolean which defaults to True. When False, the field raises a TypeError if the field is 249 assigned on an instance. The BaseModel Config must set validate_assignment to True 250 :param regex: only applies to strings, requires the field match against a regular expression 251 pattern string. The schema will have a ``pattern`` validation keyword 252 :param repr: show this field in the representation 253 :param **extra: any additional keyword arguments will be added as is to the schema 254 """ 255 field_info = FieldInfo( 256 default, 257 default_factory=default_factory, 258 alias=alias, 259 title=title, 260 description=description, 261 exclude=exclude, 262 include=include, 263 const=const, 264 gt=gt, 265 ge=ge, 266 lt=lt, 267 le=le, 268 multiple_of=multiple_of, 269 min_items=min_items, 270 max_items=max_items, 271 min_length=min_length, 272 max_length=max_length, 273 allow_mutation=allow_mutation, 274 regex=regex, 275 repr=repr, 276 **extra, 277 ) 278 field_info._validate() 279 return field_info 280 281 282 # used to be an enum but changed to int's for small performance improvement as less access overhead 283 SHAPE_SINGLETON = 1 284 SHAPE_LIST = 2 285 SHAPE_SET = 3 286 SHAPE_MAPPING = 4 287 SHAPE_TUPLE = 5 288 SHAPE_TUPLE_ELLIPSIS = 6 289 SHAPE_SEQUENCE = 7 290 SHAPE_FROZENSET = 8 291 SHAPE_ITERABLE = 9 292 SHAPE_GENERIC = 10 293 SHAPE_DEQUE = 11 294 SHAPE_DICT = 12 295 SHAPE_DEFAULTDICT = 13 296 SHAPE_COUNTER = 14 297 SHAPE_NAME_LOOKUP = { 298 SHAPE_LIST: 'List[{}]', 299 SHAPE_SET: 'Set[{}]', 300 SHAPE_TUPLE_ELLIPSIS: 'Tuple[{}, ...]', 301 SHAPE_SEQUENCE: 'Sequence[{}]', 302 SHAPE_FROZENSET: 'FrozenSet[{}]', 303 SHAPE_ITERABLE: 'Iterable[{}]', 304 SHAPE_DEQUE: 'Deque[{}]', 305 SHAPE_DICT: 'Dict[{}]', 306 SHAPE_DEFAULTDICT: 'DefaultDict[{}]', 307 SHAPE_COUNTER: 'Counter[{}]', 308 } 309 310 MAPPING_LIKE_SHAPES: Set[int] = {SHAPE_DEFAULTDICT, SHAPE_DICT, SHAPE_MAPPING, SHAPE_COUNTER} 311 312 313 class ModelField(Representation): 314 __slots__ = ( 315 'type_', 316 'outer_type_', 317 'sub_fields', 318 'key_field', 319 'validators', 320 'pre_validators', 321 'post_validators', 322 'default', 323 'default_factory', 324 'required', 325 'model_config', 326 'name', 327 'alias', 328 'has_alias', 329 'field_info', 330 'validate_always', 331 'allow_none', 332 'shape', 333 'class_validators', 334 'parse_json', 335 ) 336 337 def __init__( 338 self, 339 *, 340 name: str, 341 type_: Type[Any], 342 class_validators: Optional[Dict[str, Validator]], 343 model_config: Type['BaseConfig'], 344 default: Any = None, 345 default_factory: Optional[NoArgAnyCallable] = None, 346 required: 'BoolUndefined' = Undefined, 347 alias: str = None, 348 field_info: Optional[FieldInfo] = None, 349 ) -> None: 350 351 self.name: str = name 352 self.has_alias: bool = bool(alias) 353 self.alias: str = alias or name 354 self.type_: Any = type_ 355 self.outer_type_: Any = type_ 356 self.class_validators = class_validators or {} 357 self.default: Any = default 358 self.default_factory: Optional[NoArgAnyCallable] = default_factory 359 self.required: 'BoolUndefined' = required 360 self.model_config = model_config 361 self.field_info: FieldInfo = field_info or FieldInfo(default) 362 363 self.allow_none: bool = False 364 self.validate_always: bool = False 365 self.sub_fields: Optional[List[ModelField]] = None 366 self.key_field: Optional[ModelField] = None 367 self.validators: 'ValidatorsList' = [] 368 self.pre_validators: Optional['ValidatorsList'] = None 369 self.post_validators: Optional['ValidatorsList'] = None 370 self.parse_json: bool = False 371 self.shape: int = SHAPE_SINGLETON 372 self.model_config.prepare_field(self) 373 self.prepare() 374 375 def get_default(self) -> Any: 376 return smart_deepcopy(self.default) if self.default_factory is None else self.default_factory() 377 378 @staticmethod 379 def _get_field_info( 380 field_name: str, annotation: Any, value: Any, config: Type['BaseConfig'] 381 ) -> Tuple[FieldInfo, Any]: 382 """ 383 Get a FieldInfo from a root typing.Annotated annotation, value, or config default. 384 385 The FieldInfo may be set in typing.Annotated or the value, but not both. If neither contain 386 a FieldInfo, a new one will be created using the config. 387 388 :param field_name: name of the field for use in error messages 389 :param annotation: a type hint such as `str` or `Annotated[str, Field(..., min_length=5)]` 390 :param value: the field's assigned value 391 :param config: the model's config object 392 :return: the FieldInfo contained in the `annotation`, the value, or a new one from the config. 393 """ 394 field_info_from_config = config.get_field_info(field_name) 395 396 field_info = None 397 if get_origin(annotation) is Annotated: 398 field_infos = [arg for arg in get_args(annotation)[1:] if isinstance(arg, FieldInfo)] 399 if len(field_infos) > 1: 400 raise ValueError(f'cannot specify multiple `Annotated` `Field`s for {field_name!r}') 401 field_info = next(iter(field_infos), None) 402 if field_info is not None: 403 field_info.update_from_config(field_info_from_config) 404 if field_info.default is not Undefined: 405 raise ValueError(f'`Field` default cannot be set in `Annotated` for {field_name!r}') 406 if value is not Undefined and value is not Required: 407 # check also `Required` because of `validate_arguments` that sets `...` as default value 408 field_info.default = value 409 410 if isinstance(value, FieldInfo): 411 if field_info is not None: 412 raise ValueError(f'cannot specify `Annotated` and value `Field`s together for {field_name!r}') 413 field_info = value 414 field_info.update_from_config(field_info_from_config) 415 elif field_info is None: 416 field_info = FieldInfo(value, **field_info_from_config) 417 value = None if field_info.default_factory is not None else field_info.default 418 field_info._validate() 419 return field_info, value 420 421 @classmethod 422 def infer( 423 cls, 424 *, 425 name: str, 426 value: Any, 427 annotation: Any, 428 class_validators: Optional[Dict[str, Validator]], 429 config: Type['BaseConfig'], 430 ) -> 'ModelField': 431 from .schema import get_annotation_from_field_info 432 433 field_info, value = cls._get_field_info(name, annotation, value, config) 434 required: 'BoolUndefined' = Undefined 435 if value is Required: 436 required = True 437 value = None 438 elif value is not Undefined: 439 required = False 440 annotation = get_annotation_from_field_info(annotation, field_info, name, config.validate_assignment) 441 442 return cls( 443 name=name, 444 type_=annotation, 445 alias=field_info.alias, 446 class_validators=class_validators, 447 default=value, 448 default_factory=field_info.default_factory, 449 required=required, 450 model_config=config, 451 field_info=field_info, 452 ) 453 454 def set_config(self, config: Type['BaseConfig']) -> None: 455 self.model_config = config 456 info_from_config = config.get_field_info(self.name) 457 config.prepare_field(self) 458 new_alias = info_from_config.get('alias') 459 new_alias_priority = info_from_config.get('alias_priority') or 0 460 if new_alias and new_alias_priority >= (self.field_info.alias_priority or 0): 461 self.field_info.alias = new_alias 462 self.field_info.alias_priority = new_alias_priority 463 self.alias = new_alias 464 new_exclude = info_from_config.get('exclude') 465 if new_exclude is not None: 466 self.field_info.exclude = ValueItems.merge(self.field_info.exclude, new_exclude) 467 new_include = info_from_config.get('include') 468 if new_include is not None: 469 self.field_info.include = ValueItems.merge(self.field_info.include, new_include, intersect=True) 470 471 @property 472 def alt_alias(self) -> bool: 473 return self.name != self.alias 474 475 def prepare(self) -> None: 476 """ 477 Prepare the field but inspecting self.default, self.type_ etc. 478 479 Note: this method is **not** idempotent (because _type_analysis is not idempotent), 480 e.g. calling it it multiple times may modify the field and configure it incorrectly. 481 """ 482 self._set_default_and_type() 483 if self.type_.__class__ is ForwardRef or self.type_.__class__ is DeferredType: 484 # self.type_ is currently a ForwardRef and there's nothing we can do now, 485 # user will need to call model.update_forward_refs() 486 return 487 488 self._type_analysis() 489 if self.required is Undefined: 490 self.required = True 491 if self.default is Undefined and self.default_factory is None: 492 self.default = None 493 self.populate_validators() 494 495 def _set_default_and_type(self) -> None: 496 """ 497 Set the default value, infer the type if needed and check if `None` value is valid. 498 """ 499 if self.default_factory is not None: 500 if self.type_ is Undefined: 501 raise errors_.ConfigError( 502 f'you need to set the type of field {self.name!r} when using `default_factory`' 503 ) 504 return 505 506 default_value = self.get_default() 507 508 if default_value is not None and self.type_ is Undefined: 509 self.type_ = default_value.__class__ 510 self.outer_type_ = self.type_ 511 512 if self.type_ is Undefined: 513 raise errors_.ConfigError(f'unable to infer type for attribute "{self.name}"') 514 515 if self.required is False and default_value is None: 516 self.allow_none = True 517 518 def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) 519 # typing interface is horrible, we have to do some ugly checks 520 if lenient_issubclass(self.type_, JsonWrapper): 521 self.type_ = self.type_.inner_type 522 self.parse_json = True 523 elif lenient_issubclass(self.type_, Json): 524 self.type_ = Any 525 self.parse_json = True 526 elif isinstance(self.type_, TypeVar): 527 if self.type_.__bound__: 528 self.type_ = self.type_.__bound__ 529 elif self.type_.__constraints__: 530 self.type_ = Union[self.type_.__constraints__] 531 else: 532 self.type_ = Any 533 elif is_new_type(self.type_): 534 self.type_ = new_type_supertype(self.type_) 535 536 if self.type_ is Any or self.type_ is object: 537 if self.required is Undefined: 538 self.required = False 539 self.allow_none = True 540 return 541 elif self.type_ is Pattern: 542 # python 3.7 only, Pattern is a typing object but without sub fields 543 return 544 elif is_literal_type(self.type_): 545 return 546 elif is_typeddict(self.type_): 547 return 548 549 origin = get_origin(self.type_) 550 # add extra check for `collections.abc.Hashable` for python 3.10+ where origin is not `None` 551 if origin is None or origin is CollectionsHashable: 552 # field is not "typing" object eg. Union, Dict, List etc. 553 # allow None for virtual superclasses of NoneType, e.g. Hashable 554 if isinstance(self.type_, type) and isinstance(None, self.type_): 555 self.allow_none = True 556 return 557 if origin is Annotated: 558 self.type_ = get_args(self.type_)[0] 559 self._type_analysis() 560 return 561 if origin is Callable: 562 return 563 if is_union(origin): 564 types_ = [] 565 for type_ in get_args(self.type_): 566 if type_ is NoneType: 567 if self.required is Undefined: 568 self.required = False 569 self.allow_none = True 570 continue 571 types_.append(type_) 572 573 if len(types_) == 1: 574 # Optional[] 575 self.type_ = types_[0] 576 # this is the one case where the "outer type" isn't just the original type 577 self.outer_type_ = self.type_ 578 # re-run to correctly interpret the new self.type_ 579 self._type_analysis() 580 else: 581 self.sub_fields = [self._create_sub_type(t, f'{self.name}_{display_as_type(t)}') for t in types_] 582 return 583 584 if issubclass(origin, Tuple): # type: ignore 585 # origin == Tuple without item type 586 args = get_args(self.type_) 587 if not args: # plain tuple 588 self.type_ = Any 589 self.shape = SHAPE_TUPLE_ELLIPSIS 590 elif len(args) == 2 and args[1] is Ellipsis: # e.g. Tuple[int, ...] 591 self.type_ = args[0] 592 self.shape = SHAPE_TUPLE_ELLIPSIS 593 self.sub_fields = [self._create_sub_type(args[0], f'{self.name}_0')] 594 elif args == ((),): # Tuple[()] means empty tuple 595 self.shape = SHAPE_TUPLE 596 self.type_ = Any 597 self.sub_fields = [] 598 else: 599 self.shape = SHAPE_TUPLE 600 self.sub_fields = [self._create_sub_type(t, f'{self.name}_{i}') for i, t in enumerate(args)] 601 return 602 603 if issubclass(origin, List): 604 # Create self validators 605 get_validators = getattr(self.type_, '__get_validators__', None) 606 if get_validators: 607 self.class_validators.update( 608 {f'list_{i}': Validator(validator, pre=True) for i, validator in enumerate(get_validators())} 609 ) 610 611 self.type_ = get_args(self.type_)[0] 612 self.shape = SHAPE_LIST 613 elif issubclass(origin, Set): 614 # Create self validators 615 get_validators = getattr(self.type_, '__get_validators__', None) 616 if get_validators: 617 self.class_validators.update( 618 {f'set_{i}': Validator(validator, pre=True) for i, validator in enumerate(get_validators())} 619 ) 620 621 self.type_ = get_args(self.type_)[0] 622 self.shape = SHAPE_SET 623 elif issubclass(origin, FrozenSet): 624 # Create self validators 625 get_validators = getattr(self.type_, '__get_validators__', None) 626 if get_validators: 627 self.class_validators.update( 628 {f'frozenset_{i}': Validator(validator, pre=True) for i, validator in enumerate(get_validators())} 629 ) 630 631 self.type_ = get_args(self.type_)[0] 632 self.shape = SHAPE_FROZENSET 633 elif issubclass(origin, Deque): 634 self.type_ = get_args(self.type_)[0] 635 self.shape = SHAPE_DEQUE 636 elif issubclass(origin, Sequence): 637 self.type_ = get_args(self.type_)[0] 638 self.shape = SHAPE_SEQUENCE 639 elif issubclass(origin, DefaultDict): 640 self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True) 641 self.type_ = get_args(self.type_)[1] 642 self.shape = SHAPE_DEFAULTDICT 643 elif issubclass(origin, Counter): 644 self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True) 645 self.type_ = int 646 self.shape = SHAPE_COUNTER 647 elif issubclass(origin, Dict): 648 self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True) 649 self.type_ = get_args(self.type_)[1] 650 self.shape = SHAPE_DICT 651 elif issubclass(origin, Mapping): 652 self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True) 653 self.type_ = get_args(self.type_)[1] 654 self.shape = SHAPE_MAPPING 655 # Equality check as almost everything inherits form Iterable, including str 656 # check for Iterable and CollectionsIterable, as it could receive one even when declared with the other 657 elif origin in {Iterable, CollectionsIterable}: 658 self.type_ = get_args(self.type_)[0] 659 self.shape = SHAPE_ITERABLE 660 self.sub_fields = [self._create_sub_type(self.type_, f'{self.name}_type')] 661 elif issubclass(origin, Type): # type: ignore 662 return 663 elif hasattr(origin, '__get_validators__') or self.model_config.arbitrary_types_allowed: 664 # Is a Pydantic-compatible generic that handles itself 665 # or we have arbitrary_types_allowed = True 666 self.shape = SHAPE_GENERIC 667 self.sub_fields = [self._create_sub_type(t, f'{self.name}_{i}') for i, t in enumerate(get_args(self.type_))] 668 self.type_ = origin 669 return 670 else: 671 raise TypeError(f'Fields of type "{origin}" are not supported.') 672 673 # type_ has been refined eg. as the type of a List and sub_fields needs to be populated 674 self.sub_fields = [self._create_sub_type(self.type_, '_' + self.name)] 675 676 def _create_sub_type(self, type_: Type[Any], name: str, *, for_keys: bool = False) -> 'ModelField': 677 if for_keys: 678 class_validators = None 679 else: 680 # validators for sub items should not have `each_item` as we want to check only the first sublevel 681 class_validators = { 682 k: Validator( 683 func=v.func, 684 pre=v.pre, 685 each_item=False, 686 always=v.always, 687 check_fields=v.check_fields, 688 skip_on_failure=v.skip_on_failure, 689 ) 690 for k, v in self.class_validators.items() 691 if v.each_item 692 } 693 return self.__class__( 694 type_=type_, 695 name=name, 696 class_validators=class_validators, 697 model_config=self.model_config, 698 ) 699 700 def populate_validators(self) -> None: 701 """ 702 Prepare self.pre_validators, self.validators, and self.post_validators based on self.type_'s __get_validators__ 703 and class validators. This method should be idempotent, e.g. it should be safe to call multiple times 704 without mis-configuring the field. 705 """ 706 self.validate_always = getattr(self.type_, 'validate_always', False) or any( 707 v.always for v in self.class_validators.values() 708 ) 709 710 class_validators_ = self.class_validators.values() 711 if not self.sub_fields or self.shape == SHAPE_GENERIC: 712 get_validators = getattr(self.type_, '__get_validators__', None) 713 v_funcs = ( 714 *[v.func for v in class_validators_ if v.each_item and v.pre], 715 *(get_validators() if get_validators else list(find_validators(self.type_, self.model_config))), 716 *[v.func for v in class_validators_ if v.each_item and not v.pre], 717 ) 718 self.validators = prep_validators(v_funcs) 719 720 self.pre_validators = [] 721 self.post_validators = [] 722 723 if self.field_info and self.field_info.const: 724 self.post_validators.append(make_generic_validator(constant_validator)) 725 726 if class_validators_: 727 self.pre_validators += prep_validators(v.func for v in class_validators_ if not v.each_item and v.pre) 728 self.post_validators += prep_validators(v.func for v in class_validators_ if not v.each_item and not v.pre) 729 730 if self.parse_json: 731 self.pre_validators.append(make_generic_validator(validate_json)) 732 733 self.pre_validators = self.pre_validators or None 734 self.post_validators = self.post_validators or None 735 736 def validate( 737 self, v: Any, values: Dict[str, Any], *, loc: 'LocStr', cls: Optional['ModelOrDc'] = None 738 ) -> 'ValidateReturn': 739 740 assert self.type_.__class__ is not DeferredType 741 742 if self.type_.__class__ is ForwardRef: 743 assert cls is not None 744 raise ConfigError( 745 f'field "{self.name}" not yet prepared so type is still a ForwardRef, ' 746 f'you might need to call {cls.__name__}.update_forward_refs().' 747 ) 748 749 errors: Optional['ErrorList'] 750 if self.pre_validators: 751 v, errors = self._apply_validators(v, values, loc, cls, self.pre_validators) 752 if errors: 753 return v, errors 754 755 if v is None: 756 if is_none_type(self.type_): 757 # keep validating 758 pass 759 elif self.allow_none: 760 if self.post_validators: 761 return self._apply_validators(v, values, loc, cls, self.post_validators) 762 else: 763 return None, None 764 else: 765 return v, ErrorWrapper(NoneIsNotAllowedError(), loc) 766 767 if self.shape == SHAPE_SINGLETON: 768 v, errors = self._validate_singleton(v, values, loc, cls) 769 elif self.shape in MAPPING_LIKE_SHAPES: 770 v, errors = self._validate_mapping_like(v, values, loc, cls) 771 elif self.shape == SHAPE_TUPLE: 772 v, errors = self._validate_tuple(v, values, loc, cls) 773 elif self.shape == SHAPE_ITERABLE: 774 v, errors = self._validate_iterable(v, values, loc, cls) 775 elif self.shape == SHAPE_GENERIC: 776 v, errors = self._apply_validators(v, values, loc, cls, self.validators) 777 else: 778 # sequence, list, set, generator, tuple with ellipsis, frozen set 779 v, errors = self._validate_sequence_like(v, values, loc, cls) 780 781 if not errors and self.post_validators: 782 v, errors = self._apply_validators(v, values, loc, cls, self.post_validators) 783 return v, errors 784 785 def _validate_sequence_like( # noqa: C901 (ignore complexity) 786 self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc'] 787 ) -> 'ValidateReturn': 788 """ 789 Validate sequence-like containers: lists, tuples, sets and generators 790 Note that large if-else blocks are necessary to enable Cython 791 optimization, which is why we disable the complexity check above. 792 """ 793 if not sequence_like(v): 794 e: errors_.PydanticTypeError 795 if self.shape == SHAPE_LIST: 796 e = errors_.ListError() 797 elif self.shape in (SHAPE_TUPLE, SHAPE_TUPLE_ELLIPSIS): 798 e = errors_.TupleError() 799 elif self.shape == SHAPE_SET: 800 e = errors_.SetError() 801 elif self.shape == SHAPE_FROZENSET: 802 e = errors_.FrozenSetError() 803 else: 804 e = errors_.SequenceError() 805 return v, ErrorWrapper(e, loc) 806 807 loc = loc if isinstance(loc, tuple) else (loc,) 808 result = [] 809 errors: List[ErrorList] = [] 810 for i, v_ in enumerate(v): 811 v_loc = *loc, i 812 r, ee = self._validate_singleton(v_, values, v_loc, cls) 813 if ee: 814 errors.append(ee) 815 else: 816 result.append(r) 817 818 if errors: 819 return v, errors 820 821 converted: Union[List[Any], Set[Any], FrozenSet[Any], Tuple[Any, ...], Iterator[Any], Deque[Any]] = result 822 823 if self.shape == SHAPE_SET: 824 converted = set(result) 825 elif self.shape == SHAPE_FROZENSET: 826 converted = frozenset(result) 827 elif self.shape == SHAPE_TUPLE_ELLIPSIS: 828 converted = tuple(result) 829 elif self.shape == SHAPE_DEQUE: 830 converted = deque(result) 831 elif self.shape == SHAPE_SEQUENCE: 832 if isinstance(v, tuple): 833 converted = tuple(result) 834 elif isinstance(v, set): 835 converted = set(result) 836 elif isinstance(v, Generator): 837 converted = iter(result) 838 elif isinstance(v, deque): 839 converted = deque(result) 840 return converted, None 841 842 def _validate_iterable( 843 self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc'] 844 ) -> 'ValidateReturn': 845 """ 846 Validate Iterables. 847 848 This intentionally doesn't validate values to allow infinite generators. 849 """ 850 851 try: 852 iterable = iter(v) 853 except TypeError: 854 return v, ErrorWrapper(errors_.IterableError(), loc) 855 return iterable, None 856 857 def _validate_tuple( 858 self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc'] 859 ) -> 'ValidateReturn': 860 e: Optional[Exception] = None 861 if not sequence_like(v): 862 e = errors_.TupleError() 863 else: 864 actual_length, expected_length = len(v), len(self.sub_fields) # type: ignore 865 if actual_length != expected_length: 866 e = errors_.TupleLengthError(actual_length=actual_length, expected_length=expected_length) 867 868 if e: 869 return v, ErrorWrapper(e, loc) 870 871 loc = loc if isinstance(loc, tuple) else (loc,) 872 result = [] 873 errors: List[ErrorList] = [] 874 for i, (v_, field) in enumerate(zip(v, self.sub_fields)): # type: ignore 875 v_loc = *loc, i 876 r, ee = field.validate(v_, values, loc=v_loc, cls=cls) 877 if ee: 878 errors.append(ee) 879 else: 880 result.append(r) 881 882 if errors: 883 return v, errors 884 else: 885 return tuple(result), None 886 887 def _validate_mapping_like( 888 self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc'] 889 ) -> 'ValidateReturn': 890 try: 891 v_iter = dict_validator(v) 892 except TypeError as exc: 893 return v, ErrorWrapper(exc, loc) 894 895 loc = loc if isinstance(loc, tuple) else (loc,) 896 result, errors = {}, [] 897 for k, v_ in v_iter.items(): 898 v_loc = *loc, '__key__' 899 key_result, key_errors = self.key_field.validate(k, values, loc=v_loc, cls=cls) # type: ignore 900 if key_errors: 901 errors.append(key_errors) 902 continue 903 904 v_loc = *loc, k 905 value_result, value_errors = self._validate_singleton(v_, values, v_loc, cls) 906 if value_errors: 907 errors.append(value_errors) 908 continue 909 910 result[key_result] = value_result 911 if errors: 912 return v, errors 913 elif self.shape == SHAPE_DICT: 914 return result, None 915 elif self.shape == SHAPE_DEFAULTDICT: 916 return defaultdict(self.type_, result), None 917 elif self.shape == SHAPE_COUNTER: 918 return CollectionCounter(result), None 919 else: 920 return self._get_mapping_value(v, result), None 921 922 def _get_mapping_value(self, original: T, converted: Dict[Any, Any]) -> Union[T, Dict[Any, Any]]: 923 """ 924 When type is `Mapping[KT, KV]` (or another unsupported mapping), we try to avoid 925 coercing to `dict` unwillingly. 926 """ 927 original_cls = original.__class__ 928 929 if original_cls == dict or original_cls == Dict: 930 return converted 931 elif original_cls in {defaultdict, DefaultDict}: 932 return defaultdict(self.type_, converted) 933 else: 934 try: 935 # Counter, OrderedDict, UserDict, ... 936 return original_cls(converted) # type: ignore 937 except TypeError: 938 raise RuntimeError(f'Could not convert dictionary to {original_cls.__name__!r}') from None 939 940 def _validate_singleton( 941 self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc'] 942 ) -> 'ValidateReturn': 943 if self.sub_fields: 944 errors = [] 945 946 if self.model_config.smart_union and is_union(get_origin(self.type_)): 947 # 1st pass: check if the value is an exact instance of one of the Union types 948 # (e.g. to avoid coercing a bool into an int) 949 for field in self.sub_fields: 950 if v.__class__ is field.outer_type_: 951 return v, None 952 953 # 2nd pass: check if the value is an instance of any subclass of the Union types 954 for field in self.sub_fields: 955 # This whole logic will be improved later on to support more complex `isinstance` checks 956 # It will probably be done once a strict mode is added and be something like: 957 # ``` 958 # value, error = field.validate(v, values, strict=True) 959 # if error is None: 960 # return value, None 961 # ``` 962 try: 963 if isinstance(v, field.outer_type_): 964 return v, None 965 except TypeError: 966 # compound type 967 if isinstance(v, get_origin(field.outer_type_)): 968 value, error = field.validate(v, values, loc=loc, cls=cls) 969 if not error: 970 return value, None 971 972 # 1st pass by default or 3rd pass with `smart_union` enabled: 973 # check if the value can be coerced into one of the Union types 974 for field in self.sub_fields: 975 value, error = field.validate(v, values, loc=loc, cls=cls) 976 if error: 977 errors.append(error) 978 else: 979 return value, None 980 return v, errors 981 else: 982 return self._apply_validators(v, values, loc, cls, self.validators) 983 984 def _apply_validators( 985 self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc'], validators: 'ValidatorsList' 986 ) -> 'ValidateReturn': 987 for validator in validators: 988 try: 989 v = validator(cls, v, values, self, self.model_config) 990 except (ValueError, TypeError, AssertionError) as exc: 991 return v, ErrorWrapper(exc, loc) 992 return v, None 993 994 def is_complex(self) -> bool: 995 """ 996 Whether the field is "complex" eg. env variables should be parsed as JSON. 997 """ 998 from .main import BaseModel 999 1000 return ( 1001 self.shape != SHAPE_SINGLETON 1002 or lenient_issubclass(self.type_, (BaseModel, list, set, frozenset, dict)) 1003 or hasattr(self.type_, '__pydantic_model__') # pydantic dataclass 1004 ) 1005 1006 def _type_display(self) -> PyObjectStr: 1007 t = display_as_type(self.type_) 1008 1009 # have to do this since display_as_type(self.outer_type_) is different (and wrong) on python 3.6 1010 if self.shape in MAPPING_LIKE_SHAPES: 1011 t = f'Mapping[{display_as_type(self.key_field.type_)}, {t}]' # type: ignore 1012 elif self.shape == SHAPE_TUPLE: 1013 t = 'Tuple[{}]'.format(', '.join(display_as_type(f.type_) for f in self.sub_fields)) # type: ignore 1014 elif self.shape == SHAPE_GENERIC: 1015 assert self.sub_fields 1016 t = '{}[{}]'.format( 1017 display_as_type(self.type_), ', '.join(display_as_type(f.type_) for f in self.sub_fields) 1018 ) 1019 elif self.shape != SHAPE_SINGLETON: 1020 t = SHAPE_NAME_LOOKUP[self.shape].format(t) 1021 1022 if self.allow_none and (self.shape != SHAPE_SINGLETON or not self.sub_fields): 1023 t = f'Optional[{t}]' 1024 return PyObjectStr(t) 1025 1026 def __repr_args__(self) -> 'ReprArgs': 1027 args = [('name', self.name), ('type', self._type_display()), ('required', self.required)] 1028 1029 if not self.required: 1030 if self.default_factory is not None: 1031 args.append(('default_factory', f'<function {self.default_factory.__name__}>')) 1032 else: 1033 args.append(('default', self.default)) 1034 1035 if self.alt_alias: 1036 args.append(('alias', self.alias)) 1037 return args 1038 1039 1040 class ModelPrivateAttr(Representation): 1041 __slots__ = ('default', 'default_factory') 1042 1043 def __init__(self, default: Any = Undefined, *, default_factory: Optional[NoArgAnyCallable] = None) -> None: 1044 self.default = default 1045 self.default_factory = default_factory 1046 1047 def get_default(self) -> Any: 1048 return smart_deepcopy(self.default) if self.default_factory is None else self.default_factory() 1049 1050 def __eq__(self, other: Any) -> bool: 1051 return isinstance(other, self.__class__) and (self.default, self.default_factory) == ( 1052 other.default, 1053 other.default_factory, 1054 ) 1055 1056 1057 def PrivateAttr( 1058 default: Any = Undefined, 1059 *, 1060 default_factory: Optional[NoArgAnyCallable] = None, 1061 ) -> Any: 1062 """ 1063 Indicates that attribute is only used internally and never mixed with regular fields. 1064 1065 Types or values of private attrs are not checked by pydantic and it's up to you to keep them relevant. 1066 1067 Private attrs are stored in model __slots__. 1068 1069 :param default: the attribute’s default value 1070 :param default_factory: callable that will be called when a default value is needed for this attribute 1071 If both `default` and `default_factory` are set, an error is raised. 1072 """ 1073 if default is not Undefined and default_factory is not None: 1074 raise ValueError('cannot specify both default and default_factory') 1075 1076 return ModelPrivateAttr( 1077 default, 1078 default_factory=default_factory, 1079 ) 1080 1081 1082 class DeferredType: 1083 """ 1084 Used to postpone field preparation, while creating recursive generic models. 1085 """ 1086 [end of pydantic/fields.py] </code> I need you to solve this issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the following format. <patch> --- a/file.py +++ b/file.py @@ -1,27 +1,35 @@ def euclidean(a, b): - while b: - a, b = b, a % b - return a + if b == 0: + return a + return euclidean(b, a % b) def bresenham(x0, y0, x1, y1): points = [] dx = abs(x1 - x0) dy = abs(y1 - y0) - sx = 1 if x0 < x1 else -1 - sy = 1 if y0 < y1 else -1 - err = dx - dy + x, y = x0, y0 + sx = -1 if x0 > x1 else 1 + sy = -1 if y0 > y1 else 1 - while True: - points.append((x0, y0)) - if x0 == x1 and y0 == y1: - break - e2 = 2 * err - if e2 > -dy: + if dx > dy: + err = dx / 2.0 + while x != x1: + points.append((x, y)) err -= dy - x0 += sx - if e2 < dx: - err += dx - y0 += sy + if err < 0: + y += sy + err += dx + x += sx + else: + err = dy / 2.0 + while y != y1: + points.append((x, y)) + err -= dx + if err < 0: + x += sx + err += dy + y += sy + points.append((x, y)) return points </patch>
pydantic/pydantic
7421579480148cdfbd7752b17b49a3dbbc7557bc
"none is not an allowed value" when using Union with Any ### Checks * [x] I added a descriptive title to this issue * [x] I have searched (google, github) for similar issues and couldn't find anything * [x] I have read and followed [the docs](https://pydantic-docs.helpmanual.io/) and still think this is a bug # Bug It seems that `None` is allowed when a field's type is `Any` (as is expected, stated in the docs), but `None` is not allowed when a field's type is `Union[SomeType, Any]`. Output of `python -c "import pydantic.utils; print(pydantic.utils.version_info())"`: ``` pydantic version: 1.8.2 pydantic compiled: True install path: C:\Users\TobyHarradine\PycharmProjects\orchestration\.venv\Lib\site-packages\pydantic python version: 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] platform: Windows-10-10.0.19041-SP0 optional deps. installed: ['typing-extensions'] ``` Code which reproduces the issue: ```pycon >>> import pydantic >>> class M(pydantic.BaseModel): ... a: Any ... >>> M(a=1) M(a=1) >>> M(a=None) M(a=None) >>> class M(pydantic.BaseModel): ... a: Union[int, Any] ... >>> M(a=1) M(a=1) >>> M(a="abcd") M(a='abcd') >>> M(a=None) Traceback (most recent call last): File "<input>", line 1, in <module> File "pydantic\main.py", line 406, in pydantic.main.BaseModel.__init__ pydantic.error_wrappers.ValidationError: 1 validation error for M a none is not an allowed value (type=type_error.none.not_allowed) ``` This may be somewhat related to #1624.
`allow_none` attribute for field `a` remains `False`. Possible fix may be in pydantic/fields.py:566: ``` if is_union_origin(origin): types_ = [] for type_ in get_args(self.type_): if type_ is NoneType or type_ is Any or type_ is object: if self.required is Undefined: self.required = False self.allow_none = True continue types_.append(type_) ``` @mykhailoleskiv That almost works, except it doesn't add `Any` or `object` to `types_` (which eventually becomes `ModelField.sub_fields`). So `M(a="abcd")` or something like that no longer works. I'll open a PR
2021-11-25 23:06:55+00:00
<patch> diff --git a/pydantic/fields.py b/pydantic/fields.py --- a/pydantic/fields.py +++ b/pydantic/fields.py @@ -34,7 +34,6 @@ Callable, ForwardRef, NoArgAnyCallable, - NoneType, display_as_type, get_args, get_origin, @@ -563,10 +562,11 @@ def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) if is_union(origin): types_ = [] for type_ in get_args(self.type_): - if type_ is NoneType: + if is_none_type(type_) or type_ is Any or type_ is object: if self.required is Undefined: self.required = False self.allow_none = True + if is_none_type(type_): continue types_.append(type_) </patch>
diff --git a/tests/test_edge_cases.py b/tests/test_edge_cases.py --- a/tests/test_edge_cases.py +++ b/tests/test_edge_cases.py @@ -83,6 +83,23 @@ class Model(BaseModel): ] +def test_union_int_any(): + class Model(BaseModel): + v: Union[int, Any] + + m = Model(v=123) + assert m.v == 123 + + m = Model(v='123') + assert m.v == 123 + + m = Model(v='foobar') + assert m.v == 'foobar' + + m = Model(v=None) + assert m.v is None + + def test_union_priority(): class ModelOne(BaseModel): v: Union[int, str] = ...
0.0
[ "tests/test_edge_cases.py::test_union_int_any" ]
[ "tests/test_edge_cases.py::test_str_bytes", "tests/test_edge_cases.py::test_str_bytes_none", "tests/test_edge_cases.py::test_union_int_str", "tests/test_edge_cases.py::test_union_priority", "tests/test_edge_cases.py::test_typed_list", "tests/test_edge_cases.py::test_typed_set", "tests/test_edge_cases.py::test_dict_dict", "tests/test_edge_cases.py::test_none_list", "tests/test_edge_cases.py::test_typed_dict[value0-result0]", "tests/test_edge_cases.py::test_typed_dict[value1-result1]", "tests/test_edge_cases.py::test_typed_dict[value2-result2]", "tests/test_edge_cases.py::test_typed_dict_error[1-errors0]", "tests/test_edge_cases.py::test_typed_dict_error[value1-errors1]", "tests/test_edge_cases.py::test_typed_dict_error[value2-errors2]", "tests/test_edge_cases.py::test_dict_key_error", "tests/test_edge_cases.py::test_tuple", "tests/test_edge_cases.py::test_tuple_more", "tests/test_edge_cases.py::test_tuple_length_error", "tests/test_edge_cases.py::test_tuple_invalid", "tests/test_edge_cases.py::test_tuple_value_error", "tests/test_edge_cases.py::test_recursive_list", "tests/test_edge_cases.py::test_recursive_list_error", "tests/test_edge_cases.py::test_list_unions", "tests/test_edge_cases.py::test_recursive_lists", "tests/test_edge_cases.py::test_str_enum", "tests/test_edge_cases.py::test_any_dict", "tests/test_edge_cases.py::test_success_values_include", "tests/test_edge_cases.py::test_include_exclude_unset", "tests/test_edge_cases.py::test_include_exclude_defaults", "tests/test_edge_cases.py::test_skip_defaults_deprecated", "tests/test_edge_cases.py::test_advanced_exclude", "tests/test_edge_cases.py::test_advanced_exclude_by_alias", "tests/test_edge_cases.py::test_advanced_value_include", "tests/test_edge_cases.py::test_advanced_value_exclude_include", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude0-expected0]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude1-expected1]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude2-expected2]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude3-expected3]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude4-expected4]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude5-expected5]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude6-expected6]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude7-expected7]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude8-expected8]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude9-expected9]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude10-expected10]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude11-expected11]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude12-expected12]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude13-expected13]", "tests/test_edge_cases.py::test_advanced_exclude_nested_lists[exclude14-expected14]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include0-expected0]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include1-expected1]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include2-expected2]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include3-expected3]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include4-expected4]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include5-expected5]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include6-expected6]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include7-expected7]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include8-expected8]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include9-expected9]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include10-expected10]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include11-expected11]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include12-expected12]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include13-expected13]", "tests/test_edge_cases.py::test_advanced_include_nested_lists[include14-expected14]", "tests/test_edge_cases.py::test_field_set_ignore_extra", "tests/test_edge_cases.py::test_field_set_allow_extra", "tests/test_edge_cases.py::test_field_set_field_name", "tests/test_edge_cases.py::test_values_order", "tests/test_edge_cases.py::test_inheritance", "tests/test_edge_cases.py::test_inheritance_subclass_default", "tests/test_edge_cases.py::test_invalid_type", "tests/test_edge_cases.py::test_valid_string_types[a", "tests/test_edge_cases.py::test_valid_string_types[some", "tests/test_edge_cases.py::test_valid_string_types[value2-foobar]", "tests/test_edge_cases.py::test_valid_string_types[123-123]", "tests/test_edge_cases.py::test_valid_string_types[123.45-123.45]", "tests/test_edge_cases.py::test_valid_string_types[value5-12.45]", "tests/test_edge_cases.py::test_valid_string_types[True-True]", "tests/test_edge_cases.py::test_valid_string_types[False-False]", "tests/test_edge_cases.py::test_valid_string_types[a10-a10]", "tests/test_edge_cases.py::test_valid_string_types[whatever-whatever]", "tests/test_edge_cases.py::test_invalid_string_types[value0-errors0]", "tests/test_edge_cases.py::test_invalid_string_types[value1-errors1]", "tests/test_edge_cases.py::test_inheritance_config", "tests/test_edge_cases.py::test_partial_inheritance_config", "tests/test_edge_cases.py::test_annotation_inheritance", "tests/test_edge_cases.py::test_string_none", "tests/test_edge_cases.py::test_return_errors_ok", "tests/test_edge_cases.py::test_return_errors_error", "tests/test_edge_cases.py::test_optional_required", "tests/test_edge_cases.py::test_invalid_validator", "tests/test_edge_cases.py::test_unable_to_infer", "tests/test_edge_cases.py::test_multiple_errors", "tests/test_edge_cases.py::test_validate_all", "tests/test_edge_cases.py::test_force_extra", "tests/test_edge_cases.py::test_illegal_extra_value", "tests/test_edge_cases.py::test_multiple_inheritance_config", "tests/test_edge_cases.py::test_submodel_different_type", "tests/test_edge_cases.py::test_self", "tests/test_edge_cases.py::test_self_recursive[BaseModel]", "tests/test_edge_cases.py::test_self_recursive[BaseSettings]", "tests/test_edge_cases.py::test_nested_init[BaseModel]", "tests/test_edge_cases.py::test_nested_init[BaseSettings]", "tests/test_edge_cases.py::test_init_inspection", "tests/test_edge_cases.py::test_type_on_annotation", "tests/test_edge_cases.py::test_assign_type", "tests/test_edge_cases.py::test_optional_subfields", "tests/test_edge_cases.py::test_not_optional_subfields", "tests/test_edge_cases.py::test_optional_field_constraints", "tests/test_edge_cases.py::test_field_str_shape", "tests/test_edge_cases.py::test_field_type_display[int-int]", "tests/test_edge_cases.py::test_field_type_display[type_1-Optional[int]]", "tests/test_edge_cases.py::test_field_type_display[type_2-Union[NoneType,", "tests/test_edge_cases.py::test_field_type_display[type_3-Union[int,", "tests/test_edge_cases.py::test_field_type_display[type_4-List[int]]", "tests/test_edge_cases.py::test_field_type_display[type_5-Tuple[int,", "tests/test_edge_cases.py::test_field_type_display[type_6-Union[List[int],", "tests/test_edge_cases.py::test_field_type_display[type_7-List[Tuple[int,", "tests/test_edge_cases.py::test_field_type_display[type_8-Mapping[int,", "tests/test_edge_cases.py::test_field_type_display[type_9-FrozenSet[int]]", "tests/test_edge_cases.py::test_field_type_display[type_10-Tuple[int,", "tests/test_edge_cases.py::test_field_type_display[type_11-Optional[List[int]]]", "tests/test_edge_cases.py::test_field_type_display[dict-dict]", "tests/test_edge_cases.py::test_field_type_display[type_13-DisplayGen[bool,", "tests/test_edge_cases.py::test_any_none", "tests/test_edge_cases.py::test_type_var_any", "tests/test_edge_cases.py::test_type_var_constraint", "tests/test_edge_cases.py::test_type_var_bound", "tests/test_edge_cases.py::test_dict_bare", "tests/test_edge_cases.py::test_list_bare", "tests/test_edge_cases.py::test_dict_any", "tests/test_edge_cases.py::test_modify_fields", "tests/test_edge_cases.py::test_exclude_none", "tests/test_edge_cases.py::test_exclude_none_recursive", "tests/test_edge_cases.py::test_exclude_none_with_extra", "tests/test_edge_cases.py::test_str_method_inheritance", "tests/test_edge_cases.py::test_repr_method_inheritance", "tests/test_edge_cases.py::test_optional_validator", "tests/test_edge_cases.py::test_required_optional", "tests/test_edge_cases.py::test_required_any", "tests/test_edge_cases.py::test_custom_generic_validators", "tests/test_edge_cases.py::test_custom_generic_arbitrary_allowed", "tests/test_edge_cases.py::test_custom_generic_disallowed", "tests/test_edge_cases.py::test_hashable_required", "tests/test_edge_cases.py::test_hashable_optional[1]", "tests/test_edge_cases.py::test_hashable_optional[None]", "tests/test_edge_cases.py::test_default_factory_called_once", "tests/test_edge_cases.py::test_default_factory_validator_child", "tests/test_edge_cases.py::test_cython_function_untouched", "tests/test_edge_cases.py::test_resolve_annotations_module_missing", "tests/test_edge_cases.py::test_iter_coverage", "tests/test_edge_cases.py::test_config_field_info", "tests/test_edge_cases.py::test_config_field_info_alias", "tests/test_edge_cases.py::test_config_field_info_merge", "tests/test_edge_cases.py::test_config_field_info_allow_mutation", "tests/test_edge_cases.py::test_arbitrary_types_allowed_custom_eq" ]
7421579480148cdfbd7752b17b49a3dbbc7557bc
steemit__hivemind-255
You will be provided with a partial code base and an issue statement explaining a problem to resolve. <issue> Support for account_update2 / posting_json_metadata I broadcasted posting_json_metadata using the new account_update2 operation (https://steemd.com/@tftest1), but unlike when broadcasting json_metadata, this does not change the information that are indexed in hive_accounts </issue> <code> [start of README.md] 1 # Hivemind [BETA] 2 3 #### Developer-friendly microservice powering social networks on the Steem blockchain. 4 5 Hive is a "consensus interpretation" layer for the Steem blockchain, maintaining the state of social features such as post feeds, follows, and communities. Written in Python, it synchronizes an SQL database with chain state, providing developers with a more flexible/extensible alternative to the raw steemd API. 6 7 ## Development Environment 8 9 - Python 3.6 required 10 - Postgres 10+ recommended 11 12 Dependencies: 13 14 - OSX: `$ brew install python3 postgresql` 15 - Ubuntu: `$ sudo apt-get install python3 python3-pip` 16 17 Installation: 18 19 ```bash 20 $ createdb hive 21 $ export DATABASE_URL=postgresql://user:pass@localhost:5432/hive 22 ``` 23 24 ```bash 25 $ git clone https://github.com/steemit/hivemind.git 26 $ cd hivemind 27 $ pip3 install -e .[test] 28 ``` 29 30 Start the indexer: 31 32 ```bash 33 $ hive sync 34 ``` 35 36 ```bash 37 $ hive status 38 {'db_head_block': 19930833, 'db_head_time': '2018-02-16 21:37:36', 'db_head_age': 10} 39 ``` 40 41 Start the server: 42 43 ```bash 44 $ hive server 45 ``` 46 47 ```bash 48 $ curl --data '{"jsonrpc":"2.0","id":0,"method":"hive.db_head_state","params":{}}' http://localhost:8080 49 {"jsonrpc": "2.0", "result": {"db_head_block": 19930795, "db_head_time": "2018-02-16 21:35:42", "db_head_age": 10}, "id": 0} 50 ``` 51 52 Run tests: 53 54 ```bash 55 $ make test 56 ``` 57 58 59 ## Production Environment 60 61 Hivemind is deployed as a Docker container. 62 63 Here is an example command that will initialize the DB schema and start the syncing process: 64 65 ``` 66 docker run -d --name hivemind --env DATABASE_URL=postgresql://user:pass@hostname:5432/databasename --env STEEMD_URL=https://yoursteemnode --env SYNC_SERVICE=1 -p 8080:8080 steemit/hivemind:latest 67 ``` 68 69 Be sure to set `DATABASE_URL` to point to your postgres database and `STEEMD_URL` to point to your steemd node to sync from. 70 71 Once the database is synced, Hivemind will be available for serving requests. 72 73 To follow along the logs, use this: 74 75 ``` 76 docker logs -f hivemind 77 ``` 78 79 80 ## Configuration 81 82 | Environment | CLI argument | Default | 83 | ------------------------ | -------------------- | ------- | 84 | `LOG_LEVEL` | `--log-level` | INFO | 85 | `HTTP_SERVER_PORT` | `--http-server-port` | 8080 | 86 | `DATABASE_URL` | `--database-url` | postgresql://user:pass@localhost:5432/hive | 87 | `STEEMD_URL` | `--steemd-url` | https://api.steemit.com | 88 | `MAX_BATCH` | `--max-batch` | 50 | 89 | `MAX_WORKERS` | `--max-workers` | 4 | 90 | `TRAIL_BLOCKS` | `--trail-blocks` | 2 | 91 92 Precedence: CLI over ENV over hive.conf. Check `hive --help` for details. 93 94 95 ## Requirements 96 97 98 99 ### Hardware 100 101 - Focus on Postgres performance 102 - 2.5GB of memory for `hive sync` process 103 - 250GB storage for database 104 105 106 ### Steem config 107 108 Build flags 109 110 - `LOW_MEMORY_NODE=OFF` - need post content 111 - `CLEAR_VOTES=OFF` - need all vote data 112 - `SKIP_BY_TX=ON` - tx lookup not used 113 114 Plugins 115 116 - Required: `reputation reputation_api database_api condenser_api block_api` 117 - Not required: `follow*`, `tags*`, `market_history`, `account_history`, `witness` 118 119 120 ### Postgres Performance 121 122 For a system with 16G of memory, here's a good start: 123 124 ``` 125 effective_cache_size = 12GB # 50-75% of avail memory 126 maintenance_work_mem = 2GB 127 random_page_cost = 1.0 # assuming SSD storage 128 shared_buffers = 4GB # 25% of memory 129 work_mem = 512MB 130 synchronous_commit = off 131 checkpoint_completion_target = 0.9 132 checkpoint_timeout = 30min 133 max_wal_size = 4GB 134 ``` 135 136 ## JSON-RPC API 137 138 The minimum viable API is to remove the requirement for the `follow` and `tags` plugins (now rolled into [`condenser_api`](https://github.com/steemit/steem/blob/master/libraries/plugins/apis/condenser_api/condenser_api.cpp)) from the backend node while still being able to power condenser's non-wallet features. Thus, this is the core API set: 139 140 ``` 141 condenser_api.get_followers 142 condenser_api.get_following 143 condenser_api.get_follow_count 144 145 condenser_api.get_content 146 condenser_api.get_content_replies 147 148 condenser_api.get_state 149 150 condenser_api.get_trending_tags 151 152 condenser_api.get_discussions_by_trending 153 condenser_api.get_discussions_by_hot 154 condenser_api.get_discussions_by_promoted 155 condenser_api.get_discussions_by_created 156 157 condenser_api.get_discussions_by_blog 158 condenser_api.get_discussions_by_feed 159 condenser_api.get_discussions_by_comments 160 condenser_api.get_replies_by_last_update 161 162 condenser_api.get_blog 163 condenser_api.get_blog_entries 164 condenser_api.get_discussions_by_author_before_date 165 ``` 166 167 168 ## Overview 169 170 171 #### History 172 173 Initially, the [steemit.com](https://steemit.com) app was powered exclusively by `steemd` nodes. It was purely a client-side app without *any* backend other than a public and permissionless API node. As powerful as this model is, there are two issues: (a) maintaining UI-specific indices/APIs becomes expensive when tightly coupled to critical consensus nodes; and (b) frontend developers must be able to iterate quickly and access data in flexible and creative ways without writing C++. 174 175 To relieve backend and frontend pressure, non-consensus and frontend-oriented concerns can be decoupled from `steemd` itself. This (a) allows the consensus node to focus on scalability and reliability, and (b) allows the frontend to maintain its own state layer, allowing for flexibility not feasible otherwise. 176 177 Specifically, the goal is to completely remove the `follow` and `tags` plugins, as well as `get_state` from the backend node itself, and re-implement them in `hive`. In doing so, we form the foundational infrastructure on which to implement communities and more. 178 179 #### Purpose 180 181 ##### Hive tracks posts, relationships, social actions, custom operations, and derived states. 182 183 - *discussions:* by blog, trending, hot, created, etc 184 - *communities:* mod roles/actions, members, feeds (in 1.5; [spec](https://github.com/steemit/hivemind/blob/master/docs/communities.md)) 185 - *accounts:* normalized profile data, reputation 186 - *feeds:* un/follows and un/reblogs 187 188 ##### Hive does not track most blockchain operations. 189 190 For anything to do with wallets, orders, escrow, keys, recovery, or account history, query SBDS or steemd. 191 192 ##### Hive can be extended or leveraged to create: 193 194 - reactions, bookmarks 195 - comment on reblogs 196 - indexing custom profile data 197 - reorganize old posts (categorize, filter, hide/show) 198 - voting/polls (democratic or burn/send to vote) 199 - modlists: (e.g. spammy, abuse, badtaste) 200 - crowdsourced metadata 201 - mentions indexing 202 - full-text search 203 - follow lists 204 - bot tracking 205 - mini-games 206 - community bots 207 208 #### Core indexer 209 210 Ingests blocks sequentially, processing operations relevant to accounts, post creations/edits/deletes, and custom_json ops for follows, reblogs, and communities. From these we build account and post lookup tables, follow/reblog state, and communities/members data. Built exclusively from raw blocks, it becomes the ground truth for internal state. Hive does not reimplement logic required for deriving payout values, reputation, and other statistics which are much more easily attained from steemd itself in the cache layer. 211 212 #### Cache layer 213 214 Synchronizes the latest state of posts and users, allowing us to serve discussions and lists of posts with all expected information (title, preview, image, payout, votes, etc) without needing `steemd`. This layer is first built once the initial core indexing is complete. Incoming blocks trigger cache updates (including recalculation of trending score) for any posts referenced in `comment` or `vote` operations. There is a sweep to paid out posts to ensure they are updated in full with their final state. 215 216 #### API layer 217 218 Performs queries against the core and cache tables, merging them into a response in such a way that the frontend will not need to perform any additional calls to `steemd` itself. The initial API simply mimics steemd's `condenser_api` for backwards compatibility, but will be extended to leverage new opportunities and simplify application development. 219 220 221 #### Fork Resolution 222 223 **Latency vs. consistency vs. complexity** 224 225 The easiest way to avoid forks is to only index up to the last irreversible block, but the delay is too much where users expect quick feedback, e.g. votes and live discussions. We can apply the following approach: 226 227 1. Follow the chain as closely to `head_block` as possible 228 2. Indexer trails a few blocks behind, by no more than 6s - 9s 229 3. If missed blocks detected, back off from `head_block` 230 4. Database constraints on block linking to detect failure asap 231 5. If a fork is encountered between `hive_head` and `steem_head`, trivial recovery 232 6. Otherwise, pop blocks until in sync. Inconsistent state possible but rare for `TRAIL_BLOCKS > 1`. 233 7. A separate service with a greater follow distance creates periodic snapshots 234 235 236 ## Documentation 237 238 ```bash 239 $ make docs && open docs/hive/index.html 240 ``` 241 242 ## License 243 244 MIT 245 [end of README.md] [start of hive/indexer/accounts.py] 1 """Accounts indexer.""" 2 3 import logging 4 5 from datetime import datetime 6 from toolz import partition_all 7 8 import ujson as json 9 10 from hive.db.adapter import Db 11 from hive.utils.normalize import rep_log10, vests_amount 12 from hive.utils.timer import Timer 13 from hive.utils.account import safe_profile_metadata 14 from hive.utils.unique_fifo import UniqueFIFO 15 16 log = logging.getLogger(__name__) 17 18 DB = Db.instance() 19 20 class Accounts: 21 """Manages account id map, dirty queue, and `hive_accounts` table.""" 22 23 # name->id map 24 _ids = {} 25 26 # fifo queue 27 _dirty = UniqueFIFO() 28 29 # in-mem id->rank map 30 _ranks = {} 31 32 # account core methods 33 # -------------------- 34 35 @classmethod 36 def load_ids(cls): 37 """Load a full (name: id) dict into memory.""" 38 assert not cls._ids, "id map already loaded" 39 cls._ids = dict(DB.query_all("SELECT name, id FROM hive_accounts")) 40 41 @classmethod 42 def clear_ids(cls): 43 """Wipe id map. Only used for db migration #5.""" 44 cls._ids = None 45 46 @classmethod 47 def default_score(cls, name): 48 """Return default notification score based on rank.""" 49 _id = cls.get_id(name) 50 rank = cls._ranks[_id] if _id in cls._ranks else 1000000 51 if rank < 200: return 70 # 0.02% 100k 52 if rank < 1000: return 60 # 0.1% 10k 53 if rank < 6500: return 50 # 0.5% 1k 54 if rank < 25000: return 40 # 2.0% 100 55 if rank < 100000: return 30 # 8.0% 15 56 return 20 57 58 @classmethod 59 def get_id(cls, name): 60 """Get account id by name. Throw if not found.""" 61 assert name in cls._ids, "account does not exist or was not registered" 62 return cls._ids[name] 63 64 @classmethod 65 def exists(cls, name): 66 """Check if an account name exists.""" 67 return name in cls._ids 68 69 @classmethod 70 def register(cls, names, block_date): 71 """Block processing: register "candidate" names. 72 73 There are four ops which can result in account creation: 74 *account_create*, *account_create_with_delegation*, *pow*, 75 and *pow2*. *pow* ops result in account creation only when 76 the account they name does not already exist! 77 """ 78 79 # filter out names which already registered 80 new_names = list(filter(lambda n: not cls.exists(n), set(names))) 81 if not new_names: 82 return 83 84 for name in new_names: 85 DB.query("INSERT INTO hive_accounts (name, created_at) " 86 "VALUES (:name, :date)", name=name, date=block_date) 87 88 # pull newly-inserted ids and merge into our map 89 sql = "SELECT name, id FROM hive_accounts WHERE name IN :names" 90 for name, _id in DB.query_all(sql, names=tuple(new_names)): 91 cls._ids[name] = _id 92 93 # post-insert: pass to communities to check for new registrations 94 from hive.indexer.community import Community, START_DATE 95 if block_date > START_DATE: 96 Community.register(new_names, block_date) 97 98 # account cache methods 99 # --------------------- 100 101 @classmethod 102 def dirty(cls, account): 103 """Marks given account as needing an update.""" 104 return cls._dirty.add(account) 105 106 @classmethod 107 def dirty_set(cls, accounts): 108 """Marks given accounts as needing an update.""" 109 return cls._dirty.extend(accounts) 110 111 @classmethod 112 def dirty_all(cls): 113 """Marks all accounts as dirty. Use to rebuild entire table.""" 114 cls.dirty(set(DB.query_col("SELECT name FROM hive_accounts"))) 115 116 @classmethod 117 def dirty_oldest(cls, limit=50000): 118 """Flag `limit` least-recently updated accounts for update.""" 119 sql = "SELECT name FROM hive_accounts ORDER BY cached_at LIMIT :limit" 120 return cls.dirty_set(set(DB.query_col(sql, limit=limit))) 121 122 @classmethod 123 def flush(cls, steem, trx=False, spread=1): 124 """Process all accounts flagged for update. 125 126 - trx: bool - wrap the update in a transaction 127 - spread: int - spread writes over a period of `n` calls 128 """ 129 accounts = cls._dirty.shift_portion(spread) 130 131 count = len(accounts) 132 if not count: 133 return 0 134 135 if trx: 136 log.info("[SYNC] update %d accounts", count) 137 138 cls._cache_accounts(accounts, steem, trx=trx) 139 return count 140 141 @classmethod 142 def fetch_ranks(cls): 143 """Rebuild account ranks and store in memory for next update.""" 144 sql = "SELECT id FROM hive_accounts ORDER BY vote_weight DESC" 145 for rank, _id in enumerate(DB.query_col(sql)): 146 cls._ranks[_id] = rank + 1 147 148 @classmethod 149 def _cache_accounts(cls, accounts, steem, trx=True): 150 """Fetch all `accounts` and write to db.""" 151 timer = Timer(len(accounts), 'account', ['rps', 'wps']) 152 for name_batch in partition_all(1000, accounts): 153 cached_at = datetime.now().strftime('%Y-%m-%dT%H:%M:%S') 154 155 timer.batch_start() 156 batch = steem.get_accounts(name_batch) 157 158 timer.batch_lap() 159 sqls = [cls._sql(acct, cached_at) for acct in batch] 160 DB.batch_queries(sqls, trx) 161 162 timer.batch_finish(len(batch)) 163 if trx or len(accounts) > 1000: 164 log.info(timer.batch_status()) 165 166 @classmethod 167 def _sql(cls, account, cached_at): 168 """Prepare a SQL query from a steemd account.""" 169 vests = vests_amount(account['vesting_shares']) 170 171 vote_weight = (vests 172 + vests_amount(account['received_vesting_shares']) 173 - vests_amount(account['delegated_vesting_shares'])) 174 175 proxy_weight = 0 if account['proxy'] else float(vests) 176 for satoshis in account['proxied_vsf_votes']: 177 proxy_weight += float(satoshis) / 1e6 178 179 # remove empty keys 180 useless = ['transfer_history', 'market_history', 'post_history', 181 'vote_history', 'other_history', 'tags_usage', 182 'guest_bloggers'] 183 for key in useless: 184 del account[key] 185 186 # pull out valid profile md and delete the key 187 profile = safe_profile_metadata(account) 188 del account['json_metadata'] 189 190 active_at = max(account['created'], 191 account['last_account_update'], 192 account['last_post'], 193 account['last_root_post'], 194 account['last_vote_time']) 195 196 values = { 197 'name': account['name'], 198 'created_at': account['created'], 199 'proxy': account['proxy'], 200 'post_count': account['post_count'], 201 'reputation': rep_log10(account['reputation']), 202 'proxy_weight': proxy_weight, 203 'vote_weight': vote_weight, 204 'active_at': active_at, 205 'cached_at': cached_at, 206 207 'display_name': profile['name'], 208 'about': profile['about'], 209 'location': profile['location'], 210 'website': profile['website'], 211 'profile_image': profile['profile_image'], 212 'cover_image': profile['cover_image'], 213 214 'raw_json': json.dumps(account)} 215 216 # update rank field, if present 217 _id = cls.get_id(account['name']) 218 if _id in cls._ranks: 219 values['rank'] = cls._ranks[_id] 220 221 bind = ', '.join([k+" = :"+k for k in list(values.keys())][1:]) 222 return ("UPDATE hive_accounts SET %s WHERE name = :name" % bind, values) 223 [end of hive/indexer/accounts.py] [start of hive/utils/account.py] 1 """Methods for normalizing/sanitizing steemd account metadata.""" 2 3 import ujson as json 4 from hive.utils.normalize import trunc 5 6 def safe_profile_metadata(account): 7 """Given an account, return sanitized profile data.""" 8 prof = {} 9 try: 10 prof = json.loads(account['json_metadata'])['profile'] 11 if not isinstance(prof, dict): 12 prof = {} 13 except Exception: 14 pass 15 16 name = str(prof['name']) if 'name' in prof else None 17 about = str(prof['about']) if 'about' in prof else None 18 location = str(prof['location']) if 'location' in prof else None 19 website = str(prof['website']) if 'website' in prof else None 20 profile_image = str(prof['profile_image']) if 'profile_image' in prof else None 21 cover_image = str(prof['cover_image']) if 'cover_image' in prof else None 22 23 name = _char_police(name) 24 about = _char_police(about) 25 location = _char_police(location) 26 27 name = trunc(name, 20) 28 about = trunc(about, 160) 29 location = trunc(location, 30) 30 31 if name and name[0:1] == '@': 32 name = None 33 if website and len(website) > 100: 34 website = None 35 if website and not _valid_url_proto(website): 36 website = 'http://' + website 37 38 if profile_image and not _valid_url_proto(profile_image): 39 profile_image = None 40 if cover_image and not _valid_url_proto(cover_image): 41 cover_image = None 42 if profile_image and len(profile_image) > 1024: 43 profile_image = None 44 if cover_image and len(cover_image) > 1024: 45 cover_image = None 46 47 return dict( 48 name=name or '', 49 about=about or '', 50 location=location or '', 51 website=website or '', 52 profile_image=profile_image or '', 53 cover_image=cover_image or '', 54 ) 55 56 def _valid_url_proto(url): 57 assert url 58 return url[0:7] == 'http://' or url[0:8] == 'https://' 59 60 def _char_police(string): 61 """If a string has bad chars, ignore it. 62 63 Unclear how a NUL would get in profile data, 64 but Postgres does not allow them in strings. 65 """ 66 if not string: 67 return None 68 if string.find('\x00') > -1: 69 return None 70 return string 71 [end of hive/utils/account.py] </code> I need you to solve this issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the following format. <patch> --- a/file.py +++ b/file.py @@ -1,27 +1,35 @@ def euclidean(a, b): - while b: - a, b = b, a % b - return a + if b == 0: + return a + return euclidean(b, a % b) def bresenham(x0, y0, x1, y1): points = [] dx = abs(x1 - x0) dy = abs(y1 - y0) - sx = 1 if x0 < x1 else -1 - sy = 1 if y0 < y1 else -1 - err = dx - dy + x, y = x0, y0 + sx = -1 if x0 > x1 else 1 + sy = -1 if y0 > y1 else 1 - while True: - points.append((x0, y0)) - if x0 == x1 and y0 == y1: - break - e2 = 2 * err - if e2 > -dy: + if dx > dy: + err = dx / 2.0 + while x != x1: + points.append((x, y)) err -= dy - x0 += sx - if e2 < dx: - err += dx - y0 += sy + if err < 0: + y += sy + err += dx + x += sx + else: + err = dy / 2.0 + while y != y1: + points.append((x, y)) + err -= dx + if err < 0: + x += sx + err += dy + y += sy + points.append((x, y)) return points </patch>
steemit/hivemind
a50ffb074b422956f9ccf79fb49eb0a8969b494e
Support for account_update2 / posting_json_metadata I broadcasted posting_json_metadata using the new account_update2 operation (https://steemd.com/@tftest1), but unlike when broadcasting json_metadata, this does not change the information that are indexed in hive_accounts
2019-09-27 17:04:29+00:00
<patch> diff --git a/hive/indexer/accounts.py b/hive/indexer/accounts.py index 3c8de1b..485320c 100644 --- a/hive/indexer/accounts.py +++ b/hive/indexer/accounts.py @@ -186,6 +186,7 @@ class Accounts: # pull out valid profile md and delete the key profile = safe_profile_metadata(account) del account['json_metadata'] + del account['posting_json_metadata'] active_at = max(account['created'], account['last_account_update'], diff --git a/hive/utils/account.py b/hive/utils/account.py index fe1302d..caf3830 100644 --- a/hive/utils/account.py +++ b/hive/utils/account.py @@ -6,12 +6,19 @@ from hive.utils.normalize import trunc def safe_profile_metadata(account): """Given an account, return sanitized profile data.""" prof = {} + try: - prof = json.loads(account['json_metadata'])['profile'] - if not isinstance(prof, dict): - prof = {} + # read from posting_json_metadata, if version==2 + prof = json.loads(account['posting_json_metadata'])['profile'] + assert isinstance(prof, dict) + assert 'version' in prof and prof['version'] == 2 except Exception: - pass + try: + # fallback to json_metadata + prof = json.loads(account['json_metadata'])['profile'] + assert isinstance(prof, dict) + except Exception: + prof = {} name = str(prof['name']) if 'name' in prof else None about = str(prof['about']) if 'about' in prof else None </patch>
diff --git a/tests/utils/test_utils_account.py b/tests/utils/test_utils_account.py index b112e11..deb0db1 100644 --- a/tests/utils/test_utils_account.py +++ b/tests/utils/test_utils_account.py @@ -11,8 +11,9 @@ def test_valid_account(): website='http://www.davincilife.com/', cover_image='https://steemitimages.com/0x0/https://pbs.twimg.com/profile_banners/816255358066946050/1483447009/1500x500', profile_image='https://www.parhlo.com/wp-content/uploads/2016/01/tmp617041537745813506.jpg', + version=2, ) - account = {'name': 'foo', 'json_metadata': json.dumps(dict(profile=raw_profile))} + account = {'name': 'foo', 'posting_json_metadata': json.dumps(dict(profile=raw_profile))} safe_profile = safe_profile_metadata(account) for key, safe_value in safe_profile.items(): @@ -26,7 +27,11 @@ def test_invalid_account(): cover_image='example.com/avatar.jpg', profile_image='https://example.com/valid-url-but-longer-than-1024-chars' + 'x' * 1024, ) - account = {'name': 'foo', 'json_metadata': json.dumps(dict(profile=raw_profile))} + ignore_prof = dict( + name='Ignore me -- missing version:2!', + ) + account = {'name': 'foo', 'json_metadata': json.dumps(dict(profile=raw_profile)), + 'posting_json_metadata': json.dumps(dict(profile=ignore_prof))} safe_profile = safe_profile_metadata(account) assert safe_profile['name'] == 'NameIsTooBigByOne...'
0.0
[ "tests/utils/test_utils_account.py::test_valid_account" ]
[ "tests/utils/test_utils_account.py::test_invalid_account" ]
a50ffb074b422956f9ccf79fb49eb0a8969b494e
streamlink__streamlink-2085
You will be provided with a partial code base and an issue statement explaining a problem to resolve. <issue> How to Stream Akamai (?) Video from Senate Foreign Relations Committee Website ## Issue <!-- Replace [ ] with [x] in order to check the box --> - [x] This is not a bug report, feature request, or plugin issue/request. - [x] I have read the contribution guidelines. ### Description I am attempting to load archived video and live video streams of the US Senate Foreign Relations Committee ([Example](https://www.foreign.senate.gov/hearings/business-meeting-082218)) in VLC via streamlink. It appears their video streaming is done via Akamai and AMP v4.90.9 from right-clicking the player embedded in provided examples. ### Expected / Actual behavior Ideally, pointing streamlink to the hearing page containing an embedded player would automagically identify available streams and open the best quality stream in VLC: `streamlink "https://www.foreign.senate.gov/hearings/business-meeting-082218" best` What actually happens is that streamlink fails with an error `error: No plugin can handle URL: https://www.foreign.senate.gov/hearings/business-meeting-082218` ### Reproduction steps / Explicit stream URLs to test I have discovered that the URL for their embedded player gets a little closer ([Example](http://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218)), but streamlink still doesn't find any streams at this URL. That is, until I replace https:// with *akamaihd://*: `streamlink "akamaihd://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218"` Results in: ```[cli][info] Found matching plugin akamaihd for URL akamaihd://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218 Available streams: live (worst, best) ``` When I specify "best" and run the command again, the result is: ```[cli][info] Found matching plugin akamaihd for URL akamaihd://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218 [cli][info] Available streams: live (worst, best) [cli][info] Opening stream: live (akamaihd) [cli][error] Try 1/1: Could not open stream <AkamaiHDStream('http://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218', swf=None)> (Could not open stream: Unable to open URL: http://www.senate.gov/isvp/ (503 Server Error: Service Unavailable for url: http://www.senate.gov/isvp/?fp=LNX+11%2C1%2C102%2C63&r=PPJRC&g=VFVQOIITOQRF&v=2.5.8)) error: Could not open stream <AkamaiHDStream('http://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218', swf=None)>, tried 1 times, exiting ``` ### Logs ``` [cli][debug] OS: macOS 10.13.6 [cli][debug] Python: 2.7.15 [cli][debug] Streamlink: 0.14.2 [cli][debug] Requests(2.19.1), Socks(1.6.7), Websocket(0.48.0) [cli][info] Found matching plugin akamaihd for URL akamaihd://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218 [plugin.akamaihd][debug] URL=http://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218; params={} [cli][info] Available streams: live (worst, best) [cli][info] Opening stream: live (akamaihd) [stream.akamaihd][debug] Opening host=http://www.senate.gov streamname=isvp/ [cli][error] Try 1/1: Could not open stream <AkamaiHDStream('http://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218', swf=None)> (Could not open stream: Unable to open URL: http://www.senate.gov/isvp/ (503 Server Error: Service Unavailable for url: http://www.senate.gov/isvp/?fp=LNX+11%2C1%2C102%2C63&r=VREJP&g=JOHWJGPLHFNA&v=2.5.8)) error: Could not open stream <AkamaiHDStream('http://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218', swf=None)>, tried 1 times, exiting ``` ### Additional comments, screenshots, etc. It appears the Senate Foreign Relations Committee uses the date of the hearing as the main reference ID. Since the committee only meets once a day, there's only ever one stream on any given day. There's possibly useful information in the source of each player page. In the source code for the example link I've used above, there's this snippet: ``` <a id="watch-live-now" class="small btn" href="javascript:openVideoWin('/hearings/watch?hearingid=AA0FF459-5056-A066-60A0-8B11F704E85E');">Open New Window</a> ``` Also, from the source code the video player code can have a lot of parameters specified: ``` https://www.senate.gov/isvp/?comm=foreign&type=arch&stt=21:50&filename=foreign082218&auto_play=false&wmode=transparent&poster=https%3A%2F%2Fwww%2Eforeign%2Esenate%2Egov%2Fthemes%2Fforeign%2Fimages%2Fvideo%2Dposter%2Dflash%2Dfit%2Epng ``` [Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate) </issue> <code> [start of README.md] 1 # [Streamlink][streamlink-website] 2 3 [![TravisCI build status][travisci-build-status-badge]][travisci-build-status] 4 [![codecov.io][codecov-coverage-badge]][codecov-coverage] [![Backers on Open Collective][opencollective-backers-badge]](#backers) [![Sponsors on Open Collective][opencollective-sponsors-badge]](#sponsors) 5 6 Streamlink is a CLI utility that pipes flash videos from online streaming services to a variety of video players such as VLC. 7 8 The main purpose of streamlink is to convert CPU-heavy flash plugins to a less CPU-intensive format. 9 10 Streamlink is a fork of the [Livestreamer][livestreamer] project. 11 12 Please note that by using this application you're bypassing ads run by 13 sites such as Twitch.tv. Please consider donating or paying for subscription 14 services when they are available for the content you consume and enjoy. 15 16 17 # [Installation][streamlink-installation] 18 19 #### Installation via Python pip 20 21 ```bash 22 sudo pip install streamlink 23 ``` 24 25 #### Manual installation via Python 26 27 ```bash 28 git clone https://github.com/streamlink/streamlink 29 cd streamlink 30 sudo python setup.py install 31 ``` 32 33 #### Windows, MacOS, Linux and BSD specific installation methods 34 35 - [Windows][streamlink-installation-windows] 36 - [Windows portable version][streamlink-installation-windows-portable] 37 - [MacOS][streamlink-installation-others] 38 - [Linux and BSD][streamlink-installation-linux] 39 40 41 # Features 42 43 Streamlink is built via a plugin system which allows new services to be easily added. 44 45 Supported streaming services, among many others, are: 46 47 - [Dailymotion](https://www.dailymotion.com) 48 - [Livestream](https://livestream.com) 49 - [Twitch](https://www.twitch.tv) 50 - [UStream](http://www.ustream.tv/explore/all) 51 - [YouTube](https://www.youtube.com) 52 53 A list of all supported plugins can be found on the [plugin page][streamlink-plugins]. 54 55 56 # Quickstart 57 58 After installing, simply use: 59 60 ``` 61 streamlink STREAMURL best 62 ``` 63 64 Streamlink will automatically open the stream in its default video player! 65 See [Streamlink's detailed documentation][streamlink-documentation] for all available configuration options, CLI parameters and usage examples. 66 67 68 # Contributing 69 70 All contributions are welcome. 71 Feel free to open a new thread on the issue tracker or submit a new pull request. 72 Please read [CONTRIBUTING.md][contributing] first. Thanks! 73 74 [![Contributors][opencollective-contributors]][contributors] 75 76 77 ## Backers 78 79 Thank you to all our backers! \[[Become a backer][opencollective-backer]\] 80 81 [![Backers on Open Collective][opencollective-backers-image]][opencollective-backers] 82 83 84 ## Sponsors 85 86 Support this project by becoming a sponsor. Your logo will show up here with a link to your website. \[[Become a sponsor][opencollective-sponsor]\] 87 88 [![Open Collective Streamlink Sponsor](https://opencollective.com/streamlink/sponsor/0/avatar.svg)](https://opencollective.com/streamlink/sponsor/0/website) 89 [![Open Collective Streamlink Sponsor](https://opencollective.com/streamlink/sponsor/1/avatar.svg)](https://opencollective.com/streamlink/sponsor/1/website) 90 [![Open Collective Streamlink Sponsor](https://opencollective.com/streamlink/sponsor/2/avatar.svg)](https://opencollective.com/streamlink/sponsor/2/website) 91 [![Open Collective Streamlink Sponsor](https://opencollective.com/streamlink/sponsor/3/avatar.svg)](https://opencollective.com/streamlink/sponsor/3/website) 92 [![Open Collective Streamlink Sponsor](https://opencollective.com/streamlink/sponsor/4/avatar.svg)](https://opencollective.com/streamlink/sponsor/4/website) 93 [![Open Collective Streamlink Sponsor](https://opencollective.com/streamlink/sponsor/5/avatar.svg)](https://opencollective.com/streamlink/sponsor/5/website) 94 [![Open Collective Streamlink Sponsor](https://opencollective.com/streamlink/sponsor/6/avatar.svg)](https://opencollective.com/streamlink/sponsor/6/website) 95 [![Open Collective Streamlink Sponsor](https://opencollective.com/streamlink/sponsor/7/avatar.svg)](https://opencollective.com/streamlink/sponsor/7/website) 96 [![Open Collective Streamlink Sponsor](https://opencollective.com/streamlink/sponsor/8/avatar.svg)](https://opencollective.com/streamlink/sponsor/8/website) 97 [![Open Collective Streamlink Sponsor](https://opencollective.com/streamlink/sponsor/9/avatar.svg)](https://opencollective.com/streamlink/sponsor/9/website) 98 99 100 [streamlink-website]: https://streamlink.github.io 101 [streamlink-plugins]: https://streamlink.github.io/plugin_matrix.html 102 [streamlink-documentation]: https://streamlink.github.io/cli.html 103 [streamlink-installation]: https://streamlink.github.io/install.html 104 [streamlink-installation-windows]: https://streamlink.github.io/install.html#windows-binaries 105 [streamlink-installation-windows-portable]: https://streamlink.github.io/install.html#windows-portable-version 106 [streamlink-installation-linux]: https://streamlink.github.io/install.html#linux-and-bsd-packages 107 [streamlink-installation-others]: https://streamlink.github.io/install.html#other-platforms 108 [livestreamer]: https://github.com/chrippa/livestreamer 109 [contributing]: https://github.com/streamlink/streamlink/blob/master/CONTRIBUTING.md 110 [changelog]: https://github.com/streamlink/streamlink/blob/master/CHANGELOG.rst 111 [contributors]: https://github.com/streamlink/streamlink/graphs/contributors 112 [travisci-build-status]: https://travis-ci.org/streamlink/streamlink 113 [travisci-build-status-badge]: https://travis-ci.org/streamlink/streamlink.svg?branch=master 114 [codecov-coverage]: https://codecov.io/github/streamlink/streamlink?branch=master 115 [codecov-coverage-badge]: https://codecov.io/github/streamlink/streamlink/coverage.svg?branch=master 116 [opencollective-contributors]: https://opencollective.com/streamlink/contributors.svg?width=890 117 [opencollective-backer]: https://opencollective.com/streamlink#backer 118 [opencollective-backers]: https://opencollective.com/streamlink#backers 119 [opencollective-backers-image]: https://opencollective.com/streamlink/backers.svg?width=890 120 [opencollective-sponsor]: https://opencollective.com/streamlink#sponsor 121 [opencollective-backers-badge]: https://opencollective.com/streamlink/backers/badge.svg 122 [opencollective-sponsors-badge]: https://opencollective.com/streamlink/sponsors/badge.svg 123 [end of README.md] [start of /dev/null] 1 [end of /dev/null] [start of docs/plugin_matrix.rst] 1 .. _plugin_matrix: 2 3 4 Plugins 5 ======= 6 7 This is a list of the currently built in plugins and what URLs and features 8 they support. Streamlink's primary focus is live streams, so VOD support 9 is limited. 10 11 12 ======================= ==================== ===== ===== =========================== 13 Name URL(s) Live VOD Notes 14 ======================= ==================== ===== ===== =========================== 15 abematv abema.tv Yes Yes Streams are geo-restricted to Japan. 16 abweb abweb.com Yes No Requires a login and a subscription. 17 adultswim adultswim.com Yes Yes Streams may be geo-restricted, some VOD streams are protected by DRM. 18 afreeca - afreecatv.com Yes No 19 - afreeca.tv 20 aljazeeraen aljazeera.com Yes Yes English version of the site. 21 animelab animelab.com -- Yes Requires a login. Streams may be geo-restricted to Australia and New Zealand. 22 app17 17app.co Yes -- 23 ard_live daserste.de Yes Yes Streams may be geo-restricted to Germany. 24 ard_mediathek - ardmediathek.de Yes Yes Streams may be geo-restricted to Germany. 25 - mediathek... [5]_ 26 artetv arte.tv Yes Yes 27 atresplayer atresplayer.com Yes No Streams are geo-restricted to Spain. 28 bbciplayer bbc.co.uk/iplayer Yes Yes Streams may be geo-restricted to the United Kingdom. 29 beattv be-at.tv Yes Yes Playlist not implemented yet. 30 bfmtv bfmtv.com Yes Yes 31 01net.com 32 bigo - live.bigo.tv Yes -- 33 - bigoweb.co 34 bilibili live.bilibili.com Yes ? 35 bloomberg bloomberg.com Yes Yes 36 brightcove players.brig... [6]_ Yes Yes 37 btsports sport.bt.com Yes Yes Requires subscription account 38 btv btv.bg Yes No Requires login, and geo-restricted to Bulgaria. 39 canalplus mycanal.fr No Yes Streams may be geo-restricted to France. 40 cdnbg - tv.bnt.bg Yes No Streams may be geo-restricted to Bulgaria. 41 - bgonair.bg 42 - kanal3.bg 43 - bitelevision.com 44 - nova.bg 45 ceskatelevize ceskatelevize.cz Yes Yes Streams may be geo-restricted to Czechia. 46 cinergroup - showtv.com.tr Yes No 47 - haberturk.com 48 - showmax.com.tr 49 - showturk.com.tr 50 - bloomberght.com 51 cnews cnews.fr Yes Yes 52 crunchyroll crunchyroll.com -- Yes 53 cybergame cybergame.tv Yes Yes 54 dailymotion dailymotion.com Yes Yes 55 delfi - delfi.lt -- Yes 56 - delfi.ee 57 - delfi.lv 58 deutschewelle dw.com Yes Yes 59 dingittv dingit.tv Yes Yes 60 dogan - teve2.com.tr Yes Yes VOD is supported for teve2 and kanald 61 - kanald.com.tr 62 - dreamtv.com.tr 63 - cnnturk.com 64 - dreamturk.com.tr 65 dogus - ntvspor.net Yes No 66 - kralmuzik.com.tr 67 - ntv.com.tr 68 - eurostartv.com.tr 69 dommune dommune.com Yes -- 70 douyutv - douyu.com Yes Yes 71 - v.douyu.com 72 drdk dr.dk Yes Yes Streams may be geo-restricted to Denmark. 73 earthcam earthcam.com Yes Yes Only works for the cams hosted on EarthCam. 74 egame egame.qq.com Yes No 75 ellobo ellobo106.com Yes - 76 eltrecetv eltrecetv.com.ar Yes Yes Streams may be geo-restricted to Argentina. 77 eurocom eurocom.bg Yes No 78 euronews euronews.com Yes No 79 europaplus europaplus.ru Yes -- 80 facebook facebook.com Yes No Only 360p HLS streams. 81 filmon filmon.com Yes Yes Only SD quality streams. 82 foxtr fox.com.tr Yes No 83 funimationnow - funimation.com -- Yes 84 - funimationnow.uk 85 gardenersworld gardenersworld.com -- Yes 86 garena garena.live Yes -- 87 goltelevision goltelevision.com Yes No Streams may be geo-restricted to Spain. 88 goodgame goodgame.ru Yes No Only HLS streams are available. 89 googledrive - docs.google.com -- Yes 90 - drive.google.com 91 gulli replay.gulli.fr Yes Yes Streams may be geo-restricted to France. 92 hitbox - hitbox.tv Yes Yes 93 - smashcast.tv 94 huajiao huajiao.com Yes No 95 huomao huomao.com Yes No 96 huya huya.com Yes No Temporarily only HLS streams available. 97 idf1 idf1.fr Yes Yes 98 ine ine.com --- Yes 99 itvplayer itv.com/itvplayer Yes Yes Streams may be geo-restricted to Great Britain. 100 kanal7 kanal7.com Yes No 101 kingkong kingkong.com.tw Yes -- 102 live_russia_tv live.russia.tv Yes -- 103 liveedu - liveedu.tv Yes -- Some streams require a login. 104 - livecoding.tv 105 liveme liveme.com Yes -- 106 livestream new.livestream.com Yes -- 107 lrt lrt.lt Yes No 108 ltv_lsm_lv ltv.lsm.lv Yes No Streams may be geo-restricted to Latvia. 109 mediaklikk mediaklikk.hu Yes No Streams may be geo-restricted to Hungary. 110 mitele mitele.es Yes No Streams may be geo-restricted to Spain. 111 mixer mixer.com Yes Yes 112 mjunoon mjunoon.tv Yes Yes 113 mlgtv mlg.tv Yes -- 114 nbc nbc.com No Yes Streams are geo-restricted to USA. Authentication is not supported. 115 nbcsports nbcsports.com No Yes Streams maybe be geo-restricted to USA. Authentication is not supported. 116 nhkworld nhk.or.jp/nhkworld Yes No 117 nos nos.nl Yes Yes Streams may be geo-restricted to Netherlands. 118 npo - npo.nl Yes Yes Streams may be geo-restricted to Netherlands. 119 - zapp.nl 120 - zappelin.nl 121 nrk - tv.nrk.no Yes Yes Streams may be geo-restricted to Norway. 122 - radio.nrk.no 123 ok_live ok.ru Yes -- 124 olympicchannel olympicchannel.com Yes Yes Only non-premium content is available. 125 onetv - 1tv.ru Yes Yes Streams may be geo-restricted to Russia. VOD only for 1tv.ru 126 - ctc.ru 127 - chetv.ru 128 - ctclove.ru 129 - domashny.ru 130 openrectv openrec.tv Yes Yes 131 orf_tvthek tvthek.orf.at Yes Yes 132 ovvatv ovva.tv Yes No 133 pandatv panda.tv Yes ? 134 periscope periscope.tv Yes Yes Replay/VOD is supported. 135 picarto picarto.tv Yes Yes 136 piczel piczel.tv Yes No 137 pixiv sketch.pixiv.net Yes -- 138 playtv - playtv.fr Yes -- Streams may be geo-restricted to France. 139 - play.tv 140 pluzz - france.tv Yes Yes Streams may be geo-restricted to France, Andorra and Monaco. 141 - ludo.fr 142 - zouzous.fr 143 - france3-reg.. [8]_ 144 powerapp powerapp.com.tr Yes No 145 qq live.qq.com Yes No 146 radionet - radio.net Yes -- 147 - radio.at 148 - radio.de 149 - radio.dk 150 - radio.es 151 - radio.fr 152 - radio.it 153 - radio.pl 154 - radio.pt 155 - radio.se 156 raiplay raiplay.it Yes No Most streams are geo-restricted to Italy. 157 reshet reshet.tv Yes Yes Streams may be geo-restricted to Israel. 158 rtbf - rtbf.be/auvio Yes Yes Streams may be geo-restricted to Belgium or Europe. 159 - rtbfradioplayer.be 160 rtlxl rtlxl.nl No Yes Streams may be geo-restricted to The Netherlands. Livestreams not supported. 161 rte rte.ie/player Yes Yes 162 rtpplay rtp.pt/play Yes Yes Streams may be geo-restricted to Portugal. 163 rtve rtve.es Yes No 164 rtvs rtvs.sk Yes No Streams may be geo-restricted to Slovakia. 165 ruv ruv.is Yes Yes Streams may be geo-restricted to Iceland. 166 schoolism schoolism.com -- Yes Requires a login and a subscription. 167 showroom showroom-live.com Yes No Only RTMP streams are available. 168 skai skai.gr Yes No Only embedded youtube live streams are supported 169 sportal sportal.bg Yes No 170 sportschau sportschau.de Yes No 171 srgssr - srf.ch Yes No Streams are geo-restricted to Switzerland. 172 - rts.ch 173 - rsi.ch 174 - rtr.ch 175 ssh101 ssh101.com Yes No 176 startv startv.com.tr Yes No 177 steam steamcommunity.com Yes No Some streams will require a Steam account. 178 streamable streamable.com - Yes 179 streamingvideoprovider streamingvid... [2]_ Yes -- RTMP streams requires rtmpdump with 180 K-S-V patches. 181 streamme stream.me Yes -- 182 streann ott.streann.com Yes Yes 183 svtplay - svtplay.se Yes Yes Streams may be geo-restricted to Sweden. 184 - svtflow.se 185 - oppetarkiv.se 186 swisstxt - srf.ch Yes No Streams are geo-restricted to Switzerland. 187 - rsi.ch 188 teamliquid teamliquid.net Yes Yes 189 teleclubzoom teleclubzoom.ch Yes No Streams are geo-restricted to Switzerland. 190 telefe telefe.com No Yes Streams are geo-restricted to Argentina. 191 tf1 - tf1.fr Yes No Streams may be geo-restricted to France. 192 - lci.fr 193 tga - star.plu.cn Yes No 194 - star.tga.plu.cn 195 - star.longzhu.com 196 theplatform player.thepl... [7]_ No Yes 197 tigerdile tigerdile.com Yes -- 198 tlctr tlctv.com.tr Yes No 199 trt trt.net.tr Yes No Some streams may be geo-restricted to Turkey. 200 trtspor trtspor.com Yes No Some streams are geo-restricted to Turkey. 201 turkuvaz - atv.com.tr Yes No 202 - a2tv.com.tr 203 - ahaber.com.tr 204 - aspor.com.tr 205 - minikago.com.tr 206 - minikacocuk.com.tr 207 tv1channel tv1channel.org Yes Yes 208 tv3cat tv3.cat Yes Yes Streams may be geo-restricted to Spain. 209 tv4play - tv4play.se Yes Yes Streams may be geo-restricted to Sweden. 210 Only non-premium streams currently supported. 211 - fotbollskanalen.se 212 tv5monde - tv5monde.com Yes Yes Streams may be geo-restricted to France, Belgium and Switzerland. 213 - tv5mondeplus.com 214 - tv5mondepl... [9]_ 215 tv8 tv8.com.tr Yes No 216 tv360 tv360.com.tr Yes No 217 tvcatchup tvcatchup.com Yes No Streams may be geo-restricted to Great Britain. 218 tvnbg - tvn.bg Yes - 219 - live.tvn.bg 220 tvp tvpstream.vod.tvp.pl Yes No Streams may be geo-restricted to Poland. 221 tvplayer tvplayer.com Yes No Streams may be geo-restricted to Great Britain. Premium streams are not supported. 222 tvrby tvr.by Yes No Streams may be geo-restricted to Belarus. 223 tvrplus tvrplus.ro Yes No Streams may be geo-restricted to Romania. 224 tvtoya tvtoya.pl Yes -- 225 twitch twitch.tv Yes Yes Possible to authenticate for access to 226 subscription streams. 227 ustreamtv ustream.tv Yes Yes 228 ustvnow ustvnow.com Yes -- All streams require an account, some streams require a subscription. 229 vaughnlive - vaughnlive.tv Yes -- 230 - breakers.tv 231 - instagib.tv 232 - vapers.tv 233 viasat - juicyplay.dk Yes Yes Streams may be geo-restricted. 234 - play.nova.bg 235 - skaties.lv 236 - tv3.dk 237 - tv3.ee 238 - tv3.lt 239 - tv6play.no 240 - viafree.dk 241 - viafree.no 242 - viafree.se 243 vidio vidio.com Yes Yes 244 vinhlongtv thvli.vn Yes No Streams are geo-restricted to Vietnam 245 vk vk.com Yes Yes 246 vrtbe vrt.be/vrtnu Yes Yes 247 webcast_india_gov webcast.gov.in Yes No You can use #Channel to indicate CH number. 248 webtv web.tv Yes -- 249 welt welt.de Yes Yes Streams may be geo-restricted to Germany. 250 wwenetwork network.wwe.com Yes Yes Requires an account to access any content. 251 younow younow.com Yes -- 252 youtube - youtube.com Yes Yes Protected videos are not supported. 253 - youtu.be 254 yupptv yupptv.com Yes Yes Some streams require an account and subscription. 255 zattoo - zattoo.com Yes Yes 256 - nettv.net... [10]_ 257 - tvonline.ewe.de 258 - iptv.glat... [11]_ 259 - mobiltv.q... [12]_ 260 - player.waly.tv 261 - tvplus.m-net.de 262 - www.bbv-tv.net 263 - www.meinewelt.cc 264 - www.myvisiontv.ch 265 - www.netplus.tv 266 - www.quantum-tv.com 267 - www.saktv.ch 268 - www.vtxtv.ch 269 zdf_mediathek zdf.de Yes Yes Streams may be geo-restricted to Germany. 270 zengatv zengatv.com Yes No 271 zhanqi zhanqi.tv Yes No 272 ======================= ==================== ===== ===== =========================== 273 274 275 .. [2] streamingvideoprovider.co.uk 276 .. [5] mediathek.daserste.de 277 .. [6] players.brightcove.net 278 .. [7] player.theplatform.com 279 .. [8] france3-regions.francetvinfo.fr 280 .. [9] tv5mondeplusafrique.com 281 .. [10] nettv.netcologne.de 282 .. [11] iptv.glattvision.ch 283 .. [12] mobiltv.quickline.com 284 [end of docs/plugin_matrix.rst] </code> I need you to solve this issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the following format. <patch> --- a/file.py +++ b/file.py @@ -1,27 +1,35 @@ def euclidean(a, b): - while b: - a, b = b, a % b - return a + if b == 0: + return a + return euclidean(b, a % b) def bresenham(x0, y0, x1, y1): points = [] dx = abs(x1 - x0) dy = abs(y1 - y0) - sx = 1 if x0 < x1 else -1 - sy = 1 if y0 < y1 else -1 - err = dx - dy + x, y = x0, y0 + sx = -1 if x0 > x1 else 1 + sy = -1 if y0 > y1 else 1 - while True: - points.append((x0, y0)) - if x0 == x1 and y0 == y1: - break - e2 = 2 * err - if e2 > -dy: + if dx > dy: + err = dx / 2.0 + while x != x1: + points.append((x, y)) err -= dy - x0 += sx - if e2 < dx: - err += dx - y0 += sy + if err < 0: + y += sy + err += dx + x += sx + else: + err = dy / 2.0 + while y != y1: + points.append((x, y)) + err -= dx + if err < 0: + x += sx + err += dy + y += sy + points.append((x, y)) return points </patch>
streamlink/streamlink
4e4a5a97b5eed3ddc11d11daf8368b6317695858
How to Stream Akamai (?) Video from Senate Foreign Relations Committee Website ## Issue <!-- Replace [ ] with [x] in order to check the box --> - [x] This is not a bug report, feature request, or plugin issue/request. - [x] I have read the contribution guidelines. ### Description I am attempting to load archived video and live video streams of the US Senate Foreign Relations Committee ([Example](https://www.foreign.senate.gov/hearings/business-meeting-082218)) in VLC via streamlink. It appears their video streaming is done via Akamai and AMP v4.90.9 from right-clicking the player embedded in provided examples. ### Expected / Actual behavior Ideally, pointing streamlink to the hearing page containing an embedded player would automagically identify available streams and open the best quality stream in VLC: `streamlink "https://www.foreign.senate.gov/hearings/business-meeting-082218" best` What actually happens is that streamlink fails with an error `error: No plugin can handle URL: https://www.foreign.senate.gov/hearings/business-meeting-082218` ### Reproduction steps / Explicit stream URLs to test I have discovered that the URL for their embedded player gets a little closer ([Example](http://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218)), but streamlink still doesn't find any streams at this URL. That is, until I replace https:// with *akamaihd://*: `streamlink "akamaihd://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218"` Results in: ```[cli][info] Found matching plugin akamaihd for URL akamaihd://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218 Available streams: live (worst, best) ``` When I specify "best" and run the command again, the result is: ```[cli][info] Found matching plugin akamaihd for URL akamaihd://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218 [cli][info] Available streams: live (worst, best) [cli][info] Opening stream: live (akamaihd) [cli][error] Try 1/1: Could not open stream <AkamaiHDStream('http://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218', swf=None)> (Could not open stream: Unable to open URL: http://www.senate.gov/isvp/ (503 Server Error: Service Unavailable for url: http://www.senate.gov/isvp/?fp=LNX+11%2C1%2C102%2C63&r=PPJRC&g=VFVQOIITOQRF&v=2.5.8)) error: Could not open stream <AkamaiHDStream('http://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218', swf=None)>, tried 1 times, exiting ``` ### Logs ``` [cli][debug] OS: macOS 10.13.6 [cli][debug] Python: 2.7.15 [cli][debug] Streamlink: 0.14.2 [cli][debug] Requests(2.19.1), Socks(1.6.7), Websocket(0.48.0) [cli][info] Found matching plugin akamaihd for URL akamaihd://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218 [plugin.akamaihd][debug] URL=http://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218; params={} [cli][info] Available streams: live (worst, best) [cli][info] Opening stream: live (akamaihd) [stream.akamaihd][debug] Opening host=http://www.senate.gov streamname=isvp/ [cli][error] Try 1/1: Could not open stream <AkamaiHDStream('http://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218', swf=None)> (Could not open stream: Unable to open URL: http://www.senate.gov/isvp/ (503 Server Error: Service Unavailable for url: http://www.senate.gov/isvp/?fp=LNX+11%2C1%2C102%2C63&r=VREJP&g=JOHWJGPLHFNA&v=2.5.8)) error: Could not open stream <AkamaiHDStream('http://www.senate.gov/isvp/?comm=foreign&type=live&filename=foreign082218', swf=None)>, tried 1 times, exiting ``` ### Additional comments, screenshots, etc. It appears the Senate Foreign Relations Committee uses the date of the hearing as the main reference ID. Since the committee only meets once a day, there's only ever one stream on any given day. There's possibly useful information in the source of each player page. In the source code for the example link I've used above, there's this snippet: ``` <a id="watch-live-now" class="small btn" href="javascript:openVideoWin('/hearings/watch?hearingid=AA0FF459-5056-A066-60A0-8B11F704E85E');">Open New Window</a> ``` Also, from the source code the video player code can have a lot of parameters specified: ``` https://www.senate.gov/isvp/?comm=foreign&type=arch&stt=21:50&filename=foreign082218&auto_play=false&wmode=transparent&poster=https%3A%2F%2Fwww%2Eforeign%2Esenate%2Egov%2Fthemes%2Fforeign%2Fimages%2Fvideo%2Dposter%2Dflash%2Dfit%2Epng ``` [Love Streamlink? Please consider supporting our collective. Thanks!](https://opencollective.com/streamlink/donate)
2018-10-02 13:49:25+00:00
<patch> diff --git a/docs/plugin_matrix.rst b/docs/plugin_matrix.rst index 0bb62885..5f27e220 100644 --- a/docs/plugin_matrix.rst +++ b/docs/plugin_matrix.rst @@ -164,6 +164,7 @@ rtve rtve.es Yes No rtvs rtvs.sk Yes No Streams may be geo-restricted to Slovakia. ruv ruv.is Yes Yes Streams may be geo-restricted to Iceland. schoolism schoolism.com -- Yes Requires a login and a subscription. +senategov senate.gov -- Yes Supports hearing streams. showroom showroom-live.com Yes No Only RTMP streams are available. skai skai.gr Yes No Only embedded youtube live streams are supported sportal sportal.bg Yes No diff --git a/src/streamlink/plugins/senategov.py b/src/streamlink/plugins/senategov.py new file mode 100644 index 00000000..2942b288 --- /dev/null +++ b/src/streamlink/plugins/senategov.py @@ -0,0 +1,113 @@ +import re +import logging + +from streamlink.plugin import Plugin +from streamlink.plugin.api import useragents +from streamlink.plugin.api.utils import itertags +from streamlink.stream import HLSStream +from streamlink.utils import parse_json +from streamlink.compat import urlparse, parse_qsl +from streamlink.utils.times import hours_minutes_seconds + +log = logging.getLogger(__name__) + + +class SenateGov(Plugin): + url_re = re.compile(r"""https?://(?:.+\.)?senate\.gov/(isvp)?""") + streaminfo_re = re.compile(r"""var\s+streamInfo\s+=\s+new\s+Array\s*\(\s*(\[.*\])\);""") + stt_re = re.compile(r"""^(?:(?P<hours>\d+):)?(?P<minutes>\d+):(?P<seconds>\d+)$""") + url_lookup = { + "ag": ["76440", "https://ag-f.akamaihd.net"], + "aging": ["76442", "https://aging-f.akamaihd.net"], + "approps": ["76441", "https://approps-f.akamaihd.net"], + "armed": ["76445", "https://armed-f.akamaihd.net"], + "banking": ["76446", "https://banking-f.akamaihd.net"], + "budget": ["76447", "https://budget-f.akamaihd.net"], + "cecc": ["76486", "https://srs-f.akamaihd.net"], + "commerce": ["80177", "https://commerce1-f.akamaihd.net"], + "csce": ["75229", "https://srs-f.akamaihd.net"], + "dpc": ["76590", "https://dpc-f.akamaihd.net"], + "energy": ["76448", "https://energy-f.akamaihd.net"], + "epw": ["76478", "https://epw-f.akamaihd.net"], + "ethics": ["76449", "https://ethics-f.akamaihd.net"], + "finance": ["76450", "https://finance-f.akamaihd.net"], + "foreign": ["76451", "https://foreign-f.akamaihd.net"], + "govtaff": ["76453", "https://govtaff-f.akamaihd.net"], + "help": ["76452", "https://help-f.akamaihd.net"], + "indian": ["76455", "https://indian-f.akamaihd.net"], + "intel": ["76456", "https://intel-f.akamaihd.net"], + "intlnarc": ["76457", "https://intlnarc-f.akamaihd.net"], + "jccic": ["85180", "https://jccic-f.akamaihd.net"], + "jec": ["76458", "https://jec-f.akamaihd.net"], + "judiciary": ["76459", "https://judiciary-f.akamaihd.net"], + "rpc": ["76591", "https://rpc-f.akamaihd.net"], + "rules": ["76460", "https://rules-f.akamaihd.net"], + "saa": ["76489", "https://srs-f.akamaihd.net"], + "smbiz": ["76461", "https://smbiz-f.akamaihd.net"], + "srs": ["75229", "https://srs-f.akamaihd.net"], + "uscc": ["76487", "https://srs-f.akamaihd.net"], + "vetaff": ["76462", "https://vetaff-f.akamaihd.net"], + } + + hls_url = "{base}/i/{filename}_1@{number}/master.m3u8?" + hlsarch_url = "https://ussenate-f.akamaihd.net/i/{filename}.mp4/master.m3u8" + + @classmethod + def can_handle_url(cls, url): + return cls.url_re.match(url) is not None + + def _isvp_to_m3u8(self, url): + qs = dict(parse_qsl(urlparse(url).query)) + if "comm" not in qs: + log.error("Missing `comm` value") + if "filename" not in qs: + log.error("Missing `filename` value") + + d = self.url_lookup.get(qs['comm']) + if d: + snumber, baseurl = d + stream_url = self.hls_url.format(filename=qs['filename'], number=snumber, base=baseurl) + else: + stream_url = self.hlsarch_url.format(filename=qs['filename']) + + return stream_url, self.parse_stt(qs.get('stt', 0)) + + def _get_streams(self): + self.session.http.headers.update({ + "User-Agent": useragents.CHROME, + }) + m = self.url_re.match(self.url) + if m and not m.group(1): + log.debug("Searching for ISVP URL") + isvp_url = self._get_isvp_url() + else: + isvp_url = self.url + + if not isvp_url: + log.error("Could not find the ISVP URL") + return + else: + log.debug("ISVP URL: {0}".format(isvp_url)) + + stream_url, start_offset = self._isvp_to_m3u8(isvp_url) + log.debug("Start offset is: {0}s".format(start_offset)) + return HLSStream.parse_variant_playlist(self.session, stream_url, start_offset=start_offset) + + def _get_isvp_url(self): + res = self.session.http.get(self.url) + for iframe in itertags(res.text, 'iframe'): + m = self.url_re.match(iframe.attributes.get('src')) + return m and m.group(1) is not None and iframe.attributes.get('src') + + @classmethod + def parse_stt(cls, param): + m = cls.stt_re.match(param) + if m: + return int(m.group('hours') or 0) * 3600 + \ + int(m.group('minutes')) * 60 + \ + int(m.group('seconds')) + else: + return 0 + + +__plugin__ = SenateGov </patch>
diff --git a/tests/plugins/test_senategov.py b/tests/plugins/test_senategov.py new file mode 100644 index 00000000..6fb5eda8 --- /dev/null +++ b/tests/plugins/test_senategov.py @@ -0,0 +1,18 @@ +from streamlink.plugins.senategov import SenateGov +import unittest + + +class TestPluginSenateGov(unittest.TestCase): + def test_can_handle_url(self): + # should match + self.assertTrue(SenateGov.can_handle_url("https://www.foreign.senate.gov/hearings/business-meeting-082218")) + self.assertTrue(SenateGov.can_handle_url("https://www.senate.gov/isvp/?comm=foreign&type=arch&stt=21:50&filename=foreign082218&auto_play=false&wmode=transparent&poster=https%3A%2F%2Fwww%2Eforeign%2Esenate%2Egov%2Fthemes%2Fforeign%2Fimages%2Fvideo-poster-flash-fit%2Epng")) + + # shouldn't match + self.assertFalse(SenateGov.can_handle_url("http://www.tvcatchup.com/")) + self.assertFalse(SenateGov.can_handle_url("http://www.youtube.com/")) + + def test_stt_parse(self): + self.assertEqual(600, SenateGov.parse_stt("10:00")) + self.assertEqual(3600, SenateGov.parse_stt("01:00:00")) + self.assertEqual(70, SenateGov.parse_stt("1:10"))
0.0
[ "tests/plugins/test_senategov.py::TestPluginSenateGov::test_can_handle_url", "tests/plugins/test_senategov.py::TestPluginSenateGov::test_stt_parse" ]
[]
4e4a5a97b5eed3ddc11d11daf8368b6317695858
coverahealth__dataspec-15
You will be provided with a partial code base and an issue statement explaining a problem to resolve. <issue> Support email address string format Applications commonly need to validate that an email address is at least in a valid format. Python features the [`email.headerregistry.Address`](https://docs.python.org/3/library/email.headerregistry.html#email.headerregistry.Address) object which parses email address strings and can provide some reasonable hints about formatting errors. It may not be foolproof, but for common cases it is probably sufficient. </issue> <code> [start of README.md] 1 # Data Spec 2 3 [![PyPI](https://img.shields.io/pypi/v/dataspec.svg?style=flat-square)](https://pypi.org/project/dataspec/) [![python](https://img.shields.io/pypi/pyversions/dataspec.svg?style=flat-square)](https://pypi.org/project/dataspec/) [![pyimpl](https://img.shields.io/pypi/implementation/dataspec.svg?style=flat-square)](https://pypi.org/project/dataspec/) [![CircleCI]( https://img.shields.io/circleci/project/github/coverahealth/dataspec/master.svg?style=flat-square)](https://circleci.com/gh/coverahealth/dataspec) [![license](https://img.shields.io/github/license/coverahealth/dataspec.svg?style=flat-square)](https://github.com/coverahealth/dataspec/blob/master/LICENSE) 4 5 ## What are Specs? 6 7 Specs are declarative data specifications written in pure Python code. Specs can be 8 created using the Spec utility function `s`. Specs provide two useful and related 9 functions. The first is to evaluate whether an arbitrary data structure satisfies 10 the specification. The second function is to conform (or normalize) valid data 11 structures into a canonical format. 12 13 The simplest Specs are based on common predicate functions, such as 14 `lambda x: isinstance(x, str)` which asks "Is the object x an instance of `str`?". 15 Fortunately, Specs are not limited to being created from single predicates. Specs can 16 also be created from groups of predicates, composed in a variety of useful ways, and 17 even defined for complex data structures. Because Specs are ultimately backed by 18 pure Python code, any question that you can answer about your data in code can be 19 encoded in a Spec. 20 21 ## How to Use 22 23 To begin using the `spec` library, you can simply import the `s` object: 24 25 ```python 26 from dataspec import s 27 ``` 28 29 Nearly all of the useful functionality in `spec` is packed into `s`. 30 31 ### Spec API 32 33 `s` is a generic Spec constructor, which can be called to generate new Specs from 34 a variety of sources: 35 36 * Enumeration specs: 37 * Using a Python `set` or `frozenset`: `s({"a", "b", ...})`, or 38 * Using a Python `Enum` like `State`, `s(State)`. 39 * Collection specs: 40 * Using a Python `list`: `s([State])` 41 * Mapping type specs: 42 * Using a Python `dict`: `s({"name": s.is_str})` 43 * Tuple type specs: 44 * Using a Python `tuple`: `s((s.is_str, s.is_num))` 45 * Specs based on: 46 * Using a standard Python predicate: `s(lambda x: x > 0)` 47 * Using a Python function yielding `ErrorDetails` 48 49 Specs are designed to be composed, so each of the above spec types can serve as the 50 base for more complex data definitions. For collection, mapping, and tuple type Specs, 51 Specs will be recursively created for child elements if they are types understood 52 by `s`. 53 54 Specs may also optionally be created with "tags", which are just string names provided 55 in `ErrorDetails` objects emitted by Spec instance `validate` methods. Specs are 56 required to have tags and all builtin Spec factories will supply a default tag if 57 one is not given. 58 59 The `s` API also includes several Spec factories for common Python types such as 60 `bool`, `bytes`, `date`, `datetime` (via `s.inst`), `float` (via `s.num`), `int` 61 (via `s.num`), `str`, `time`, and `uuid`. 62 63 `s` also includes several pre-built Specs for basic types which are useful if you 64 only want to verify that a value is of a specific type. All the pre-built Specs 65 are supplied as `s.is_{type}` on `s`. 66 67 All Specs provide the following API: 68 69 * `Spec.is_valid(x)` returns a `bool` indicating if `x` is valid according to the 70 Spec definition 71 * `Spec.validate(x)` yields consecutive `ErrorDetails` describing every spec 72 violation for `x`. By definition, if `next(Spec.validate(x))` returns an 73 empty generator, then `x` satisfies the Spec. 74 * `Spec.validate_ex(x)` throws a `ValidationError` containing the full list of 75 `ErrorDetails` of errors occurred validating `x` if any errors are encountered. 76 Otherwise, returns `None`. 77 * `Spec.conform(x)` attempts to conform `x` according to the Spec conformer iff 78 `x` is valid according to the Spec. Otherwise returns `INVALID`. 79 * `Spec.conform_valid(x)` conforms `x` using the Spec conformer, without checking 80 first if `x` is valid. Useful if you wish to check your data for validity and 81 conform it in separate steps without incurring validation costs twice. 82 * `Spec.with_conformer(c)` returns a new Spec instance with the Conformer `c`. 83 The old Spec instance is not modified. 84 * `Spec.with_tag(t)` returns a new Spec instance with the Tag `t`. The old Spec 85 instance is not modified. 86 87 ### Scalar Specs 88 89 The simplest data specs are those which evaluate Python's builtin scalar types: 90 strings, integers, floats, and booleans. 91 92 You can create a spec which validates strings with `s.str()`. Common string 93 validations can be specified as keyword arguments, such as the min/max length or a 94 matching regex. If you are only interested in validating that a value is a string 95 without any further validations, spec features the predefined spec `s.is_str` (note 96 no function call required). 97 98 Likewise, numeric specs can be created using `s.num()`, with several builtin 99 validations available as keyword arguments such as min/max value and narrowing down 100 the specific numeric types. If you are only interested in validating that a value is 101 numeric, you can use the builtin `s.is_num` or `s.is_int` or `s.is_float` specs. 102 103 ### Predicate Specs 104 105 You can define a spec using any simple predicate you may have by passing the predicate 106 directly to the `s` function, since not every valid state of your data can be specified 107 using existing specs. 108 109 ```python 110 spec = s(lambda id_: uuid.UUID(id_).version == 4) 111 spec.is_valid("4716df50-0aa0-4b7d-98a4-1f2b2bcb1c6b") # True 112 spec.is_valid("b4e9735a-ee8c-11e9-8708-4c327592fea9") # False 113 ``` 114 115 ### UUID Specs 116 117 In the previous section, we used a simple predicate to check that a UUID was a certain 118 version of an RFC 4122 variant UUID. However, `spec` includes builtin UUID specs which 119 can simplify the logic here: 120 121 ```python 122 spec = s.uuid(versions={4}) 123 spec.is_valid("4716df50-0aa0-4b7d-98a4-1f2b2bcb1c6b") # True 124 spec.is_valid("b4e9735a-ee8c-11e9-8708-4c327592fea9") # False 125 ``` 126 127 Additionally, if you are only interested in validating that a value is a UUID, the 128 builting spec `s.is_uuid` is available. 129 130 ### Date Specs 131 132 `spec` includes some builtin Specs for Python's `datetime`, `date`, and `time` classes. 133 With the builtin specs, you can validate that any of these three class types are before 134 or after a given. Suppose you want to verify that someone is 18 by checking their date 135 of birth: 136 137 ```python 138 spec = s.date(after=date.today() - timedelta(years=18)) 139 spec.is_valid(date.today() - timedelta(years=21)) # True 140 spec.is_valid(date.today() - timedelta(years=12)) # False 141 ``` 142 143 For datetimes (instants) and times, you can also use `is_aware=True` to specify that 144 the instance be timezone-aware (e.g. not naive). 145 146 You can use the builtins `s.is_date`, `s.is_inst`, and `s.is_time` if you only want to 147 validate that a value is an instance of any of those classes. 148 149 ### Set (Enum) Specs 150 151 Commonly, you may be interested in validating that a value is one of a constrained set 152 of known values. In Python code, you would use an `Enum` type to model these values. 153 To define an enumermation spec, you can use either pass an existing `Enum` value into 154 your spec: 155 156 ```python 157 class YesNo(Enum): 158 YES = "Yes" 159 NO = "No" 160 161 s(YesNo).is_valid("Yes") # True 162 s(YesNo).is_valid("Maybe") # False 163 ``` 164 165 Any valid representation of the `Enum` value would satisfy the spec, including the 166 value, alias, and actual `Enum` value (like `YesNo.NO`). 167 168 Additionally, for simpler cases you can specify an enum using Python `set`s (or 169 `frozenset`s): 170 171 ```python 172 s({"Yes", "No"}).is_valid("Yes") # True 173 s({"Yes", "No"}).is_valid("Maybe") # False 174 ``` 175 176 ### Collection Specs 177 178 Specs can be defined for values in homogenous collections as well. Define a spec for 179 a homogenous collection as a list passed to `s` with the first element as the Spec 180 for collection elements: 181 182 ```python 183 s([s.num(min_=0)]).is_valid([1, 2, 3, 4]) # True 184 s([s.num(min_=0)]).is_valid([-11, 2, 3]) # False 185 ``` 186 187 You may also want to assert certain conditions that apply to the collection as a whole. 188 Spec allows you to specify an _optional_ dictionary as the second element of the list 189 with a few possible rules applying to the collection as a whole, such as length and 190 collection type. 191 192 ```python 193 s([s.num(min_=0), {"kind": list}]).is_valid([1, 2, 3, 4]) # True 194 s([s.num(min_=0), {"kind": list}]).is_valid({1, 2, 3, 4}) # False 195 ``` 196 197 Collection specs conform input collections by applying the element conformer(s) to each 198 element of the input collection. Callers can specify an `"into"` key in the collection 199 options dictionary as part of the spec to specify which type of collection is emitted 200 by the collection spec default conformer. Collection specs which do not specify the 201 `"into"` collection type will conform collections into the same type as the input 202 collection. 203 204 ### Tuple Specs 205 206 Specs can be defined for heterogenous collections of elements, which is often the use 207 case for Python's `tuple` type. To define a spec for a tuple, pass a tuple of specs for 208 each element in the collection at the corresponding tuple index: 209 210 ``` 211 s( 212 ( 213 s.str("id", format_="uuid"), 214 s.str("first_name"), 215 s.str("last_name"), 216 s.str("date_of_birth", format_="iso-date"), 217 s("gender", {"M", "F"}), 218 ) 219 ) 220 ``` 221 222 Tuple specs conform input tuples by applying each field's conformer(s) to the fields of 223 the input tuple to return a new tuple. If each field in the tuple spec has a unique tag 224 and the tuple has a custom tag specified, the default conformer will yield a 225 `namedtuple` with the tuple spec tag as the type name and the field spec tags as each 226 field name. The type name and field names will be munged to be valid Python 227 identifiers. 228 229 ### Mapping Specs 230 231 Specs can be defined for mapping/associative types and objects. To define a spec for a 232 mapping type, pass a dictionary of specs to `s`. The keys should be the expected key 233 value (most often a string) and the value should be the spec for values located in that 234 key. If a mapping spec contains a key, the spec considers that key _required_. To 235 specify an _optional_ key in the spec, wrap the key in `s.opt`. Optional keys will 236 be validated if they are present, but allow the map to exclude those keys without 237 being considered invalid. 238 239 ```python 240 s( 241 { 242 "id": s.str("id", format_="uuid"), 243 "first_name": s.str("first_name"), 244 "last_name": s.str("last_name"), 245 "date_of_birth": s.str("date_of_birth", format_="iso-date"), 246 "gender": s("gender", {"M", "F"}), 247 s.opt("state"): s("state", {"CA", "GA", "NY"}), 248 } 249 ) 250 ``` 251 252 Above the key `"state"` is optional in tested values, but if it is provided it must 253 be one of `"CA"`, `"GA"`, or `"NY"`. 254 255 *Note:* Mapping specs do not validate that input values _only_ contain the expected 256 set of keys. Extra keys will be ignored. This is intentional behavior. 257 258 Mapping specs conform input dictionaries by applying each field's conformer(s) to 259 the fields of the input map to return a new dictionary. As a consequence, the value 260 returned by the mapping spec default conformer will not include any extra keys 261 included in the input. Optional keys will be included in the conformed value if they 262 appear in the input map. 263 264 ### Combination Specs 265 266 In most of the previous examples, we used basic builtin Specs. However, real world 267 data often more nuanced specifications for data. Fortunately, Specs were designed 268 to be composed. In particular, Specs can be composed using standard boolean logic. 269 To specify an `or` spec, you can use `s.any(...)` with any `n` specs. 270 271 ```python 272 spec = s.any(s.str(format_="uuid"), s.str(maxlength=0)) 273 spec.is_valid("4716df50-0aa0-4b7d-98a4-1f2b2bcb1c6b") # True 274 spec.is_valid("") # True 275 spec.is_valid("3837273723") # False 276 ``` 277 278 Similarly, to specify an `and` spec, you can use `s.all(...)` with any `n` specs: 279 280 ```python 281 spec = s.all(s.str(format_="uuid"), s(lambda id_: uuid.UUID(id_).version == 4)) 282 spec.is_valid("4716df50-0aa0-4b7d-98a4-1f2b2bcb1c6b") # True 283 spec.is_valid("b4e9735a-ee8c-11e9-8708-4c327592fea9") # False 284 ``` 285 286 `and` Specs apply each child Spec's conformer to the value during validation, 287 so you may assume the output of the previous Spec's conformer in subsequent 288 Specs. 289 290 ### Examples 291 292 Suppose you'd like to define a Spec for validating that a string is at least 10 293 characters long (ignore encoding nuances), you could define that as follows: 294 295 ```python 296 spec = s.str(minlength=10) 297 spec.is_valid("a string") # False 298 spec.is_valid("London, England") # True 299 ``` 300 301 Or perhaps you'd like to check that every number in a list is above a certain value: 302 303 ```python 304 spec = s([s.num(min_=70), {"kind": list}]) 305 spec.is_valid([70, 83, 92, 99]) # True 306 spec.is_valid({70, 83, 92, 99}) # False, as the input collection is a set 307 spec.is_valid([43, 66, 80, 93]) # False, not all numbers above 70 308 ``` 309 310 A more realistic case for a Spec is validating incoming data at the application 311 boundaries. Suppose you're accepting a user profile submission as a JSON object over 312 an HTTP endpoint, you could validate the data like so: 313 314 ```python 315 spec = s( 316 "user-profile", 317 { 318 "id": s.str("id", format_="uuid"), 319 "first_name": s.str("first_name"), 320 "last_name": s.str("last_name"), 321 "date_of_birth": s.str("date_of_birth", format_="iso-date"), 322 "gender": s("gender", {"M", "F"}), 323 s.opt("state"): s.str(minlength=2, maxlength=2), 324 } 325 ) 326 spec.is_valid( # True 327 { 328 "id": "e1bc9fb2-a4d3-4683-bfef-3acc61b0edcc", 329 "first_name": "Carl", 330 "last_name": "Sagan", 331 "date_of_birth": "1996-12-20", 332 "gender": "M", 333 "state": "CA", 334 } 335 ) 336 spec.is_valid( # True; note that extra keys _are ignored_ 337 { 338 "id": "958e2f55-5fdf-4b84-a522-a0765299ba4b", 339 "first_name": "Marie", 340 "last_name": "Curie", 341 "date_of_birth": "1867-11-07", 342 "gender": "F", 343 "occupation": "Chemist", 344 } 345 ) 346 spec.is_valid( # False; missing "gender" key 347 { 348 "id": "958e2f55-5fdf-4b84-a522-a0765299ba4b", 349 "first_name": "Marie", 350 "last_name": "Curie", 351 "date_of_birth": "1867-11-07", 352 } 353 ) 354 ``` 355 356 ## Concepts 357 358 ### Predicates 359 360 Predicates are functions of one argument which return a boolean. Predicates answer 361 questions such as "is `x` an instance of `str`?" or "is `n` greater than `0`?". 362 Frequently in Python, predicates are simply expressions used in an `if` statement. 363 In functional programming languages (and particularly in Lisps), it is more common 364 to encode these predicates in functions which can be combined using lambdas or 365 partials to be reused. Spec encourages that functional paradigm and benefits 366 directly from it. 367 368 Predicate functions should satisfy the `PredicateFn` type and can be wrapped in the 369 `PredicateSpec` spec type. 370 371 ### Validators 372 373 Validators are like predicates in that they answer the same fundamental questions about 374 data that predicates do. However, Validators are a Spec concept that allow us to 375 retrieve richer error data from Spec failures than we can natively with a simple 376 predicate. Validators are functions of one argument which return 0 or more `ErrorDetails` 377 instances (typically `yield`ed as a generator) describing the error. 378 379 Validator functions should satisfy the `ValidatorFn` type and can be wrapped in the 380 `ValidatorSpec` spec type. 381 382 ### Conformers 383 384 Conformers are functions of one argument, `x`, that return either a conformed value, 385 which may be `x` itself, a new value based on `x`, or the special Spec value 386 `INVALID` if the value cannot be conformed. 387 388 All specs may include conformers. Scalar spec types such as `PredicateSpec` and 389 `ValidatorSpec` simply return their argument if it satisfies the spec. Specs for 390 more complex data structures supply a default conformer which produce new data 391 structures after applying any child conformation functions to the data structure 392 elements. 393 394 ### Tags 395 396 All Specs can be created with optional tags, specified as a string in the first 397 positional argument of any spec creation function. Tags are useful for providing 398 useful names for specs in debugging and validation messages. 399 400 ## TODOs 401 - in dict specs, default child spec tag from corresponding dictionary key 402 - break out conformers into separate object? main value would be to propogate 403 `.conform_valid()` calls all the way through; currently they don't propogate 404 past collection, dict, and tuple specs 405 406 ## License 407 408 MIT License 409 [end of README.md] [start of CHANGELOG.md] 1 # Changelog 2 All notable changes to this project will be documented in this file. 3 4 The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 5 and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 6 7 ## [Unreleased] 8 ### Added 9 - Add an exact length validator to the string spec factory (#2) 10 - Add conforming string formats (#3) 11 - Add ISO time string format (#4) 12 - Allow type-checking specs to be created by passing a type directly to `s` (#12) 13 14 ## [0.1.0] - 2019-10-20 15 ### Added 16 - Initial commit 17 [end of CHANGELOG.md] [start of src/dataspec/factories.py] 1 import re 2 import sys 3 import threading 4 import uuid 5 from datetime import date, datetime, time 6 from typing import ( 7 Any, 8 Callable, 9 Iterator, 10 List, 11 Mapping, 12 MutableMapping, 13 Optional, 14 Set, 15 Tuple, 16 Type, 17 TypeVar, 18 Union, 19 cast, 20 ) 21 22 import attr 23 24 from dataspec.base import ( 25 Conformer, 26 ErrorDetails, 27 ObjectSpec, 28 OptionalKey, 29 PredicateSpec, 30 Spec, 31 SpecPredicate, 32 Tag, 33 ValidatorFn, 34 ValidatorSpec, 35 compose_conformers, 36 make_spec, 37 pred_to_validator, 38 ) 39 40 T = TypeVar("T") 41 42 43 def _tag_maybe( 44 maybe_tag: Union[Tag, T], *args: T 45 ) -> Tuple[Optional[str], Tuple[T, ...]]: 46 """Return the Spec tag and the remaining arguments if a tag is given, else return 47 the arguments.""" 48 tag = maybe_tag if isinstance(maybe_tag, str) else None 49 return tag, (cast("Tuple[T, ...]", (maybe_tag, *args)) if tag is None else args) 50 51 52 def any_spec(*preds: SpecPredicate, conformer: Optional[Conformer] = None) -> Spec: 53 """Return a Spec which may be satisfied if the input value satisfies at least one 54 input Spec.""" 55 tag, preds = _tag_maybe(*preds) # pylint: disable=no-value-for-parameter 56 specs = [make_spec(pred) for pred in preds] 57 58 def _any_pred(e) -> bool: 59 for spec in specs: 60 if spec.is_valid(e): 61 return True 62 63 return False 64 65 return PredicateSpec(tag or "any", pred=_any_pred, conformer=conformer) 66 67 68 def all_spec(*preds: SpecPredicate, conformer: Optional[Conformer] = None) -> Spec: 69 """Return a Spec which requires all of the input Specs to be satisfied to validate 70 input data.""" 71 tag, preds = _tag_maybe(*preds) # pylint: disable=no-value-for-parameter 72 specs = [make_spec(pred) for pred in preds] 73 74 def _all_preds(e) -> bool: 75 """Validate e against successive conformations to spec in specs.""" 76 77 for spec in specs: 78 if not spec.is_valid(e): 79 return False 80 e = spec.conform_valid(e) 81 82 return True 83 84 return PredicateSpec( 85 tag or "all", 86 pred=_all_preds, 87 conformer=compose_conformers(*specs, conform_final=conformer), 88 ) 89 90 91 def bool_spec( 92 tag: Optional[Tag] = None, 93 allowed_values: Optional[Set[bool]] = None, 94 conformer: Optional[Conformer] = None, 95 ) -> Spec: 96 """Return a Spec which returns True for boolean values.""" 97 98 assert allowed_values is None or all(isinstance(e, bool) for e in allowed_values) 99 100 @pred_to_validator("Value '{value}' is not boolean", complement=True) 101 def is_bool(v) -> bool: 102 return isinstance(v, bool) 103 104 validators = [is_bool] 105 106 if allowed_values is not None: 107 108 @pred_to_validator( 109 f"Value '{{value}}' not in {allowed_values}", complement=True 110 ) 111 def is_allowed_bool_type(v) -> bool: 112 return v in allowed_values # type: ignore 113 114 validators.append(is_allowed_bool_type) 115 116 return ValidatorSpec.from_validators( 117 tag or "bool", *validators, conformer=conformer 118 ) 119 120 121 def bytes_spec( # noqa: MC0001 # pylint: disable=too-many-arguments 122 tag: Optional[Tag] = None, 123 type_: Tuple[Union[Type[bytes], Type[bytearray]], ...] = (bytes, bytearray), 124 minlength: Optional[int] = None, 125 maxlength: Optional[int] = None, 126 conformer: Optional[Conformer] = None, 127 ) -> Spec: 128 """Return a spec that can validate bytes and bytearrays against common rules.""" 129 130 @pred_to_validator(f"Value '{{value}}' is not a {type_}", complement=True) 131 def is_bytes(s: Any) -> bool: 132 return isinstance(s, type_) 133 134 validators: List[Union[ValidatorFn, ValidatorSpec]] = [is_bytes] 135 136 if minlength is not None: 137 138 if not isinstance(minlength, int): 139 raise TypeError("Byte minlength spec must be an integer length") 140 141 if minlength < 0: 142 raise ValueError("Byte minlength spec cannot be less than 0") 143 144 @pred_to_validator( 145 f"Bytes '{{value}}' does not meet minimum length {minlength}" 146 ) 147 def bytestr_has_min_length(s: str) -> bool: 148 return len(s) < minlength # type: ignore 149 150 validators.append(bytestr_has_min_length) 151 152 if maxlength is not None: 153 154 if not isinstance(maxlength, int): 155 raise TypeError("Byte maxlength spec must be an integer length") 156 157 if maxlength < 0: 158 raise ValueError("Byte maxlength spec cannot be less than 0") 159 160 @pred_to_validator(f"Bytes '{{value}}' exceeds maximum length {maxlength}") 161 def bytestr_has_max_length(s: str) -> bool: 162 return len(s) > maxlength # type: ignore 163 164 validators.append(bytestr_has_max_length) 165 166 if minlength is not None and maxlength is not None: 167 if minlength > maxlength: 168 raise ValueError( 169 "Cannot define a spec with minlength greater than maxlength" 170 ) 171 172 return ValidatorSpec.from_validators( 173 tag or "bytes", *validators, conformer=conformer 174 ) 175 176 177 def every_spec( 178 tag: Optional[Tag] = None, conformer: Optional[Conformer] = None 179 ) -> Spec: 180 """Return a Spec which returns True for every possible value.""" 181 182 def always_true(_) -> bool: 183 return True 184 185 return PredicateSpec(tag or "every", always_true, conformer=conformer) 186 187 188 def _make_datetime_spec_factory( 189 type_: Union[Type[datetime], Type[date], Type[time]] 190 ) -> Callable[..., Spec]: 191 """ 192 Factory function for generating datetime type spec factories. 193 194 Yep. 195 """ 196 197 def _datetime_spec_factory( 198 tag: Optional[Tag] = None, 199 before: Optional[type_] = None, # type: ignore 200 after: Optional[type_] = None, # type: ignore 201 is_aware: Optional[bool] = None, 202 conformer: Optional[Conformer] = None, 203 ) -> Spec: 204 """Return a Spec which validates datetime types with common rules.""" 205 206 @pred_to_validator(f"Value '{{value}}' is not {type_}", complement=True) 207 def is_datetime_type(v) -> bool: 208 return isinstance(v, type_) 209 210 validators = [is_datetime_type] 211 212 if before is not None: 213 214 @pred_to_validator(f"Value '{{value}}' is not before {before}") 215 def is_before(dt) -> bool: 216 return before < dt 217 218 validators.append(is_before) 219 220 if after is not None: 221 222 @pred_to_validator(f"Value '{{value}}' is not after {after}") 223 def is_after(dt) -> bool: 224 return after > dt 225 226 validators.append(is_after) 227 228 if is_aware is not None: 229 if type_ is datetime: 230 231 @pred_to_validator( 232 f"Datetime '{{value}}' is not aware", complement=is_aware 233 ) 234 def datetime_is_aware(d: datetime) -> bool: 235 return d.tzinfo is not None and d.tzinfo.utcoffset(d) is not None 236 237 validators.append(datetime_is_aware) 238 239 elif type_ is time: 240 241 @pred_to_validator( 242 f"Time '{{value}}' is not aware", complement=is_aware 243 ) 244 def time_is_aware(t: time) -> bool: 245 return t.tzinfo is not None and t.tzinfo.utcoffset(None) is not None 246 247 validators.append(time_is_aware) 248 249 elif is_aware is True: 250 raise TypeError(f"Type {type_} cannot be timezone aware") 251 252 return ValidatorSpec.from_validators( 253 tag or type_.__name__, *validators, conformer=conformer 254 ) 255 256 return _datetime_spec_factory 257 258 259 datetime_spec = _make_datetime_spec_factory(datetime) 260 date_spec = _make_datetime_spec_factory(date) 261 time_spec = _make_datetime_spec_factory(time) 262 263 264 def nilable_spec( 265 *args: Union[Tag, SpecPredicate], conformer: Optional[Conformer] = None 266 ) -> Spec: 267 """Return a Spec which either satisfies a single Spec predicate or which is None.""" 268 tag, preds = _tag_maybe(*args) # pylint: disable=no-value-for-parameter 269 assert len(preds) == 1, "Only one predicate allowed" 270 spec = make_spec(cast("SpecPredicate", preds[0])) 271 272 def nil_or_pred(e) -> bool: 273 if e is None: 274 return True 275 276 return spec.is_valid(e) 277 278 return PredicateSpec(tag or "nilable", pred=nil_or_pred, conformer=conformer) 279 280 281 def num_spec( 282 tag: Optional[Tag] = None, 283 type_: Union[Type, Tuple[Type, ...]] = (float, int), 284 min_: Union[complex, float, int, None] = None, 285 max_: Union[complex, float, int, None] = None, 286 conformer: Optional[Conformer] = None, 287 ) -> Spec: 288 """Return a spec that can validate numeric values against common rules.""" 289 290 @pred_to_validator(f"Value '{{value}}' is not type {type_}", complement=True) 291 def is_numeric_type(x: Any) -> bool: 292 return isinstance(x, type_) 293 294 validators = [is_numeric_type] 295 296 if min_ is not None: 297 298 @pred_to_validator(f"Number '{{value}}' is smaller than minimum {min_}") 299 def num_meets_min(x: Union[complex, float, int]) -> bool: 300 return x < min_ # type: ignore 301 302 validators.append(num_meets_min) 303 304 if max_ is not None: 305 306 @pred_to_validator(f"String '{{value}}' exceeds maximum length {max_}") 307 def num_under_max(x: Union[complex, float, int]) -> bool: 308 return x > max_ # type: ignore 309 310 validators.append(num_under_max) 311 312 if min_ is not None and max_ is not None: 313 if min_ > max_: # type: ignore 314 raise ValueError("Cannot define a spec with min greater than max") 315 316 return ValidatorSpec.from_validators(tag or "num", *validators, conformer=conformer) 317 318 319 def obj_spec( 320 *args: Union[Tag, SpecPredicate], conformer: Optional[Conformer] = None 321 ) -> Spec: 322 """Return a Spec for an Object.""" 323 tag, preds = _tag_maybe(*args) # pylint: disable=no-value-for-parameter 324 assert len(preds) == 1, "Only one predicate allowed" 325 return ObjectSpec.from_val( 326 tag or "object", 327 cast(Mapping[str, SpecPredicate], preds[0]), 328 conformer=conformer, 329 ) 330 331 332 def opt_key(k: T) -> OptionalKey: 333 """Return `k` wrapped in a marker object indicating that the key is optional in 334 associative specs.""" 335 return OptionalKey(k) 336 337 338 @attr.s(auto_attribs=True, frozen=True, slots=True) 339 class StrFormat: 340 validator: ValidatorSpec 341 conformer: Optional[Conformer] = None 342 343 @property 344 def conforming_validator(self) -> ValidatorSpec: 345 if self.conformer is not None: 346 return cast(ValidatorSpec, self.validator.with_conformer(self.conformer)) 347 else: 348 return self.validator 349 350 351 _STR_FORMATS: MutableMapping[str, StrFormat] = {} 352 _STR_FORMAT_LOCK = threading.Lock() 353 354 355 def register_str_format_spec( 356 name: str, validate: ValidatorSpec, conformer: Optional[Conformer] = None 357 ) -> None: # pragma: no cover 358 """Register a new String format, which will be checked by the ValidatorSpec 359 `validate`. A conformer can be supplied for the string format which will 360 be applied if desired, but may otherwise be ignored.""" 361 with _STR_FORMAT_LOCK: 362 _STR_FORMATS[name] = StrFormat(validate, conformer=conformer) 363 364 365 def register_str_format( 366 tag: Tag, conformer: Optional[Conformer] = None 367 ) -> Callable[[Callable], ValidatorFn]: 368 """Decorator to register a Validator function as a string format.""" 369 370 def create_str_format(f) -> ValidatorFn: 371 register_str_format_spec(tag, ValidatorSpec(tag, f), conformer=conformer) 372 return f 373 374 return create_str_format 375 376 377 @register_str_format("uuid", conformer=uuid.UUID) 378 def _str_is_uuid(s: str) -> Iterator[ErrorDetails]: 379 try: 380 uuid.UUID(s) 381 except ValueError: 382 yield ErrorDetails( 383 message=f"String does not contain UUID", pred=_str_is_uuid, value=s 384 ) 385 386 387 if sys.version_info >= (3, 7): 388 389 @register_str_format("iso-date", conformer=date.fromisoformat) 390 def _str_is_iso_date(s: str) -> Iterator[ErrorDetails]: 391 try: 392 date.fromisoformat(s) 393 except ValueError: 394 yield ErrorDetails( 395 message=f"String does not contain ISO formatted date", 396 pred=_str_is_iso_date, 397 value=s, 398 ) 399 400 @register_str_format("iso-datetime", conformer=datetime.fromisoformat) 401 def _str_is_iso_datetime(s: str) -> Iterator[ErrorDetails]: 402 try: 403 datetime.fromisoformat(s) 404 except ValueError: 405 yield ErrorDetails( 406 message=f"String does not contain ISO formatted datetime", 407 pred=_str_is_iso_datetime, 408 value=s, 409 ) 410 411 @register_str_format("iso-time", conformer=time.fromisoformat) 412 def _str_is_iso_time(s: str) -> Iterator[ErrorDetails]: 413 try: 414 time.fromisoformat(s) 415 except ValueError: 416 yield ErrorDetails( 417 message=f"String does not contain ISO formatted time", 418 pred=_str_is_iso_time, 419 value=s, 420 ) 421 422 423 else: 424 425 _ISO_DATE_REGEX = re.compile(r"(\d{4})-(\d{2})-(\d{2})") 426 427 def _str_to_iso_date(s: str) -> Optional[date]: 428 match = re.fullmatch(_ISO_DATE_REGEX, s) 429 if match is not None: 430 year, month, day = tuple(int(match.group(x)) for x in (1, 2, 3)) 431 return date(year, month, day) 432 else: 433 return None 434 435 @register_str_format("iso-date", conformer=_str_to_iso_date) 436 def _str_is_iso_date(s: str) -> Iterator[ErrorDetails]: 437 d = _str_to_iso_date(s) 438 if d is None: 439 yield ErrorDetails( 440 message=f"String does not contain ISO formatted date", 441 pred=_str_is_iso_date, 442 value=s, 443 ) 444 445 446 def str_spec( # noqa: MC0001 # pylint: disable=too-many-arguments 447 tag: Optional[Tag] = None, 448 length: Optional[int] = None, 449 minlength: Optional[int] = None, 450 maxlength: Optional[int] = None, 451 regex: Optional[str] = None, 452 format_: Optional[str] = None, 453 conform_format: Optional[str] = None, 454 conformer: Optional[Conformer] = None, 455 ) -> Spec: 456 """Return a spec that can validate strings against common rules.""" 457 458 @pred_to_validator(f"Value '{{value}}' is not a string", complement=True) 459 def is_str(s: Any) -> bool: 460 return isinstance(s, str) 461 462 validators: List[Union[ValidatorFn, ValidatorSpec]] = [is_str] 463 464 if length is not None: 465 466 if not isinstance(length, int): 467 raise TypeError("String length spec must be an integer length") 468 469 if length < 0: 470 raise ValueError("String length spec cannot be less than 0") 471 472 if minlength is not None or maxlength is not None: 473 raise ValueError( 474 "Cannot define a string spec with exact length " 475 "and minlength or maxlength" 476 ) 477 478 @pred_to_validator(f"String length does not equal {length}", convert_value=len) 479 def str_is_exactly_len(v) -> bool: 480 return len(v) != length 481 482 validators.append(str_is_exactly_len) 483 484 if minlength is not None: 485 486 if not isinstance(minlength, int): 487 raise TypeError("String minlength spec must be an integer length") 488 489 if minlength < 0: 490 raise ValueError("String minlength spec cannot be less than 0") 491 492 @pred_to_validator( 493 f"String '{{value}}' does not meet minimum length {minlength}" 494 ) 495 def str_has_min_length(s: str) -> bool: 496 return len(s) < minlength # type: ignore 497 498 validators.append(str_has_min_length) 499 500 if maxlength is not None: 501 502 if not isinstance(maxlength, int): 503 raise TypeError("String maxlength spec must be an integer length") 504 505 if maxlength < 0: 506 raise ValueError("String maxlength spec cannot be less than 0") 507 508 @pred_to_validator(f"String '{{value}}' exceeds maximum length {maxlength}") 509 def str_has_max_length(s: str) -> bool: 510 return len(s) > maxlength # type: ignore 511 512 validators.append(str_has_max_length) 513 514 if minlength is not None and maxlength is not None: 515 if minlength > maxlength: 516 raise ValueError( 517 "Cannot define a spec with minlength greater than maxlength" 518 ) 519 520 if regex is not None and format_ is None and conform_format is None: 521 _pattern = re.compile(regex) 522 523 @pred_to_validator( 524 f"String '{{value}}' does match regex '{regex}'", complement=True 525 ) 526 def str_matches_regex(s: str) -> bool: 527 return bool(_pattern.fullmatch(s)) 528 529 validators.append(str_matches_regex) 530 elif regex is None and format_ is not None and conform_format is None: 531 with _STR_FORMAT_LOCK: 532 validators.append(_STR_FORMATS[format_].validator) 533 elif regex is None and format_ is None and conform_format is not None: 534 with _STR_FORMAT_LOCK: 535 validators.append(_STR_FORMATS[conform_format].conforming_validator) 536 elif sum(int(v is not None) for v in [regex, format_, conform_format]) > 1: 537 raise ValueError( 538 "Cannot define a spec with more than one of: regex, format, conforming format" 539 ) 540 541 return ValidatorSpec.from_validators(tag or "str", *validators, conformer=conformer) 542 543 544 def uuid_spec( 545 tag: Optional[Tag] = None, 546 versions: Optional[Set[int]] = None, 547 conformer: Optional[Conformer] = None, 548 ) -> Spec: 549 """Return a spec that can validate UUIDs against common rules.""" 550 551 @pred_to_validator(f"Value '{{value}}' is not a UUID", complement=True) 552 def is_uuid(v: Any) -> bool: 553 return isinstance(v, uuid.UUID) 554 555 validators: List[Union[ValidatorFn, ValidatorSpec]] = [is_uuid] 556 557 if versions is not None: 558 559 if not {1, 3, 4, 5}.issuperset(set(versions)): 560 raise ValueError("UUID versions must be specified as a set of integers") 561 562 @pred_to_validator(f"UUID '{{value}}' is not RFC 4122 variant", complement=True) 563 def uuid_is_rfc_4122(v: uuid.UUID) -> bool: 564 return v.variant is uuid.RFC_4122 565 566 validators.append(uuid_is_rfc_4122) 567 568 @pred_to_validator( 569 f"UUID '{{value}}' is not in versions {versions}", complement=True 570 ) 571 def uuid_is_version(v: uuid.UUID) -> bool: 572 return v.version in versions # type: ignore 573 574 validators.append(uuid_is_version) 575 576 return ValidatorSpec.from_validators( 577 tag or "uuid", *validators, conformer=conformer 578 ) 579 [end of src/dataspec/factories.py] </code> I need you to solve this issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the following format. <patch> --- a/file.py +++ b/file.py @@ -1,27 +1,35 @@ def euclidean(a, b): - while b: - a, b = b, a % b - return a + if b == 0: + return a + return euclidean(b, a % b) def bresenham(x0, y0, x1, y1): points = [] dx = abs(x1 - x0) dy = abs(y1 - y0) - sx = 1 if x0 < x1 else -1 - sy = 1 if y0 < y1 else -1 - err = dx - dy + x, y = x0, y0 + sx = -1 if x0 > x1 else 1 + sy = -1 if y0 > y1 else 1 - while True: - points.append((x0, y0)) - if x0 == x1 and y0 == y1: - break - e2 = 2 * err - if e2 > -dy: + if dx > dy: + err = dx / 2.0 + while x != x1: + points.append((x, y)) err -= dy - x0 += sx - if e2 < dx: - err += dx - y0 += sy + if err < 0: + y += sy + err += dx + x += sx + else: + err = dy / 2.0 + while y != y1: + points.append((x, y)) + err -= dx + if err < 0: + x += sx + err += dy + y += sy + points.append((x, y)) return points </patch>
coverahealth/dataspec
b314d36fab96cb63477c1d95c734e3bd0f807ed5
Support email address string format Applications commonly need to validate that an email address is at least in a valid format. Python features the [`email.headerregistry.Address`](https://docs.python.org/3/library/email.headerregistry.html#email.headerregistry.Address) object which parses email address strings and can provide some reasonable hints about formatting errors. It may not be foolproof, but for common cases it is probably sufficient.
2019-10-24 02:08:17+00:00
<patch> diff --git a/CHANGELOG.md b/CHANGELOG.md index 9629beb..cf8c599 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Add conforming string formats (#3) - Add ISO time string format (#4) - Allow type-checking specs to be created by passing a type directly to `s` (#12) +- Add email address string format (#6) ## [0.1.0] - 2019-10-20 ### Added diff --git a/src/dataspec/factories.py b/src/dataspec/factories.py index 7f5e005..35e5e0a 100644 --- a/src/dataspec/factories.py +++ b/src/dataspec/factories.py @@ -3,6 +3,7 @@ import sys import threading import uuid from datetime import date, datetime, time +from email.headerregistry import Address from typing import ( Any, Callable, @@ -374,6 +375,18 @@ def register_str_format( return create_str_format +@register_str_format("email") +def _str_is_email_address(s: str) -> Iterator[ErrorDetails]: + try: + Address(addr_spec=s) + except (TypeError, ValueError) as e: + yield ErrorDetails( + f"String does not contain a valid email address: {e}", + pred=_str_is_email_address, + value=s, + ) + + @register_str_format("uuid", conformer=uuid.UUID) def _str_is_uuid(s: str) -> Iterator[ErrorDetails]: try: </patch>
diff --git a/tests/test_factories.py b/tests/test_factories.py index 84b2b23..3f368a8 100644 --- a/tests/test_factories.py +++ b/tests/test_factories.py @@ -652,6 +652,60 @@ class TestStringSpecValidation: def test_is_not_zipcode(self, zipcode_spec: Spec, v): assert not zipcode_spec.is_valid(v) + @pytest.mark.parametrize( + "opts", + [ + {"regex": r"\d{5}(-\d{4})?", "format_": "uuid"}, + {"regex": r"\d{5}(-\d{4})?", "conform_format": "uuid"}, + {"conform_format": "uuid", "format_": "uuid"}, + ], + ) + def test_regex_and_format_agreement(self, opts): + with pytest.raises(ValueError): + s.str(**opts) + + +class TestStringFormatValidation: + class TestEmailFormat: + @pytest.fixture + def email_spec(self) -> Spec: + return s.str(format_="email") + + @pytest.mark.parametrize( + "v", + [ + "chris@localhost", + "[email protected]", + "[email protected]", + "[email protected]", + ], + ) + def test_is_email_str(self, email_spec: Spec, v): + assert email_spec.is_valid(v) + + @pytest.mark.parametrize( + "v", + [ + None, + 25, + 3.14, + [], + set(), + "abcdef", + "abcdefg", + "100017", + "10017-383", + "1945-9-2", + "430-10-02", + "chris", + "chris@", + "@gmail", + "@gmail.com", + ], + ) + def test_is_not_email_str(self, email_spec: Spec, v): + assert not email_spec.is_valid(v) + class TestISODateFormat: @pytest.fixture def conform(self): @@ -849,18 +903,6 @@ class TestStringSpecValidation: assert not uuid_spec.is_valid(v) assert not conforming_uuid_spec.is_valid(v) - @pytest.mark.parametrize( - "opts", - [ - {"regex": r"\d{5}(-\d{4})?", "format_": "uuid"}, - {"regex": r"\d{5}(-\d{4})?", "conform_format": "uuid"}, - {"conform_format": "uuid", "format_": "uuid"}, - ], - ) - def test_regex_and_format_agreement(self, opts): - with pytest.raises(ValueError): - s.str(**opts) - class TestUUIDSpecValidation: @pytest.mark.parametrize(
0.0
[ "tests/test_factories.py::TestStringFormatValidation::TestEmailFormat::test_is_email_str[chris@localhost]", "tests/test_factories.py::TestStringFormatValidation::TestEmailFormat::test_is_email_str[[email protected]]", "tests/test_factories.py::TestStringFormatValidation::TestEmailFormat::test_is_email_str[[email protected]]", "tests/test_factories.py::TestStringFormatValidation::TestEmailFormat::test_is_email_str[[email protected]]", "tests/test_factories.py::TestStringFormatValidation::TestEmailFormat::test_is_not_email_str[None]", "tests/test_factories.py::TestStringFormatValidation::TestEmailFormat::test_is_not_email_str[25]", "tests/test_factories.py::TestStringFormatValidation::TestEmailFormat::test_is_not_email_str[3.14]", "tests/test_factories.py::TestStringFormatValidation::TestEmailFormat::test_is_not_email_str[v3]", "tests/test_factories.py::TestStringFormatValidation::TestEmailFormat::test_is_not_email_str[v4]", "tests/test_factories.py::TestStringFormatValidation::TestEmailFormat::test_is_not_email_str[abcdef]", "tests/test_factories.py::TestStringFormatValidation::TestEmailFormat::test_is_not_email_str[abcdefg]", "tests/test_factories.py::TestStringFormatValidation::TestEmailFormat::test_is_not_email_str[100017]", "tests/test_factories.py::TestStringFormatValidation::TestEmailFormat::test_is_not_email_str[10017-383]", "tests/test_factories.py::TestStringFormatValidation::TestEmailFormat::test_is_not_email_str[1945-9-2]", "tests/test_factories.py::TestStringFormatValidation::TestEmailFormat::test_is_not_email_str[430-10-02]", "tests/test_factories.py::TestStringFormatValidation::TestEmailFormat::test_is_not_email_str[chris]", "tests/test_factories.py::TestStringFormatValidation::TestEmailFormat::test_is_not_email_str[chris@]", "tests/test_factories.py::TestStringFormatValidation::TestEmailFormat::test_is_not_email_str[@gmail]", "tests/test_factories.py::TestStringFormatValidation::TestEmailFormat::test_is_not_email_str[@gmail.com]" ]
[ "tests/test_factories.py::TestAllSpecValidation::test_all_validation[c5a28680-986f-4f0d-8187-80d1fbe22059]", "tests/test_factories.py::TestAllSpecValidation::test_all_validation[3BE59FF6-9C75-4027-B132-C9792D84547D]", "tests/test_factories.py::TestAllSpecValidation::test_all_failure[6281d852-ef4d-11e9-9002-4c327592fea9]", "tests/test_factories.py::TestAllSpecValidation::test_all_failure[0e8d7ceb-56e8-36d2-9b54-ea48d4bdea3f]", "tests/test_factories.py::TestAllSpecValidation::test_all_failure[10988ff4-136c-5ca7-ab35-a686a56c22c4]", "tests/test_factories.py::TestAllSpecValidation::test_all_failure[]", "tests/test_factories.py::TestAllSpecValidation::test_all_failure[5_0]", "tests/test_factories.py::TestAllSpecValidation::test_all_failure[abcde]", "tests/test_factories.py::TestAllSpecValidation::test_all_failure[ABCDe]", "tests/test_factories.py::TestAllSpecValidation::test_all_failure[5_1]", "tests/test_factories.py::TestAllSpecValidation::test_all_failure[3.14]", "tests/test_factories.py::TestAllSpecValidation::test_all_failure[None]", "tests/test_factories.py::TestAllSpecValidation::test_all_failure[v10]", "tests/test_factories.py::TestAllSpecValidation::test_all_failure[v11]", "tests/test_factories.py::TestAllSpecValidation::test_all_failure[v12]", "tests/test_factories.py::TestAllSpecConformation::test_all_spec_conformation[yes-YesNo.YES]", "tests/test_factories.py::TestAllSpecConformation::test_all_spec_conformation[Yes-YesNo.YES]", "tests/test_factories.py::TestAllSpecConformation::test_all_spec_conformation[yES-YesNo.YES]", "tests/test_factories.py::TestAllSpecConformation::test_all_spec_conformation[YES-YesNo.YES]", "tests/test_factories.py::TestAllSpecConformation::test_all_spec_conformation[no-YesNo.NO]", "tests/test_factories.py::TestAllSpecConformation::test_all_spec_conformation[No-YesNo.NO]", "tests/test_factories.py::TestAllSpecConformation::test_all_spec_conformation[nO-YesNo.NO]", "tests/test_factories.py::TestAllSpecConformation::test_all_spec_conformation[NO-YesNo.NO]", "tests/test_factories.py::test_any", "tests/test_factories.py::test_is_any[None]", "tests/test_factories.py::test_is_any[25]", "tests/test_factories.py::test_is_any[3.14]", "tests/test_factories.py::test_is_any[3j]", "tests/test_factories.py::test_is_any[v4]", "tests/test_factories.py::test_is_any[v5]", "tests/test_factories.py::test_is_any[v6]", "tests/test_factories.py::test_is_any[v7]", "tests/test_factories.py::test_is_any[abcdef]", "tests/test_factories.py::TestBoolValidation::test_bool[True]", "tests/test_factories.py::TestBoolValidation::test_bool[False]", "tests/test_factories.py::TestBoolValidation::test_bool_failure[1]", "tests/test_factories.py::TestBoolValidation::test_bool_failure[0]", "tests/test_factories.py::TestBoolValidation::test_bool_failure[]", "tests/test_factories.py::TestBoolValidation::test_bool_failure[a", "tests/test_factories.py::TestBoolValidation::test_is_false", "tests/test_factories.py::TestBoolValidation::test_is_true_failure[False]", "tests/test_factories.py::TestBoolValidation::test_is_true_failure[1]", "tests/test_factories.py::TestBoolValidation::test_is_true_failure[0]", "tests/test_factories.py::TestBoolValidation::test_is_true_failure[]", "tests/test_factories.py::TestBoolValidation::test_is_true_failure[a", "tests/test_factories.py::TestBoolValidation::test_is_true", "tests/test_factories.py::TestBytesSpecValidation::test_is_bytes[]", "tests/test_factories.py::TestBytesSpecValidation::test_is_bytes[a", "tests/test_factories.py::TestBytesSpecValidation::test_is_bytes[\\xf0\\x9f\\x98\\x8f]", "tests/test_factories.py::TestBytesSpecValidation::test_is_bytes[v3]", "tests/test_factories.py::TestBytesSpecValidation::test_is_bytes[v4]", "tests/test_factories.py::TestBytesSpecValidation::test_not_is_bytes[25]", "tests/test_factories.py::TestBytesSpecValidation::test_not_is_bytes[None]", "tests/test_factories.py::TestBytesSpecValidation::test_not_is_bytes[3.14]", "tests/test_factories.py::TestBytesSpecValidation::test_not_is_bytes[v3]", "tests/test_factories.py::TestBytesSpecValidation::test_not_is_bytes[v4]", "tests/test_factories.py::TestBytesSpecValidation::test_not_is_bytes[]", "tests/test_factories.py::TestBytesSpecValidation::test_not_is_bytes[a", "tests/test_factories.py::TestBytesSpecValidation::test_not_is_bytes[\\U0001f60f]", "tests/test_factories.py::TestBytesSpecValidation::TestMinlengthSpec::test_min_minlength[-1]", "tests/test_factories.py::TestBytesSpecValidation::TestMinlengthSpec::test_min_minlength[-100]", "tests/test_factories.py::TestBytesSpecValidation::TestMinlengthSpec::test_int_minlength[-0.5]", "tests/test_factories.py::TestBytesSpecValidation::TestMinlengthSpec::test_int_minlength[0.5]", "tests/test_factories.py::TestBytesSpecValidation::TestMinlengthSpec::test_int_minlength[2.71]", "tests/test_factories.py::TestBytesSpecValidation::TestMinlengthSpec::test_is_minlength[abcde]", "tests/test_factories.py::TestBytesSpecValidation::TestMinlengthSpec::test_is_minlength[abcdef]", "tests/test_factories.py::TestBytesSpecValidation::TestMinlengthSpec::test_is_not_minlength[None]", "tests/test_factories.py::TestBytesSpecValidation::TestMinlengthSpec::test_is_not_minlength[25]", "tests/test_factories.py::TestBytesSpecValidation::TestMinlengthSpec::test_is_not_minlength[3.14]", "tests/test_factories.py::TestBytesSpecValidation::TestMinlengthSpec::test_is_not_minlength[v3]", "tests/test_factories.py::TestBytesSpecValidation::TestMinlengthSpec::test_is_not_minlength[v4]", "tests/test_factories.py::TestBytesSpecValidation::TestMinlengthSpec::test_is_not_minlength[]", "tests/test_factories.py::TestBytesSpecValidation::TestMinlengthSpec::test_is_not_minlength[a]", "tests/test_factories.py::TestBytesSpecValidation::TestMinlengthSpec::test_is_not_minlength[ab]", "tests/test_factories.py::TestBytesSpecValidation::TestMinlengthSpec::test_is_not_minlength[abc]", "tests/test_factories.py::TestBytesSpecValidation::TestMinlengthSpec::test_is_not_minlength[abcd]", "tests/test_factories.py::TestBytesSpecValidation::TestMaxlengthSpec::test_min_maxlength[-1]", "tests/test_factories.py::TestBytesSpecValidation::TestMaxlengthSpec::test_min_maxlength[-100]", "tests/test_factories.py::TestBytesSpecValidation::TestMaxlengthSpec::test_int_maxlength[-0.5]", "tests/test_factories.py::TestBytesSpecValidation::TestMaxlengthSpec::test_int_maxlength[0.5]", "tests/test_factories.py::TestBytesSpecValidation::TestMaxlengthSpec::test_int_maxlength[2.71]", "tests/test_factories.py::TestBytesSpecValidation::TestMaxlengthSpec::test_is_maxlength[]", "tests/test_factories.py::TestBytesSpecValidation::TestMaxlengthSpec::test_is_maxlength[a]", "tests/test_factories.py::TestBytesSpecValidation::TestMaxlengthSpec::test_is_maxlength[ab]", "tests/test_factories.py::TestBytesSpecValidation::TestMaxlengthSpec::test_is_maxlength[abc]", "tests/test_factories.py::TestBytesSpecValidation::TestMaxlengthSpec::test_is_maxlength[abcd]", "tests/test_factories.py::TestBytesSpecValidation::TestMaxlengthSpec::test_is_maxlength[abcde]", "tests/test_factories.py::TestBytesSpecValidation::TestMaxlengthSpec::test_is_not_maxlength[None]", "tests/test_factories.py::TestBytesSpecValidation::TestMaxlengthSpec::test_is_not_maxlength[25]", "tests/test_factories.py::TestBytesSpecValidation::TestMaxlengthSpec::test_is_not_maxlength[3.14]", "tests/test_factories.py::TestBytesSpecValidation::TestMaxlengthSpec::test_is_not_maxlength[v3]", "tests/test_factories.py::TestBytesSpecValidation::TestMaxlengthSpec::test_is_not_maxlength[v4]", "tests/test_factories.py::TestBytesSpecValidation::TestMaxlengthSpec::test_is_not_maxlength[abcdef]", "tests/test_factories.py::TestBytesSpecValidation::TestMaxlengthSpec::test_is_not_maxlength[abcdefg]", "tests/test_factories.py::TestBytesSpecValidation::test_minlength_and_maxlength_agreement", "tests/test_factories.py::TestInstSpecValidation::test_is_inst[v0]", "tests/test_factories.py::TestInstSpecValidation::test_is_inst_failure[None]", "tests/test_factories.py::TestInstSpecValidation::test_is_inst_failure[25]", "tests/test_factories.py::TestInstSpecValidation::test_is_inst_failure[3.14]", "tests/test_factories.py::TestInstSpecValidation::test_is_inst_failure[3j]", "tests/test_factories.py::TestInstSpecValidation::test_is_inst_failure[v4]", "tests/test_factories.py::TestInstSpecValidation::test_is_inst_failure[v5]", "tests/test_factories.py::TestInstSpecValidation::test_is_inst_failure[v6]", "tests/test_factories.py::TestInstSpecValidation::test_is_inst_failure[v7]", "tests/test_factories.py::TestInstSpecValidation::test_is_inst_failure[abcdef]", "tests/test_factories.py::TestInstSpecValidation::test_is_inst_failure[v9]", "tests/test_factories.py::TestInstSpecValidation::test_is_inst_failure[v10]", "tests/test_factories.py::TestInstSpecValidation::TestBeforeSpec::test_before_spec[v0]", "tests/test_factories.py::TestInstSpecValidation::TestBeforeSpec::test_before_spec[v1]", "tests/test_factories.py::TestInstSpecValidation::TestBeforeSpec::test_before_spec[v2]", "tests/test_factories.py::TestInstSpecValidation::TestBeforeSpec::test_before_spec[v3]", "tests/test_factories.py::TestInstSpecValidation::TestBeforeSpec::test_before_spec_failure[v0]", "tests/test_factories.py::TestInstSpecValidation::TestBeforeSpec::test_before_spec_failure[v1]", "tests/test_factories.py::TestInstSpecValidation::TestBeforeSpec::test_before_spec_failure[v2]", "tests/test_factories.py::TestInstSpecValidation::TestAfterSpec::test_after_spec[v0]", "tests/test_factories.py::TestInstSpecValidation::TestAfterSpec::test_after_spec[v1]", "tests/test_factories.py::TestInstSpecValidation::TestAfterSpec::test_after_spec[v2]", "tests/test_factories.py::TestInstSpecValidation::TestAfterSpec::test_after_spec[v3]", "tests/test_factories.py::TestInstSpecValidation::TestAfterSpec::test_after_spec_failure[v0]", "tests/test_factories.py::TestInstSpecValidation::TestAfterSpec::test_after_spec_failure[v1]", "tests/test_factories.py::TestInstSpecValidation::TestAfterSpec::test_after_spec_failure[v2]", "tests/test_factories.py::TestInstSpecValidation::TestIsAwareSpec::test_aware_spec", "tests/test_factories.py::TestInstSpecValidation::TestIsAwareSpec::test_aware_spec_failure", "tests/test_factories.py::TestDateSpecValidation::test_is_date[v0]", "tests/test_factories.py::TestDateSpecValidation::test_is_date[v1]", "tests/test_factories.py::TestDateSpecValidation::test_is_date_failure[None]", "tests/test_factories.py::TestDateSpecValidation::test_is_date_failure[25]", "tests/test_factories.py::TestDateSpecValidation::test_is_date_failure[3.14]", "tests/test_factories.py::TestDateSpecValidation::test_is_date_failure[3j]", "tests/test_factories.py::TestDateSpecValidation::test_is_date_failure[v4]", "tests/test_factories.py::TestDateSpecValidation::test_is_date_failure[v5]", "tests/test_factories.py::TestDateSpecValidation::test_is_date_failure[v6]", "tests/test_factories.py::TestDateSpecValidation::test_is_date_failure[v7]", "tests/test_factories.py::TestDateSpecValidation::test_is_date_failure[abcdef]", "tests/test_factories.py::TestDateSpecValidation::test_is_date_failure[v9]", "tests/test_factories.py::TestDateSpecValidation::TestBeforeSpec::test_before_spec[v0]", "tests/test_factories.py::TestDateSpecValidation::TestBeforeSpec::test_before_spec[v1]", "tests/test_factories.py::TestDateSpecValidation::TestBeforeSpec::test_before_spec[v2]", "tests/test_factories.py::TestDateSpecValidation::TestBeforeSpec::test_before_spec[v3]", "tests/test_factories.py::TestDateSpecValidation::TestBeforeSpec::test_before_spec_failure[v0]", "tests/test_factories.py::TestDateSpecValidation::TestBeforeSpec::test_before_spec_failure[v1]", "tests/test_factories.py::TestDateSpecValidation::TestAfterSpec::test_after_spec[v0]", "tests/test_factories.py::TestDateSpecValidation::TestAfterSpec::test_after_spec[v1]", "tests/test_factories.py::TestDateSpecValidation::TestAfterSpec::test_after_spec[v2]", "tests/test_factories.py::TestDateSpecValidation::TestAfterSpec::test_after_spec_failure[v0]", "tests/test_factories.py::TestDateSpecValidation::TestAfterSpec::test_after_spec_failure[v1]", "tests/test_factories.py::TestDateSpecValidation::TestAfterSpec::test_after_spec_failure[v2]", "tests/test_factories.py::TestDateSpecValidation::TestIsAwareSpec::test_aware_spec", "tests/test_factories.py::TestTimeSpecValidation::test_is_time[v0]", "tests/test_factories.py::TestTimeSpecValidation::test_is_time_failure[None]", "tests/test_factories.py::TestTimeSpecValidation::test_is_time_failure[25]", "tests/test_factories.py::TestTimeSpecValidation::test_is_time_failure[3.14]", "tests/test_factories.py::TestTimeSpecValidation::test_is_time_failure[3j]", "tests/test_factories.py::TestTimeSpecValidation::test_is_time_failure[v4]", "tests/test_factories.py::TestTimeSpecValidation::test_is_time_failure[v5]", "tests/test_factories.py::TestTimeSpecValidation::test_is_time_failure[v6]", "tests/test_factories.py::TestTimeSpecValidation::test_is_time_failure[v7]", "tests/test_factories.py::TestTimeSpecValidation::test_is_time_failure[abcdef]", "tests/test_factories.py::TestTimeSpecValidation::test_is_time_failure[v9]", "tests/test_factories.py::TestTimeSpecValidation::test_is_time_failure[v10]", "tests/test_factories.py::TestTimeSpecValidation::TestBeforeSpec::test_before_spec[v0]", "tests/test_factories.py::TestTimeSpecValidation::TestBeforeSpec::test_before_spec[v1]", "tests/test_factories.py::TestTimeSpecValidation::TestBeforeSpec::test_before_spec[v2]", "tests/test_factories.py::TestTimeSpecValidation::TestBeforeSpec::test_before_spec_failure[v0]", "tests/test_factories.py::TestTimeSpecValidation::TestBeforeSpec::test_before_spec_failure[v1]", "tests/test_factories.py::TestTimeSpecValidation::TestBeforeSpec::test_before_spec_failure[v2]", "tests/test_factories.py::TestTimeSpecValidation::TestAfterSpec::test_after_spec[v0]", "tests/test_factories.py::TestTimeSpecValidation::TestAfterSpec::test_after_spec[v1]", "tests/test_factories.py::TestTimeSpecValidation::TestAfterSpec::test_after_spec[v2]", "tests/test_factories.py::TestTimeSpecValidation::TestAfterSpec::test_after_spec_failure[v0]", "tests/test_factories.py::TestTimeSpecValidation::TestAfterSpec::test_after_spec_failure[v1]", "tests/test_factories.py::TestTimeSpecValidation::TestAfterSpec::test_after_spec_failure[v2]", "tests/test_factories.py::TestTimeSpecValidation::TestIsAwareSpec::test_aware_spec", "tests/test_factories.py::TestTimeSpecValidation::TestIsAwareSpec::test_aware_spec_failure", "tests/test_factories.py::test_nilable", "tests/test_factories.py::TestNumSpecValidation::test_is_num[-3]", "tests/test_factories.py::TestNumSpecValidation::test_is_num[25]", "tests/test_factories.py::TestNumSpecValidation::test_is_num[3.14]", "tests/test_factories.py::TestNumSpecValidation::test_is_num[-2.72]", "tests/test_factories.py::TestNumSpecValidation::test_is_num[-33]", "tests/test_factories.py::TestNumSpecValidation::test_not_is_num[4j]", "tests/test_factories.py::TestNumSpecValidation::test_not_is_num[6j]", "tests/test_factories.py::TestNumSpecValidation::test_not_is_num[]", "tests/test_factories.py::TestNumSpecValidation::test_not_is_num[a", "tests/test_factories.py::TestNumSpecValidation::test_not_is_num[\\U0001f60f]", "tests/test_factories.py::TestNumSpecValidation::test_not_is_num[None]", "tests/test_factories.py::TestNumSpecValidation::test_not_is_num[v6]", "tests/test_factories.py::TestNumSpecValidation::test_not_is_num[v7]", "tests/test_factories.py::TestNumSpecValidation::TestMinSpec::test_is_above_min[5]", "tests/test_factories.py::TestNumSpecValidation::TestMinSpec::test_is_above_min[6]", "tests/test_factories.py::TestNumSpecValidation::TestMinSpec::test_is_above_min[100]", "tests/test_factories.py::TestNumSpecValidation::TestMinSpec::test_is_above_min[300.14]", "tests/test_factories.py::TestNumSpecValidation::TestMinSpec::test_is_above_min[5.83838828283]", "tests/test_factories.py::TestNumSpecValidation::TestMinSpec::test_is_not_above_min[None]", "tests/test_factories.py::TestNumSpecValidation::TestMinSpec::test_is_not_above_min[-50]", "tests/test_factories.py::TestNumSpecValidation::TestMinSpec::test_is_not_above_min[4.9]", "tests/test_factories.py::TestNumSpecValidation::TestMinSpec::test_is_not_above_min[4]", "tests/test_factories.py::TestNumSpecValidation::TestMinSpec::test_is_not_above_min[0]", "tests/test_factories.py::TestNumSpecValidation::TestMinSpec::test_is_not_above_min[3.14]", "tests/test_factories.py::TestNumSpecValidation::TestMinSpec::test_is_not_above_min[v6]", "tests/test_factories.py::TestNumSpecValidation::TestMinSpec::test_is_not_above_min[v7]", "tests/test_factories.py::TestNumSpecValidation::TestMinSpec::test_is_not_above_min[]", "tests/test_factories.py::TestNumSpecValidation::TestMinSpec::test_is_not_above_min[a]", "tests/test_factories.py::TestNumSpecValidation::TestMinSpec::test_is_not_above_min[ab]", "tests/test_factories.py::TestNumSpecValidation::TestMinSpec::test_is_not_above_min[abc]", "tests/test_factories.py::TestNumSpecValidation::TestMinSpec::test_is_not_above_min[abcd]", "tests/test_factories.py::TestNumSpecValidation::TestMaxSpec::test_is_below_max[-50]", "tests/test_factories.py::TestNumSpecValidation::TestMaxSpec::test_is_below_max[4.9]", "tests/test_factories.py::TestNumSpecValidation::TestMaxSpec::test_is_below_max[4]", "tests/test_factories.py::TestNumSpecValidation::TestMaxSpec::test_is_below_max[0]", "tests/test_factories.py::TestNumSpecValidation::TestMaxSpec::test_is_below_max[3.14]", "tests/test_factories.py::TestNumSpecValidation::TestMaxSpec::test_is_below_max[5]", "tests/test_factories.py::TestNumSpecValidation::TestMaxSpec::test_is_not_below_max[None]", "tests/test_factories.py::TestNumSpecValidation::TestMaxSpec::test_is_not_below_max[6]", "tests/test_factories.py::TestNumSpecValidation::TestMaxSpec::test_is_not_below_max[100]", "tests/test_factories.py::TestNumSpecValidation::TestMaxSpec::test_is_not_below_max[300.14]", "tests/test_factories.py::TestNumSpecValidation::TestMaxSpec::test_is_not_below_max[5.83838828283]", "tests/test_factories.py::TestNumSpecValidation::TestMaxSpec::test_is_not_below_max[v5]", "tests/test_factories.py::TestNumSpecValidation::TestMaxSpec::test_is_not_below_max[v6]", "tests/test_factories.py::TestNumSpecValidation::TestMaxSpec::test_is_not_below_max[]", "tests/test_factories.py::TestNumSpecValidation::TestMaxSpec::test_is_not_below_max[a]", "tests/test_factories.py::TestNumSpecValidation::TestMaxSpec::test_is_not_below_max[ab]", "tests/test_factories.py::TestNumSpecValidation::TestMaxSpec::test_is_not_below_max[abc]", "tests/test_factories.py::TestNumSpecValidation::TestMaxSpec::test_is_not_below_max[abcd]", "tests/test_factories.py::TestNumSpecValidation::test_min_and_max_agreement", "tests/test_factories.py::TestStringSpecValidation::test_is_str[]", "tests/test_factories.py::TestStringSpecValidation::test_is_str[a", "tests/test_factories.py::TestStringSpecValidation::test_is_str[\\U0001f60f]", "tests/test_factories.py::TestStringSpecValidation::test_not_is_str[25]", "tests/test_factories.py::TestStringSpecValidation::test_not_is_str[None]", "tests/test_factories.py::TestStringSpecValidation::test_not_is_str[3.14]", "tests/test_factories.py::TestStringSpecValidation::test_not_is_str[v3]", "tests/test_factories.py::TestStringSpecValidation::test_not_is_str[v4]", "tests/test_factories.py::TestStringSpecValidation::TestCountValidation::test_min_count[-1]", "tests/test_factories.py::TestStringSpecValidation::TestCountValidation::test_min_count[-100]", "tests/test_factories.py::TestStringSpecValidation::TestCountValidation::test_int_count[-0.5]", "tests/test_factories.py::TestStringSpecValidation::TestCountValidation::test_int_count[0.5]", "tests/test_factories.py::TestStringSpecValidation::TestCountValidation::test_int_count[2.71]", "tests/test_factories.py::TestStringSpecValidation::TestCountValidation::test_maxlength_spec[xxx]", "tests/test_factories.py::TestStringSpecValidation::TestCountValidation::test_maxlength_spec[xxy]", "tests/test_factories.py::TestStringSpecValidation::TestCountValidation::test_maxlength_spec[773]", "tests/test_factories.py::TestStringSpecValidation::TestCountValidation::test_maxlength_spec[833]", "tests/test_factories.py::TestStringSpecValidation::TestCountValidation::test_count_spec_failure[]", "tests/test_factories.py::TestStringSpecValidation::TestCountValidation::test_count_spec_failure[x]", "tests/test_factories.py::TestStringSpecValidation::TestCountValidation::test_count_spec_failure[xx]", "tests/test_factories.py::TestStringSpecValidation::TestCountValidation::test_count_spec_failure[xxxx]", "tests/test_factories.py::TestStringSpecValidation::TestCountValidation::test_count_spec_failure[xxxxx]", "tests/test_factories.py::TestStringSpecValidation::TestCountValidation::test_count_and_minlength_or_maxlength_agreement[opts0]", "tests/test_factories.py::TestStringSpecValidation::TestCountValidation::test_count_and_minlength_or_maxlength_agreement[opts1]", "tests/test_factories.py::TestStringSpecValidation::TestCountValidation::test_count_and_minlength_or_maxlength_agreement[opts2]", "tests/test_factories.py::TestStringSpecValidation::TestMinlengthSpec::test_min_minlength[-1]", "tests/test_factories.py::TestStringSpecValidation::TestMinlengthSpec::test_min_minlength[-100]", "tests/test_factories.py::TestStringSpecValidation::TestMinlengthSpec::test_int_minlength[-0.5]", "tests/test_factories.py::TestStringSpecValidation::TestMinlengthSpec::test_int_minlength[0.5]", "tests/test_factories.py::TestStringSpecValidation::TestMinlengthSpec::test_int_minlength[2.71]", "tests/test_factories.py::TestStringSpecValidation::TestMinlengthSpec::test_is_minlength[abcde]", "tests/test_factories.py::TestStringSpecValidation::TestMinlengthSpec::test_is_minlength[abcdef]", "tests/test_factories.py::TestStringSpecValidation::TestMinlengthSpec::test_is_not_minlength[None]", "tests/test_factories.py::TestStringSpecValidation::TestMinlengthSpec::test_is_not_minlength[25]", "tests/test_factories.py::TestStringSpecValidation::TestMinlengthSpec::test_is_not_minlength[3.14]", "tests/test_factories.py::TestStringSpecValidation::TestMinlengthSpec::test_is_not_minlength[v3]", "tests/test_factories.py::TestStringSpecValidation::TestMinlengthSpec::test_is_not_minlength[v4]", "tests/test_factories.py::TestStringSpecValidation::TestMinlengthSpec::test_is_not_minlength[]", "tests/test_factories.py::TestStringSpecValidation::TestMinlengthSpec::test_is_not_minlength[a]", "tests/test_factories.py::TestStringSpecValidation::TestMinlengthSpec::test_is_not_minlength[ab]", "tests/test_factories.py::TestStringSpecValidation::TestMinlengthSpec::test_is_not_minlength[abc]", "tests/test_factories.py::TestStringSpecValidation::TestMinlengthSpec::test_is_not_minlength[abcd]", "tests/test_factories.py::TestStringSpecValidation::TestMaxlengthSpec::test_min_maxlength[-1]", "tests/test_factories.py::TestStringSpecValidation::TestMaxlengthSpec::test_min_maxlength[-100]", "tests/test_factories.py::TestStringSpecValidation::TestMaxlengthSpec::test_int_maxlength[-0.5]", "tests/test_factories.py::TestStringSpecValidation::TestMaxlengthSpec::test_int_maxlength[0.5]", "tests/test_factories.py::TestStringSpecValidation::TestMaxlengthSpec::test_int_maxlength[2.71]", "tests/test_factories.py::TestStringSpecValidation::TestMaxlengthSpec::test_is_maxlength[]", "tests/test_factories.py::TestStringSpecValidation::TestMaxlengthSpec::test_is_maxlength[a]", "tests/test_factories.py::TestStringSpecValidation::TestMaxlengthSpec::test_is_maxlength[ab]", "tests/test_factories.py::TestStringSpecValidation::TestMaxlengthSpec::test_is_maxlength[abc]", "tests/test_factories.py::TestStringSpecValidation::TestMaxlengthSpec::test_is_maxlength[abcd]", "tests/test_factories.py::TestStringSpecValidation::TestMaxlengthSpec::test_is_maxlength[abcde]", "tests/test_factories.py::TestStringSpecValidation::TestMaxlengthSpec::test_is_not_maxlength[None]", "tests/test_factories.py::TestStringSpecValidation::TestMaxlengthSpec::test_is_not_maxlength[25]", "tests/test_factories.py::TestStringSpecValidation::TestMaxlengthSpec::test_is_not_maxlength[3.14]", "tests/test_factories.py::TestStringSpecValidation::TestMaxlengthSpec::test_is_not_maxlength[v3]", "tests/test_factories.py::TestStringSpecValidation::TestMaxlengthSpec::test_is_not_maxlength[v4]", "tests/test_factories.py::TestStringSpecValidation::TestMaxlengthSpec::test_is_not_maxlength[abcdef]", "tests/test_factories.py::TestStringSpecValidation::TestMaxlengthSpec::test_is_not_maxlength[abcdefg]", "tests/test_factories.py::TestStringSpecValidation::test_minlength_and_maxlength_agreement", "tests/test_factories.py::TestStringSpecValidation::TestRegexSpec::test_is_zipcode[10017]", "tests/test_factories.py::TestStringSpecValidation::TestRegexSpec::test_is_zipcode[10017-3332]", "tests/test_factories.py::TestStringSpecValidation::TestRegexSpec::test_is_zipcode[37779]", "tests/test_factories.py::TestStringSpecValidation::TestRegexSpec::test_is_zipcode[37779-2770]", "tests/test_factories.py::TestStringSpecValidation::TestRegexSpec::test_is_zipcode[00000]", "tests/test_factories.py::TestStringSpecValidation::TestRegexSpec::test_is_not_zipcode[None]", "tests/test_factories.py::TestStringSpecValidation::TestRegexSpec::test_is_not_zipcode[25]", "tests/test_factories.py::TestStringSpecValidation::TestRegexSpec::test_is_not_zipcode[3.14]", "tests/test_factories.py::TestStringSpecValidation::TestRegexSpec::test_is_not_zipcode[v3]", "tests/test_factories.py::TestStringSpecValidation::TestRegexSpec::test_is_not_zipcode[v4]", "tests/test_factories.py::TestStringSpecValidation::TestRegexSpec::test_is_not_zipcode[abcdef]", "tests/test_factories.py::TestStringSpecValidation::TestRegexSpec::test_is_not_zipcode[abcdefg]", "tests/test_factories.py::TestStringSpecValidation::TestRegexSpec::test_is_not_zipcode[100017]", "tests/test_factories.py::TestStringSpecValidation::TestRegexSpec::test_is_not_zipcode[10017-383]", "tests/test_factories.py::TestStringSpecValidation::test_regex_and_format_agreement[opts0]", "tests/test_factories.py::TestStringSpecValidation::test_regex_and_format_agreement[opts1]", "tests/test_factories.py::TestStringSpecValidation::test_regex_and_format_agreement[opts2]", "tests/test_factories.py::TestStringFormatValidation::TestISODateFormat::test_is_date_str[2019-10-12]", "tests/test_factories.py::TestStringFormatValidation::TestISODateFormat::test_is_date_str[1945-09-02]", "tests/test_factories.py::TestStringFormatValidation::TestISODateFormat::test_is_date_str[1066-10-14]", "tests/test_factories.py::TestStringFormatValidation::TestISODateFormat::test_is_not_date_str[None]", "tests/test_factories.py::TestStringFormatValidation::TestISODateFormat::test_is_not_date_str[25]", "tests/test_factories.py::TestStringFormatValidation::TestISODateFormat::test_is_not_date_str[3.14]", "tests/test_factories.py::TestStringFormatValidation::TestISODateFormat::test_is_not_date_str[v3]", "tests/test_factories.py::TestStringFormatValidation::TestISODateFormat::test_is_not_date_str[v4]", "tests/test_factories.py::TestStringFormatValidation::TestISODateFormat::test_is_not_date_str[abcdef]", "tests/test_factories.py::TestStringFormatValidation::TestISODateFormat::test_is_not_date_str[abcdefg]", "tests/test_factories.py::TestStringFormatValidation::TestISODateFormat::test_is_not_date_str[100017]", "tests/test_factories.py::TestStringFormatValidation::TestISODateFormat::test_is_not_date_str[10017-383]", "tests/test_factories.py::TestStringFormatValidation::TestISODateFormat::test_is_not_date_str[1945-9-2]", "tests/test_factories.py::TestStringFormatValidation::TestISODateFormat::test_is_not_date_str[430-10-02]", "tests/test_factories.py::TestStringFormatValidation::TestISODatetimeFormat::test_is_datetime_str[2019-10-12T18:03:50.617-00:00]", "tests/test_factories.py::TestStringFormatValidation::TestISODatetimeFormat::test_is_datetime_str[1945-09-02T18:03:50.617-00:00]", "tests/test_factories.py::TestStringFormatValidation::TestISODatetimeFormat::test_is_datetime_str[1066-10-14T18:03:50.617-00:00]", "tests/test_factories.py::TestStringFormatValidation::TestISODatetimeFormat::test_is_datetime_str[2019-10-12]", "tests/test_factories.py::TestStringFormatValidation::TestISODatetimeFormat::test_is_datetime_str[1945-09-02]", "tests/test_factories.py::TestStringFormatValidation::TestISODatetimeFormat::test_is_datetime_str[1066-10-14]", "tests/test_factories.py::TestStringFormatValidation::TestISODatetimeFormat::test_is_not_datetime_str[None]", "tests/test_factories.py::TestStringFormatValidation::TestISODatetimeFormat::test_is_not_datetime_str[25]", "tests/test_factories.py::TestStringFormatValidation::TestISODatetimeFormat::test_is_not_datetime_str[3.14]", "tests/test_factories.py::TestStringFormatValidation::TestISODatetimeFormat::test_is_not_datetime_str[v3]", "tests/test_factories.py::TestStringFormatValidation::TestISODatetimeFormat::test_is_not_datetime_str[v4]", "tests/test_factories.py::TestStringFormatValidation::TestISODatetimeFormat::test_is_not_datetime_str[abcdef]", "tests/test_factories.py::TestStringFormatValidation::TestISODatetimeFormat::test_is_not_datetime_str[abcdefg]", "tests/test_factories.py::TestStringFormatValidation::TestISODatetimeFormat::test_is_not_datetime_str[100017]", "tests/test_factories.py::TestStringFormatValidation::TestISODatetimeFormat::test_is_not_datetime_str[10017-383]", "tests/test_factories.py::TestStringFormatValidation::TestISODatetimeFormat::test_is_not_datetime_str[1945-9-2]", "tests/test_factories.py::TestStringFormatValidation::TestISODatetimeFormat::test_is_not_datetime_str[430-10-02]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_time_str[18]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_time_str[18-00:00]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_time_str[18.335]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_time_str[18.335-00:00]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_time_str[18:03]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_time_str[18:03-00:00]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_time_str[18:03.335]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_time_str[18:03.335-00:00]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_time_str[18:03:50]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_time_str[18:03:50-00:00]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_time_str[18:03:50.617]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_time_str[18:03:50.617-00:00]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_time_str[18:03:50.617332]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_time_str[18:03:50.617332-00:00]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_not_time_str[None]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_not_time_str[25]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_not_time_str[3.14]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_not_time_str[v3]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_not_time_str[v4]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_not_time_str[abcdef]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_not_time_str[abcdefg]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_not_time_str[100017]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_not_time_str[10017-383]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_not_time_str[1945-9-2]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_not_time_str[430-10-02]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_not_time_str[2019-10-12]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_not_time_str[1945-09-02]", "tests/test_factories.py::TestStringFormatValidation::TestISOTimeFormat::test_is_not_time_str[1066-10-14]", "tests/test_factories.py::TestStringFormatValidation::TestUUIDFormat::test_is_uuid_str[91d7e5f0-7567-4569-a61d-02ed57507f47]", "tests/test_factories.py::TestStringFormatValidation::TestUUIDFormat::test_is_uuid_str[91d7e5f075674569a61d02ed57507f47]", "tests/test_factories.py::TestStringFormatValidation::TestUUIDFormat::test_is_uuid_str[06130510-83A5-478B-B65C-6A8DC2104E2F]", "tests/test_factories.py::TestStringFormatValidation::TestUUIDFormat::test_is_uuid_str[0613051083A5478BB65C6A8DC2104E2F]", "tests/test_factories.py::TestStringFormatValidation::TestUUIDFormat::test_is_not_uuid_str[None]", "tests/test_factories.py::TestStringFormatValidation::TestUUIDFormat::test_is_not_uuid_str[25]", "tests/test_factories.py::TestStringFormatValidation::TestUUIDFormat::test_is_not_uuid_str[3.14]", "tests/test_factories.py::TestStringFormatValidation::TestUUIDFormat::test_is_not_uuid_str[v3]", "tests/test_factories.py::TestStringFormatValidation::TestUUIDFormat::test_is_not_uuid_str[v4]", "tests/test_factories.py::TestStringFormatValidation::TestUUIDFormat::test_is_not_uuid_str[abcdef]", "tests/test_factories.py::TestStringFormatValidation::TestUUIDFormat::test_is_not_uuid_str[abcdefg]", "tests/test_factories.py::TestStringFormatValidation::TestUUIDFormat::test_is_not_uuid_str[100017]", "tests/test_factories.py::TestStringFormatValidation::TestUUIDFormat::test_is_not_uuid_str[10017-383]", "tests/test_factories.py::TestUUIDSpecValidation::test_uuid_validation[6281d852-ef4d-11e9-9002-4c327592fea9]", "tests/test_factories.py::TestUUIDSpecValidation::test_uuid_validation[0e8d7ceb-56e8-36d2-9b54-ea48d4bdea3f]", "tests/test_factories.py::TestUUIDSpecValidation::test_uuid_validation[c5a28680-986f-4f0d-8187-80d1fbe22059]", "tests/test_factories.py::TestUUIDSpecValidation::test_uuid_validation[3BE59FF6-9C75-4027-B132-C9792D84547D]", "tests/test_factories.py::TestUUIDSpecValidation::test_uuid_validation[10988ff4-136c-5ca7-ab35-a686a56c22c4]", "tests/test_factories.py::TestUUIDSpecValidation::test_uuid_validation_failure[]", "tests/test_factories.py::TestUUIDSpecValidation::test_uuid_validation_failure[5_0]", "tests/test_factories.py::TestUUIDSpecValidation::test_uuid_validation_failure[abcde]", "tests/test_factories.py::TestUUIDSpecValidation::test_uuid_validation_failure[ABCDe]", "tests/test_factories.py::TestUUIDSpecValidation::test_uuid_validation_failure[5_1]", "tests/test_factories.py::TestUUIDSpecValidation::test_uuid_validation_failure[3.14]", "tests/test_factories.py::TestUUIDSpecValidation::test_uuid_validation_failure[None]", "tests/test_factories.py::TestUUIDSpecValidation::test_uuid_validation_failure[v7]", "tests/test_factories.py::TestUUIDSpecValidation::test_uuid_validation_failure[v8]", "tests/test_factories.py::TestUUIDSpecValidation::test_uuid_validation_failure[v9]", "tests/test_factories.py::TestUUIDSpecValidation::TestUUIDVersionSpecValidation::test_invalid_uuid_version_spec[versions0]", "tests/test_factories.py::TestUUIDSpecValidation::TestUUIDVersionSpecValidation::test_invalid_uuid_version_spec[versions1]", "tests/test_factories.py::TestUUIDSpecValidation::TestUUIDVersionSpecValidation::test_invalid_uuid_version_spec[versions2]", "tests/test_factories.py::TestUUIDSpecValidation::TestUUIDVersionSpecValidation::test_uuid_validation[6281d852-ef4d-11e9-9002-4c327592fea9]", "tests/test_factories.py::TestUUIDSpecValidation::TestUUIDVersionSpecValidation::test_uuid_validation[c5a28680-986f-4f0d-8187-80d1fbe22059]", "tests/test_factories.py::TestUUIDSpecValidation::TestUUIDVersionSpecValidation::test_uuid_validation[3BE59FF6-9C75-4027-B132-C9792D84547D]", "tests/test_factories.py::TestUUIDSpecValidation::TestUUIDVersionSpecValidation::test_uuid_validation_failure[0e8d7ceb-56e8-36d2-9b54-ea48d4bdea3f]", "tests/test_factories.py::TestUUIDSpecValidation::TestUUIDVersionSpecValidation::test_uuid_validation_failure[10988ff4-136c-5ca7-ab35-a686a56c22c4]", "tests/test_factories.py::TestUUIDSpecValidation::TestUUIDVersionSpecValidation::test_uuid_validation_failure[]", "tests/test_factories.py::TestUUIDSpecValidation::TestUUIDVersionSpecValidation::test_uuid_validation_failure[5_0]", "tests/test_factories.py::TestUUIDSpecValidation::TestUUIDVersionSpecValidation::test_uuid_validation_failure[abcde]", "tests/test_factories.py::TestUUIDSpecValidation::TestUUIDVersionSpecValidation::test_uuid_validation_failure[ABCDe]", "tests/test_factories.py::TestUUIDSpecValidation::TestUUIDVersionSpecValidation::test_uuid_validation_failure[5_1]", "tests/test_factories.py::TestUUIDSpecValidation::TestUUIDVersionSpecValidation::test_uuid_validation_failure[3.14]", "tests/test_factories.py::TestUUIDSpecValidation::TestUUIDVersionSpecValidation::test_uuid_validation_failure[None]", "tests/test_factories.py::TestUUIDSpecValidation::TestUUIDVersionSpecValidation::test_uuid_validation_failure[v9]", "tests/test_factories.py::TestUUIDSpecValidation::TestUUIDVersionSpecValidation::test_uuid_validation_failure[v10]", "tests/test_factories.py::TestUUIDSpecValidation::TestUUIDVersionSpecValidation::test_uuid_validation_failure[v11]" ]
b314d36fab96cb63477c1d95c734e3bd0f807ed5