index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
729,739
minidir
__init__
null
def __init__(self) -> None: self._dir = {} pass
(self) -> NoneType
729,740
minidir
__iter__
null
def __iter__(self) -> typing.Iterator[Path]: paths: typing.List[Path] = [] for key in self._dir: paths.append(SomePath(key)) return iter(paths)
(self) -> Iterator[minidir.Path]
729,741
minidir
create
null
def create(self, path: Path) -> File: if str(path) in self._dir: raise NameCollision() self._dir[str(path)] = b"" return _FakeDirectoryFile(self._dir, str(path))
(self, path: minidir.Path) -> minidir.File
729,742
minidir
get
null
def get(self, path: Path) -> File: if str(path) not in self._dir: raise NotFound() return _FakeDirectoryFile(self._dir, str(path))
(self, path: minidir.Path) -> minidir.File
729,743
minidir
remove
null
def remove(self, path: Path) -> None: if str(path) not in self._dir: raise NotFound() del self._dir[str(path)]
(self, path: minidir.Path) -> NoneType
729,744
minidir
File
File is a interface that can read and write content.
class File(typing.Protocol): """File is a interface that can read and write content.""" def read(self) -> bytes: pass def write(self, content: bytes) -> None: pass
(*args, **kwargs)
729,747
minidir
read
null
def read(self) -> bytes: pass
(self) -> bytes
729,748
minidir
write
null
def write(self, content: bytes) -> None: pass
(self, content: bytes) -> NoneType
729,749
minidir
NameCollision
NameCollision is the error that try to create a file with invalid path.
class NameCollision(Exception): """NameCollision is the error that try to create a file with invalid path.""" pass
null
729,750
minidir
NotFound
NotFound is the error that there is no file for some path.
class NotFound(Exception): """NotFound is the error that there is no file for some path.""" pass
null
729,751
minidir
Path
Path is a interface that represent the path and name of some file.
class Path(typing.Protocol): """Path is a interface that represent the path and name of some file.""" def __hash__(self) -> int: pass def __eq__(self, other) -> bool: pass def __str__(self) -> str: pass def parent(self) -> str: pass def base(self) -> str: pass
(*args, **kwargs)
729,752
minidir
__eq__
null
def __eq__(self, other) -> bool: pass
(self, other) -> bool
729,753
minidir
__hash__
null
def __hash__(self) -> int: pass
(self) -> int
729,755
minidir
__str__
null
def __str__(self) -> str: pass
(self) -> str
729,757
minidir
base
null
def base(self) -> str: pass
(self) -> str
729,758
minidir
parent
null
def parent(self) -> str: pass
(self) -> str
729,759
minidir
SomePath
null
class SomePath: _path: pathlib.PurePath def __init__(self, path: str) -> None: self._path = pathlib.PurePath(path) self._path.__hash__ def __hash__(self) -> int: return hash(self._path) def __eq__(self, other) -> bool: if not isinstance(other, SomePath): return NotImplemented return self._path == other._path def __str__(self) -> str: return str(self._path) def parent(self) -> str: return str(self._path.parent) def base(self) -> str: return self._path.name
(path: str) -> None
729,760
minidir
__eq__
null
def __eq__(self, other) -> bool: if not isinstance(other, SomePath): return NotImplemented return self._path == other._path
(self, other) -> bool
729,761
minidir
__hash__
null
def __hash__(self) -> int: return hash(self._path)
(self) -> int
729,762
minidir
__init__
null
def __init__(self, path: str) -> None: self._path = pathlib.PurePath(path) self._path.__hash__
(self, path: str) -> NoneType
729,763
minidir
__str__
null
def __str__(self) -> str: return str(self._path)
(self) -> str
729,764
minidir
base
null
def base(self) -> str: return self._path.name
(self) -> str
729,765
minidir
parent
null
def parent(self) -> str: return str(self._path.parent)
(self) -> str
729,766
minidir
SystemDirectory
SystemDirectory is a Directory implementation for real file system.
class SystemDirectory: """SystemDirectory is a Directory implementation for real file system.""" _root: str _file_paths: typing.Set[str] def __init__(self, root: str): self._root = root self._file_paths = set() for dir_path, _, files in os.walk(root): for file in files: self._file_paths.add(os.path.join(dir_path, file)) def __iter__(self) -> typing.Iterator[Path]: paths: typing.List[Path] = [] for file_path in self._file_paths: relative = pathlib.PurePath(file_path).relative_to(self._root) paths.append(SomePath(str(relative))) return iter(paths) def create(self, path: Path) -> File: self._ensure_folder(path) try: with open(self._to_full_path(path), "xb") as _: pass except FileExistsError: raise NameCollision() if self._to_full_path(path) in self._file_paths: raise NameCollision() self._file_paths.add(self._to_full_path(path)) return _SystemFile(self._to_full_path(path)) def remove(self, path: Path) -> None: try: os.remove(self._to_full_path(path)) except FileNotFoundError: raise NotFound() self._file_paths.remove(self._to_full_path(path)) def get(self, path: Path) -> File: if self._to_full_path(path) not in self._file_paths: raise NotFound() self._file_paths.add(self._to_full_path(path)) return _SystemFile(self._to_full_path(path)) def _to_full_path(self, path: Path) -> str: return os.path.join(self._root, str(path)) def _ensure_folder(self, path: Path) -> None: path_object = pathlib.PurePath(os.path.join(self._root, str(path))) os.makedirs(path_object.parent, exist_ok=True)
(root: str)
729,767
minidir
__init__
null
def __init__(self, root: str): self._root = root self._file_paths = set() for dir_path, _, files in os.walk(root): for file in files: self._file_paths.add(os.path.join(dir_path, file))
(self, root: str)
729,768
minidir
__iter__
null
def __iter__(self) -> typing.Iterator[Path]: paths: typing.List[Path] = [] for file_path in self._file_paths: relative = pathlib.PurePath(file_path).relative_to(self._root) paths.append(SomePath(str(relative))) return iter(paths)
(self) -> Iterator[minidir.Path]
729,769
minidir
_ensure_folder
null
def _ensure_folder(self, path: Path) -> None: path_object = pathlib.PurePath(os.path.join(self._root, str(path))) os.makedirs(path_object.parent, exist_ok=True)
(self, path: minidir.Path) -> NoneType
729,770
minidir
_to_full_path
null
def _to_full_path(self, path: Path) -> str: return os.path.join(self._root, str(path))
(self, path: minidir.Path) -> str
729,771
minidir
create
null
def create(self, path: Path) -> File: self._ensure_folder(path) try: with open(self._to_full_path(path), "xb") as _: pass except FileExistsError: raise NameCollision() if self._to_full_path(path) in self._file_paths: raise NameCollision() self._file_paths.add(self._to_full_path(path)) return _SystemFile(self._to_full_path(path))
(self, path: minidir.Path) -> minidir.File
729,772
minidir
get
null
def get(self, path: Path) -> File: if self._to_full_path(path) not in self._file_paths: raise NotFound() self._file_paths.add(self._to_full_path(path)) return _SystemFile(self._to_full_path(path))
(self, path: minidir.Path) -> minidir.File
729,773
minidir
remove
null
def remove(self, path: Path) -> None: try: os.remove(self._to_full_path(path)) except FileNotFoundError: raise NotFound() self._file_paths.remove(self._to_full_path(path))
(self, path: minidir.Path) -> NoneType
729,774
minidir
_FakeDirectoryFile
null
class _FakeDirectoryFile: _dir: typing.Dict[str, bytes] _path: str def __init__(self, dir: typing.Dict[str, bytes], path: str) -> None: self._dir = dir self._path = path def read(self) -> bytes: return self._dir[self._path] def write(self, content: bytes) -> None: self._dir[self._path] = content
(dir: Dict[str, bytes], path: str) -> None
729,775
minidir
__init__
null
def __init__(self, dir: typing.Dict[str, bytes], path: str) -> None: self._dir = dir self._path = path
(self, dir: Dict[str, bytes], path: str) -> NoneType
729,776
minidir
read
null
def read(self) -> bytes: return self._dir[self._path]
(self) -> bytes
729,777
minidir
write
null
def write(self, content: bytes) -> None: self._dir[self._path] = content
(self, content: bytes) -> NoneType
729,778
minidir
_SystemFile
null
class _SystemFile: _path: str def __init__(self, path: str): self._path = path def read(self) -> bytes: with open(self._path, "rb") as file_: return file_.read() def write(self, content: bytes) -> None: with open(self._path, "wb") as file_: file_.write(content)
(path: str)
729,780
minidir
read
null
def read(self) -> bytes: with open(self._path, "rb") as file_: return file_.read()
(self) -> bytes
729,781
minidir
write
null
def write(self, content: bytes) -> None: with open(self._path, "wb") as file_: file_.write(content)
(self, content: bytes) -> NoneType
729,785
yake.yake
KeywordExtractor
null
class KeywordExtractor(object): def __init__(self, lan="en", n=3, dedupLim=0.9, dedupFunc='seqm', windowsSize=1, top=20, features=None, stopwords=None): self.lan = lan dir_path = os.path.dirname(os.path.realpath(__file__)) local_path = os.path.join("StopwordsList", "stopwords_%s.txt" % lan[:2].lower()) if os.path.exists(os.path.join(dir_path,local_path)) == False: local_path = os.path.join("StopwordsList", "stopwords_noLang.txt") resource_path = os.path.join(dir_path,local_path) if stopwords is None: try: with open(resource_path, encoding='utf-8') as stop_fil: self.stopword_set = set( stop_fil.read().lower().split("\n") ) except: print('Warning, read stopword list as ISO-8859-1') with open(resource_path, encoding='ISO-8859-1') as stop_fil: self.stopword_set = set( stop_fil.read().lower().split("\n") ) else: self.stopword_set = set(stopwords) self.n = n self.top = top self.dedupLim = dedupLim self.features = features self.windowsSize = windowsSize if dedupFunc == 'jaro_winkler' or dedupFunc == 'jaro': self.dedu_function = self.jaro elif dedupFunc.lower() == 'sequencematcher' or dedupFunc.lower() == 'seqm': self.dedu_function = self.seqm else: self.dedu_function = self.levs def jaro(self, cand1, cand2): return jellyfish.jaro_winkler(cand1, cand2 ) def levs(self, cand1, cand2): return 1.-jellyfish.levenshtein_distance(cand1, cand2 ) / max(len(cand1),len(cand2)) def seqm(self, cand1, cand2): return Levenshtein.ratio(cand1, cand2) def extract_keywords(self, text): try: if not(len(text) > 0): return [] text = text.replace('\n\t',' ') dc = DataCore(text=text, stopword_set=self.stopword_set, windowsSize=self.windowsSize, n=self.n) dc.build_single_terms_features(features=self.features) dc.build_mult_terms_features(features=self.features) resultSet = [] todedup = sorted([cc for cc in dc.candidates.values() if cc.isValid()], key=lambda c: c.H) if self.dedupLim >= 1.: return ([ (cand.H, cand.unique_kw) for cand in todedup])[:self.top] for cand in todedup: toadd = True for (h, candResult) in resultSet: dist = self.dedu_function(cand.unique_kw, candResult.unique_kw) if dist > self.dedupLim: toadd = False break if toadd: resultSet.append( (cand.H, cand) ) if len(resultSet) == self.top: break return [ (cand.kw,h) for (h,cand) in resultSet] except Exception as e: print(f"Warning! Exception: {e} generated by the following text: '{text}' ") return []
(lan='en', n=3, dedupLim=0.9, dedupFunc='seqm', windowsSize=1, top=20, features=None, stopwords=None)
729,786
yake.yake
__init__
null
def __init__(self, lan="en", n=3, dedupLim=0.9, dedupFunc='seqm', windowsSize=1, top=20, features=None, stopwords=None): self.lan = lan dir_path = os.path.dirname(os.path.realpath(__file__)) local_path = os.path.join("StopwordsList", "stopwords_%s.txt" % lan[:2].lower()) if os.path.exists(os.path.join(dir_path,local_path)) == False: local_path = os.path.join("StopwordsList", "stopwords_noLang.txt") resource_path = os.path.join(dir_path,local_path) if stopwords is None: try: with open(resource_path, encoding='utf-8') as stop_fil: self.stopword_set = set( stop_fil.read().lower().split("\n") ) except: print('Warning, read stopword list as ISO-8859-1') with open(resource_path, encoding='ISO-8859-1') as stop_fil: self.stopword_set = set( stop_fil.read().lower().split("\n") ) else: self.stopword_set = set(stopwords) self.n = n self.top = top self.dedupLim = dedupLim self.features = features self.windowsSize = windowsSize if dedupFunc == 'jaro_winkler' or dedupFunc == 'jaro': self.dedu_function = self.jaro elif dedupFunc.lower() == 'sequencematcher' or dedupFunc.lower() == 'seqm': self.dedu_function = self.seqm else: self.dedu_function = self.levs
(self, lan='en', n=3, dedupLim=0.9, dedupFunc='seqm', windowsSize=1, top=20, features=None, stopwords=None)
729,787
yake.yake
extract_keywords
null
def extract_keywords(self, text): try: if not(len(text) > 0): return [] text = text.replace('\n\t',' ') dc = DataCore(text=text, stopword_set=self.stopword_set, windowsSize=self.windowsSize, n=self.n) dc.build_single_terms_features(features=self.features) dc.build_mult_terms_features(features=self.features) resultSet = [] todedup = sorted([cc for cc in dc.candidates.values() if cc.isValid()], key=lambda c: c.H) if self.dedupLim >= 1.: return ([ (cand.H, cand.unique_kw) for cand in todedup])[:self.top] for cand in todedup: toadd = True for (h, candResult) in resultSet: dist = self.dedu_function(cand.unique_kw, candResult.unique_kw) if dist > self.dedupLim: toadd = False break if toadd: resultSet.append( (cand.H, cand) ) if len(resultSet) == self.top: break return [ (cand.kw,h) for (h,cand) in resultSet] except Exception as e: print(f"Warning! Exception: {e} generated by the following text: '{text}' ") return []
(self, text)
729,788
yake.yake
jaro
null
def jaro(self, cand1, cand2): return jellyfish.jaro_winkler(cand1, cand2 )
(self, cand1, cand2)
729,789
yake.yake
levs
null
def levs(self, cand1, cand2): return 1.-jellyfish.levenshtein_distance(cand1, cand2 ) / max(len(cand1),len(cand2))
(self, cand1, cand2)
729,790
yake.yake
seqm
null
def seqm(self, cand1, cand2): return Levenshtein.ratio(cand1, cand2)
(self, cand1, cand2)
729,794
touca._client
Client
class Client: """ """ @classmethod def instance(cls): if not hasattr(cls, "_instance"): cls._instance = cls() return cls._instance def __init__(self) -> None: self._cases: Dict[str, Case] = dict() self._configured = False self._configuration_error = str() self._options: Dict[str, Any] = dict() self._threads_case = str() self._threads_cases: Dict[int, str] = dict() self._transport = Transport() self._type_handler = TypeHandler() def _active_testcase_name(self) -> Optional[str]: if not self._configured: return None if self._options.get("concurrency"): return self._threads_case return self._threads_cases.get(get_ident()) def _prepare_save(self, path: str, cases) -> List[Case]: from pathlib import Path Path(path).parent.mkdir(parents=True, exist_ok=True) if cases: return [self._cases[x] for x in self._cases if x in cases] return list(self._cases.values()) def _post(self, path: str, body, headers: Dict[str, str] = {}): response = self._transport.request( method="POST", path=path, body=body, content_type="application/octet-stream", extra_headers=headers, ) if response.status == 204: return if response.status == 200: return response.data.decode("utf-8") reason = "" if response.status == 400: error = response.data.decode("utf-8") if "batch is sealed" in error: reason = " This version is already submitted and sealed." if "team not found" in error: reason = " This team does not exist." raise ToucaError("transport_post", reason) def configure(self, **kwargs) -> bool: """ Configures the Touca client. Must be called before declaring test cases and adding results to the client. Should be regarded as a potentially expensive operation. Should be called only from your test environment. :py:meth:`~configure` takes a variety of configuration parameters documented below. All of these parameters are optional. Calling this function without any parameters is possible: the client can capture behavior and performance data and store them on a local filesystem but it will not be able to post them to the Touca server. In most cases, You will need to pass API Key and API URL during the configuration. The code below shows the common pattern in which API URL is given in long format (it includes the team slug and the suite slug) and API Key as well as the version of the code under test are specified as environment variables ``TOUCA_API_KEY`` and ``TOUCA_TEST_VERSION``, respectively:: touca.configure(api_url='https://api.touca.io/@/acme/students') As long as the API Key and API URL to the Touca server are known to the client, it attempts to authenticate with the Touca Server. You can explicitly disable this communication in rare cases by setting configuration option ``offline`` to ``False``. You can call :py:meth:`~configure` any number of times. The client preserves the configuration parameters specified in previous calls to this function. :type api_key: str, optional :param api_key: (optional) API Key issued by the Touca server that identifies who is submitting the data. Since the value should be treated as a secret, we recommend that you pass it as an environment variable ``TOUCA_API_KEY`` instead. :type api_url: str, optional :param api_url: (optional) URL to the Touca server API. Can be provided either in long format like ``https://api.touca.io/@/myteam/mysuite/version`` or in short format like ``https://api.touca.io``. If the team, suite, or version are specified, you do not need to specify them separately. :type team: str, optional :param team: (optional) slug of your team on the Touca server. :type suite: str, optional :param suite: slug of the suite on the Touca server that corresponds to your workflow under test. :type version: str, optional :param version: version of your workflow under test. :type offline: bool, optional :param offline: determines whether client should connect with the Touca server during the configuration. Defaults to ``False`` when ``api_url`` or ``api_key`` are provided. :type concurrency: bool, optional :param concurrency: determines whether the scope of test case declaration is bound to the thread performing the declaration, or covers all other threads. Defaults to ``True``. If set to ``True``, when a thread calls :py:meth:`~declare_testcase`, all other threads also have their most recent test case changed to the newly declared test case and any subsequent call to data capturing functions such as :py:meth:`~check` will affect the newly declared test case. """ from touca._options import assign_options, update_core_options self._configuration_error = "" try: assign_options(self._options, kwargs) self._configured = update_core_options(self._options, self._transport) except RuntimeError as err: self._configuration_error = str(err) return False return True def is_configured(self) -> bool: """ Checks if previous call(s) to :py:meth:`~configure` have set the right combination of configuration parameters to enable the client to perform expected tasks. We recommend that you perform this check after client configuration and before calling other functions of the library:: if not touca.is_configured(): print(touca.configuration_error()) sys.exit(1) At a minimum, the client is considered configured if it can capture test results and store them locally on the filesystem. A single call to :py:meth:`~configure` without any configuration parameters can help us get to this state. However, if a subsequent call to :py:meth:`~configure` sets the parameter ``api_url`` in short form without specifying parameters such as ``team``, ``suite`` and ``version``, the client configuration is incomplete: We infer that the user intends to submit results but the provided configuration parameters are not sufficient to perform this operation. :return: ``True`` if the client is properly configured :rtype: bool :see also: :py:meth:`~configure` """ return self._configured def configuration_error(self) -> str: """ Provides the most recent error, if any, that is encountered during client configuration. :return: short description of the most recent configuration error :rtype: str """ return self._configuration_error def declare_testcase(self, name: str): """ Declares name of the test case to which all subsequent results will be submitted until a new test case is declared. If configuration parameter ``concurrency`` is set to ``"enabled"``, when a thread calls `declare_testcase` all other threads also have their most recent testcase changed to the newly declared one. Otherwise, each thread will submit to its own testcase. :param name: name of the testcase to be declared """ if not self._configured: return if name not in self._cases: self._cases[name] = Case( team=self._options.get("team"), suite=self._options.get("suite"), version=self._options.get("version"), name=name, ) self._threads_case = name self._threads_cases[get_ident()] = name return self._cases.get(name) def forget_testcase(self, name: str): """ Removes all logged information associated with a given test case. This information is removed from memory, such that switching back to an already-declared or already-submitted test case would behave similar to when that test case was first declared. This information is removed, for all threads, regardless of the configuration option ``concurrency``. Information already submitted to the server will not be removed from the server. This operation is useful in long-running regression test frameworks, after submission of test case to the server, if memory consumed by the client library is a concern or if there is a risk that a future test case with a similar name may be executed. :param name: name of the testcase to be removed from memory :raises ToucaError: when called with the name of a test case that was never declared """ if not self._configured: return if name not in self._cases: raise ToucaError("capture_forget", name) del self._cases[name] @casemethod def check(self, key: str, value: Any, *, rule: Optional[ComparisonRule] = None): return self._type_handler.transform(value) @casemethod def check_file(self, key: str, file): return @casemethod def assume(self, key: str, value: Any): return self._type_handler.transform(value) @casemethod def add_array_element(self, key: str, value: Any): return self._type_handler.transform(value) @casemethod def add_hit_count(self, key: str): return @casemethod def add_metric(self, key: str, milliseconds: int): return milliseconds @casemethod def start_timer(self, key: str): return @casemethod def stop_timer(self, key: str): return def add_serializer(self, datatype: Type, serializer: Callable[[Any], Dict]): """ Registers custom serialization logic for a given custom data type. Calling this function is rarely needed. The library already handles all custom data types by serializing all their properties. Custom serializers allow you to exclude a subset of an object properties during serialization. :param datattype: type to be serialized :param serializer: function that converts any object of the given type to a dictionary. """ self._type_handler.add_serializer(datatype, serializer) def save_binary(self, path: str, cases: list): """ Stores test results and performance benchmarks in binary format in a file of specified path. Touca binary files can be submitted at a later time to the Touca server. We do not recommend as a general practice for regression test tools to locally store their test results. This feature may be helpful for special cases such as when regression test tools have to be run in environments that have no access to the Touca server (e.g. running with no network access). :param path: path to file in which test results and performance benchmarks should be stored :param cases: names of test cases whose results should be stored. If a set is not specified or is set as empty, all test cases will be stored in the specified file. """ items = self._prepare_save(path, cases) content = serialize_messages([item.serialize() for item in items]) with open(path, mode="wb") as file: file.write(content) def save_json(self, path: str, cases: list): """ Stores test results and performance benchmarks in JSON format in a file of specified path. This feature may be helpful during development of regression tests tools for quick inspection of the test results and performance metrics being captured. :param path: path to file in which test results and performance benchmarks should be stored :param cases: names of test cases whose results should be stored. If a set is not specified or is set as empty, all test cases will be stored in the specified file. """ from json import dumps items = self._prepare_save(path, cases) content = dumps([testcase.json() for testcase in items]) with open(path, mode="wt") as file: file.write(content) def post(self, *, submit_async=False): """ Submits all test results recorded so far to Touca server. It is possible to call :py:meth:`~post` multiple times during runtime of the regression test tool. Test cases already submitted to the server whose test results have not changed, will not be resubmitted. It is also possible to add test results to a testcase after it is submitted to the server. Any subsequent call to :py:meth:`~post` will resubmit the modified test case. :raises ToucaError: when called on the client that is not configured to communicate with the Touca server. """ if not self._configured or self._options.get("offline"): raise ToucaError("capture_not_configured") content = serialize_messages( [item.serialize() for item in self._cases.values()] ) headers = {"X-Touca-Submission-Mode": "async" if submit_async else "sync"} result = self._post("/client/submit", content, headers) slugs = "/".join(self._options.get(x) for x in ["team", "suite", "version"]) for case in self._cases.values(): testcase_name = case._metadata().get("testcase") for key, value in case._results.items(): if isinstance(value.val, BlobType): self._post( f"/client/submit/artifact/{slugs}/{testcase_name}/{key}", value.val._value.binary(), ) return parse_comparison_result(result) if result else "sent" def seal(self): """ Notifies the Touca server that all test cases were executed for this version and no further test result is expected to be submitted. Expected to be called by the test tool once all test cases are executed and all test results are posted. Sealing the version is optional. The Touca server automatically performs this operation once a certain amount of time has passed since the last test case was submitted. This duration is configurable from the "Settings" tab in "Suite" Page. :raises ToucaError: when called on the client that is not configured to communicate with the Touca server. """ if not self._configured or self._options.get("offline"): raise ToucaError("capture_not_configured") slugs = "/".join(self._options.get(x) for x in ["team", "suite", "version"]) response = self._transport.request(method="POST", path=f"/batch/{slugs}/seal") if response.status == 403: raise ToucaError("auth_invalid_key") if response.status != 204: raise ToucaError("transport_seal")
() -> None
729,795
touca._client
__init__
null
def __init__(self) -> None: self._cases: Dict[str, Case] = dict() self._configured = False self._configuration_error = str() self._options: Dict[str, Any] = dict() self._threads_case = str() self._threads_cases: Dict[int, str] = dict() self._transport = Transport() self._type_handler = TypeHandler()
(self) -> NoneType
729,796
touca._client
_active_testcase_name
null
def _active_testcase_name(self) -> Optional[str]: if not self._configured: return None if self._options.get("concurrency"): return self._threads_case return self._threads_cases.get(get_ident())
(self) -> Optional[str]
729,797
touca._client
_post
null
def _post(self, path: str, body, headers: Dict[str, str] = {}): response = self._transport.request( method="POST", path=path, body=body, content_type="application/octet-stream", extra_headers=headers, ) if response.status == 204: return if response.status == 200: return response.data.decode("utf-8") reason = "" if response.status == 400: error = response.data.decode("utf-8") if "batch is sealed" in error: reason = " This version is already submitted and sealed." if "team not found" in error: reason = " This team does not exist." raise ToucaError("transport_post", reason)
(self, path: str, body, headers: Dict[str, str] = {})
729,798
touca._client
_prepare_save
null
def _prepare_save(self, path: str, cases) -> List[Case]: from pathlib import Path Path(path).parent.mkdir(parents=True, exist_ok=True) if cases: return [self._cases[x] for x in self._cases if x in cases] return list(self._cases.values())
(self, path: str, cases) -> List[touca._case.Case]
729,799
touca._client
add_array_element
Adds a given value to a list of results for the declared test case which is associated with the specified key. Could be considered as a helper utility function. This method is particularly helpful to log a list of items as they are found: .. code-block:: python for number in numbers: if is_prime(number): touca.add_array_element("prime numbers", number) touca.add_hit_count("number of primes") This pattern can be considered as a syntactic sugar for the following alternative: .. code-block:: python primes = [] for number in numbers: if is_prime(number): primes.append(number) if primes: touca.check("prime numbers", primes) touca.check("number of primes", len(primes)) The items added to the list are not required to be of the same type. The following code is acceptable: .. code-block:: python touca.check("prime numbers", 42) touca.check("prime numbers", "forty three") :raises RuntimeError: if specified key is already associated with a test result which was not iterable :param key: name to be associated with the logged test result :param value: element to be appended to the array :see also: :py:meth:`~check`
def casemethod(func): """ """ import inspect from functools import wraps func.__doc__ = inspect.getdoc(getattr(Case, func.__name__)) @wraps(func) def wrapper(self, *args, **kwargs): element = self._active_testcase_name() if not element: return testcase = self._cases.get(element) method = getattr(testcase, func.__name__) retval = func(self, *args, **kwargs) if not retval: method(*args, **kwargs) else: method(args[0], retval, **kwargs) return wrapper
(self, key: str, value: Any)
729,800
touca._client
add_hit_count
Increments value of key every time it is executed. creates the key with initial value of one if it does not exist. Could be considered as a helper utility function. This method is particularly helpful to track variables whose values are determined in loops with indeterminate execution cycles: .. code-block:: python for number in numbers: if is_prime(number): touca.add_array_element("prime numbers", number) touca.add_hit_count("number of primes") This pattern can be considered as a syntactic sugar for the following alternative: .. code-block:: python primes = [] for number in numbers: if is_prime(number): primes.append(number) if primes: touca.check("prime numbers", primes) touca.check("number of primes", len(primes)) :raises RuntimeError: if specified key is already associated with a test result which was not an integer :param key: name to be associated with the logged test result :see also: :py:meth:`~check`
def casemethod(func): """ """ import inspect from functools import wraps func.__doc__ = inspect.getdoc(getattr(Case, func.__name__)) @wraps(func) def wrapper(self, *args, **kwargs): element = self._active_testcase_name() if not element: return testcase = self._cases.get(element) method = getattr(testcase, func.__name__) retval = func(self, *args, **kwargs) if not retval: method(*args, **kwargs) else: method(args[0], retval, **kwargs) return wrapper
(self, key: str)
729,801
touca._client
add_metric
Adds an already obtained measurements to the list of captured performance benchmarks. Useful for logging a metric that is measured without using this SDK. :param key: name to be associated with this performance benchmark :param milliseconds: duration of this measurement in milliseconds
def casemethod(func): """ """ import inspect from functools import wraps func.__doc__ = inspect.getdoc(getattr(Case, func.__name__)) @wraps(func) def wrapper(self, *args, **kwargs): element = self._active_testcase_name() if not element: return testcase = self._cases.get(element) method = getattr(testcase, func.__name__) retval = func(self, *args, **kwargs) if not retval: method(*args, **kwargs) else: method(args[0], retval, **kwargs) return wrapper
(self, key: str, milliseconds: int)
729,802
touca._client
add_serializer
Registers custom serialization logic for a given custom data type. Calling this function is rarely needed. The library already handles all custom data types by serializing all their properties. Custom serializers allow you to exclude a subset of an object properties during serialization. :param datattype: type to be serialized :param serializer: function that converts any object of the given type to a dictionary.
def add_serializer(self, datatype: Type, serializer: Callable[[Any], Dict]): """ Registers custom serialization logic for a given custom data type. Calling this function is rarely needed. The library already handles all custom data types by serializing all their properties. Custom serializers allow you to exclude a subset of an object properties during serialization. :param datattype: type to be serialized :param serializer: function that converts any object of the given type to a dictionary. """ self._type_handler.add_serializer(datatype, serializer)
(self, datatype: Type, serializer: Callable[[Any], Dict])
729,803
touca._client
assume
Logs a given value as an assertion for the declared test case and associates it with the specified key. :param key: name to be associated with the logged test result :param value: value to be logged as a test result
def casemethod(func): """ """ import inspect from functools import wraps func.__doc__ = inspect.getdoc(getattr(Case, func.__name__)) @wraps(func) def wrapper(self, *args, **kwargs): element = self._active_testcase_name() if not element: return testcase = self._cases.get(element) method = getattr(testcase, func.__name__) retval = func(self, *args, **kwargs) if not retval: method(*args, **kwargs) else: method(args[0], retval, **kwargs) return wrapper
(self, key: str, value: Any)
729,804
touca._client
check
Captures the value of a given variable as a data point for the declared test case and associates it with the specified key. :param key: name to be associated with the captured data point :param value: value to be captured as a test result :param rule: comparison rule for this test result
def casemethod(func): """ """ import inspect from functools import wraps func.__doc__ = inspect.getdoc(getattr(Case, func.__name__)) @wraps(func) def wrapper(self, *args, **kwargs): element = self._active_testcase_name() if not element: return testcase = self._cases.get(element) method = getattr(testcase, func.__name__) retval = func(self, *args, **kwargs) if not retval: method(*args, **kwargs) else: method(args[0], retval, **kwargs) return wrapper
(self, key: str, value: Any, *, rule: Optional[touca._rules.ComparisonRule] = None)
729,805
touca._client
check_file
Captures an external file as a data point for the declared test case and associates it with the specified key. :param key: name to be associated with captured file :param path: path to the external file to be captured
def casemethod(func): """ """ import inspect from functools import wraps func.__doc__ = inspect.getdoc(getattr(Case, func.__name__)) @wraps(func) def wrapper(self, *args, **kwargs): element = self._active_testcase_name() if not element: return testcase = self._cases.get(element) method = getattr(testcase, func.__name__) retval = func(self, *args, **kwargs) if not retval: method(*args, **kwargs) else: method(args[0], retval, **kwargs) return wrapper
(self, key: str, file)
729,806
touca._client
configuration_error
Provides the most recent error, if any, that is encountered during client configuration. :return: short description of the most recent configuration error :rtype: str
def configuration_error(self) -> str: """ Provides the most recent error, if any, that is encountered during client configuration. :return: short description of the most recent configuration error :rtype: str """ return self._configuration_error
(self) -> str
729,807
touca._client
configure
Configures the Touca client. Must be called before declaring test cases and adding results to the client. Should be regarded as a potentially expensive operation. Should be called only from your test environment. :py:meth:`~configure` takes a variety of configuration parameters documented below. All of these parameters are optional. Calling this function without any parameters is possible: the client can capture behavior and performance data and store them on a local filesystem but it will not be able to post them to the Touca server. In most cases, You will need to pass API Key and API URL during the configuration. The code below shows the common pattern in which API URL is given in long format (it includes the team slug and the suite slug) and API Key as well as the version of the code under test are specified as environment variables ``TOUCA_API_KEY`` and ``TOUCA_TEST_VERSION``, respectively:: touca.configure(api_url='https://api.touca.io/@/acme/students') As long as the API Key and API URL to the Touca server are known to the client, it attempts to authenticate with the Touca Server. You can explicitly disable this communication in rare cases by setting configuration option ``offline`` to ``False``. You can call :py:meth:`~configure` any number of times. The client preserves the configuration parameters specified in previous calls to this function. :type api_key: str, optional :param api_key: (optional) API Key issued by the Touca server that identifies who is submitting the data. Since the value should be treated as a secret, we recommend that you pass it as an environment variable ``TOUCA_API_KEY`` instead. :type api_url: str, optional :param api_url: (optional) URL to the Touca server API. Can be provided either in long format like ``https://api.touca.io/@/myteam/mysuite/version`` or in short format like ``https://api.touca.io``. If the team, suite, or version are specified, you do not need to specify them separately. :type team: str, optional :param team: (optional) slug of your team on the Touca server. :type suite: str, optional :param suite: slug of the suite on the Touca server that corresponds to your workflow under test. :type version: str, optional :param version: version of your workflow under test. :type offline: bool, optional :param offline: determines whether client should connect with the Touca server during the configuration. Defaults to ``False`` when ``api_url`` or ``api_key`` are provided. :type concurrency: bool, optional :param concurrency: determines whether the scope of test case declaration is bound to the thread performing the declaration, or covers all other threads. Defaults to ``True``. If set to ``True``, when a thread calls :py:meth:`~declare_testcase`, all other threads also have their most recent test case changed to the newly declared test case and any subsequent call to data capturing functions such as :py:meth:`~check` will affect the newly declared test case.
def configure(self, **kwargs) -> bool: """ Configures the Touca client. Must be called before declaring test cases and adding results to the client. Should be regarded as a potentially expensive operation. Should be called only from your test environment. :py:meth:`~configure` takes a variety of configuration parameters documented below. All of these parameters are optional. Calling this function without any parameters is possible: the client can capture behavior and performance data and store them on a local filesystem but it will not be able to post them to the Touca server. In most cases, You will need to pass API Key and API URL during the configuration. The code below shows the common pattern in which API URL is given in long format (it includes the team slug and the suite slug) and API Key as well as the version of the code under test are specified as environment variables ``TOUCA_API_KEY`` and ``TOUCA_TEST_VERSION``, respectively:: touca.configure(api_url='https://api.touca.io/@/acme/students') As long as the API Key and API URL to the Touca server are known to the client, it attempts to authenticate with the Touca Server. You can explicitly disable this communication in rare cases by setting configuration option ``offline`` to ``False``. You can call :py:meth:`~configure` any number of times. The client preserves the configuration parameters specified in previous calls to this function. :type api_key: str, optional :param api_key: (optional) API Key issued by the Touca server that identifies who is submitting the data. Since the value should be treated as a secret, we recommend that you pass it as an environment variable ``TOUCA_API_KEY`` instead. :type api_url: str, optional :param api_url: (optional) URL to the Touca server API. Can be provided either in long format like ``https://api.touca.io/@/myteam/mysuite/version`` or in short format like ``https://api.touca.io``. If the team, suite, or version are specified, you do not need to specify them separately. :type team: str, optional :param team: (optional) slug of your team on the Touca server. :type suite: str, optional :param suite: slug of the suite on the Touca server that corresponds to your workflow under test. :type version: str, optional :param version: version of your workflow under test. :type offline: bool, optional :param offline: determines whether client should connect with the Touca server during the configuration. Defaults to ``False`` when ``api_url`` or ``api_key`` are provided. :type concurrency: bool, optional :param concurrency: determines whether the scope of test case declaration is bound to the thread performing the declaration, or covers all other threads. Defaults to ``True``. If set to ``True``, when a thread calls :py:meth:`~declare_testcase`, all other threads also have their most recent test case changed to the newly declared test case and any subsequent call to data capturing functions such as :py:meth:`~check` will affect the newly declared test case. """ from touca._options import assign_options, update_core_options self._configuration_error = "" try: assign_options(self._options, kwargs) self._configured = update_core_options(self._options, self._transport) except RuntimeError as err: self._configuration_error = str(err) return False return True
(self, **kwargs) -> bool
729,808
touca._client
declare_testcase
Declares name of the test case to which all subsequent results will be submitted until a new test case is declared. If configuration parameter ``concurrency`` is set to ``"enabled"``, when a thread calls `declare_testcase` all other threads also have their most recent testcase changed to the newly declared one. Otherwise, each thread will submit to its own testcase. :param name: name of the testcase to be declared
def declare_testcase(self, name: str): """ Declares name of the test case to which all subsequent results will be submitted until a new test case is declared. If configuration parameter ``concurrency`` is set to ``"enabled"``, when a thread calls `declare_testcase` all other threads also have their most recent testcase changed to the newly declared one. Otherwise, each thread will submit to its own testcase. :param name: name of the testcase to be declared """ if not self._configured: return if name not in self._cases: self._cases[name] = Case( team=self._options.get("team"), suite=self._options.get("suite"), version=self._options.get("version"), name=name, ) self._threads_case = name self._threads_cases[get_ident()] = name return self._cases.get(name)
(self, name: str)
729,809
touca._client
forget_testcase
Removes all logged information associated with a given test case. This information is removed from memory, such that switching back to an already-declared or already-submitted test case would behave similar to when that test case was first declared. This information is removed, for all threads, regardless of the configuration option ``concurrency``. Information already submitted to the server will not be removed from the server. This operation is useful in long-running regression test frameworks, after submission of test case to the server, if memory consumed by the client library is a concern or if there is a risk that a future test case with a similar name may be executed. :param name: name of the testcase to be removed from memory :raises ToucaError: when called with the name of a test case that was never declared
def forget_testcase(self, name: str): """ Removes all logged information associated with a given test case. This information is removed from memory, such that switching back to an already-declared or already-submitted test case would behave similar to when that test case was first declared. This information is removed, for all threads, regardless of the configuration option ``concurrency``. Information already submitted to the server will not be removed from the server. This operation is useful in long-running regression test frameworks, after submission of test case to the server, if memory consumed by the client library is a concern or if there is a risk that a future test case with a similar name may be executed. :param name: name of the testcase to be removed from memory :raises ToucaError: when called with the name of a test case that was never declared """ if not self._configured: return if name not in self._cases: raise ToucaError("capture_forget", name) del self._cases[name]
(self, name: str)
729,810
touca._client
is_configured
Checks if previous call(s) to :py:meth:`~configure` have set the right combination of configuration parameters to enable the client to perform expected tasks. We recommend that you perform this check after client configuration and before calling other functions of the library:: if not touca.is_configured(): print(touca.configuration_error()) sys.exit(1) At a minimum, the client is considered configured if it can capture test results and store them locally on the filesystem. A single call to :py:meth:`~configure` without any configuration parameters can help us get to this state. However, if a subsequent call to :py:meth:`~configure` sets the parameter ``api_url`` in short form without specifying parameters such as ``team``, ``suite`` and ``version``, the client configuration is incomplete: We infer that the user intends to submit results but the provided configuration parameters are not sufficient to perform this operation. :return: ``True`` if the client is properly configured :rtype: bool :see also: :py:meth:`~configure`
def is_configured(self) -> bool: """ Checks if previous call(s) to :py:meth:`~configure` have set the right combination of configuration parameters to enable the client to perform expected tasks. We recommend that you perform this check after client configuration and before calling other functions of the library:: if not touca.is_configured(): print(touca.configuration_error()) sys.exit(1) At a minimum, the client is considered configured if it can capture test results and store them locally on the filesystem. A single call to :py:meth:`~configure` without any configuration parameters can help us get to this state. However, if a subsequent call to :py:meth:`~configure` sets the parameter ``api_url`` in short form without specifying parameters such as ``team``, ``suite`` and ``version``, the client configuration is incomplete: We infer that the user intends to submit results but the provided configuration parameters are not sufficient to perform this operation. :return: ``True`` if the client is properly configured :rtype: bool :see also: :py:meth:`~configure` """ return self._configured
(self) -> bool
729,811
touca._client
post
Submits all test results recorded so far to Touca server. It is possible to call :py:meth:`~post` multiple times during runtime of the regression test tool. Test cases already submitted to the server whose test results have not changed, will not be resubmitted. It is also possible to add test results to a testcase after it is submitted to the server. Any subsequent call to :py:meth:`~post` will resubmit the modified test case. :raises ToucaError: when called on the client that is not configured to communicate with the Touca server.
def post(self, *, submit_async=False): """ Submits all test results recorded so far to Touca server. It is possible to call :py:meth:`~post` multiple times during runtime of the regression test tool. Test cases already submitted to the server whose test results have not changed, will not be resubmitted. It is also possible to add test results to a testcase after it is submitted to the server. Any subsequent call to :py:meth:`~post` will resubmit the modified test case. :raises ToucaError: when called on the client that is not configured to communicate with the Touca server. """ if not self._configured or self._options.get("offline"): raise ToucaError("capture_not_configured") content = serialize_messages( [item.serialize() for item in self._cases.values()] ) headers = {"X-Touca-Submission-Mode": "async" if submit_async else "sync"} result = self._post("/client/submit", content, headers) slugs = "/".join(self._options.get(x) for x in ["team", "suite", "version"]) for case in self._cases.values(): testcase_name = case._metadata().get("testcase") for key, value in case._results.items(): if isinstance(value.val, BlobType): self._post( f"/client/submit/artifact/{slugs}/{testcase_name}/{key}", value.val._value.binary(), ) return parse_comparison_result(result) if result else "sent"
(self, *, submit_async=False)
729,812
touca._client
save_binary
Stores test results and performance benchmarks in binary format in a file of specified path. Touca binary files can be submitted at a later time to the Touca server. We do not recommend as a general practice for regression test tools to locally store their test results. This feature may be helpful for special cases such as when regression test tools have to be run in environments that have no access to the Touca server (e.g. running with no network access). :param path: path to file in which test results and performance benchmarks should be stored :param cases: names of test cases whose results should be stored. If a set is not specified or is set as empty, all test cases will be stored in the specified file.
def save_binary(self, path: str, cases: list): """ Stores test results and performance benchmarks in binary format in a file of specified path. Touca binary files can be submitted at a later time to the Touca server. We do not recommend as a general practice for regression test tools to locally store their test results. This feature may be helpful for special cases such as when regression test tools have to be run in environments that have no access to the Touca server (e.g. running with no network access). :param path: path to file in which test results and performance benchmarks should be stored :param cases: names of test cases whose results should be stored. If a set is not specified or is set as empty, all test cases will be stored in the specified file. """ items = self._prepare_save(path, cases) content = serialize_messages([item.serialize() for item in items]) with open(path, mode="wb") as file: file.write(content)
(self, path: str, cases: list)
729,813
touca._client
save_json
Stores test results and performance benchmarks in JSON format in a file of specified path. This feature may be helpful during development of regression tests tools for quick inspection of the test results and performance metrics being captured. :param path: path to file in which test results and performance benchmarks should be stored :param cases: names of test cases whose results should be stored. If a set is not specified or is set as empty, all test cases will be stored in the specified file.
def save_json(self, path: str, cases: list): """ Stores test results and performance benchmarks in JSON format in a file of specified path. This feature may be helpful during development of regression tests tools for quick inspection of the test results and performance metrics being captured. :param path: path to file in which test results and performance benchmarks should be stored :param cases: names of test cases whose results should be stored. If a set is not specified or is set as empty, all test cases will be stored in the specified file. """ from json import dumps items = self._prepare_save(path, cases) content = dumps([testcase.json() for testcase in items]) with open(path, mode="wt") as file: file.write(content)
(self, path: str, cases: list)
729,814
touca._client
seal
Notifies the Touca server that all test cases were executed for this version and no further test result is expected to be submitted. Expected to be called by the test tool once all test cases are executed and all test results are posted. Sealing the version is optional. The Touca server automatically performs this operation once a certain amount of time has passed since the last test case was submitted. This duration is configurable from the "Settings" tab in "Suite" Page. :raises ToucaError: when called on the client that is not configured to communicate with the Touca server.
def seal(self): """ Notifies the Touca server that all test cases were executed for this version and no further test result is expected to be submitted. Expected to be called by the test tool once all test cases are executed and all test results are posted. Sealing the version is optional. The Touca server automatically performs this operation once a certain amount of time has passed since the last test case was submitted. This duration is configurable from the "Settings" tab in "Suite" Page. :raises ToucaError: when called on the client that is not configured to communicate with the Touca server. """ if not self._configured or self._options.get("offline"): raise ToucaError("capture_not_configured") slugs = "/".join(self._options.get(x) for x in ["team", "suite", "version"]) response = self._transport.request(method="POST", path=f"/batch/{slugs}/seal") if response.status == 403: raise ToucaError("auth_invalid_key") if response.status != 204: raise ToucaError("transport_seal")
(self)
729,815
touca._client
start_timer
Starts timing an event with the specified name. Measurement of the event is only complete when function :py:meth:`~stop_timer` is later called for the specified name. :param key: name to be associated with the performance metric
def casemethod(func): """ """ import inspect from functools import wraps func.__doc__ = inspect.getdoc(getattr(Case, func.__name__)) @wraps(func) def wrapper(self, *args, **kwargs): element = self._active_testcase_name() if not element: return testcase = self._cases.get(element) method = getattr(testcase, func.__name__) retval = func(self, *args, **kwargs) if not retval: method(*args, **kwargs) else: method(args[0], retval, **kwargs) return wrapper
(self, key: str)
729,816
touca._client
stop_timer
Stops timing an event with the specified name. Expects function :py:meth:`~start_timer` to have been called previously with the specified name. :param key: name to be associated with the performance metric
def casemethod(func): """ """ import inspect from functools import wraps func.__doc__ = inspect.getdoc(getattr(Case, func.__name__)) @wraps(func) def wrapper(self, *args, **kwargs): element = self._active_testcase_name() if not element: return testcase = self._cases.get(element) method = getattr(testcase, func.__name__) retval = func(self, *args, **kwargs) if not retval: method(*args, **kwargs) else: method(args[0], retval, **kwargs) return wrapper
(self, key: str)
729,817
touca._rules
ComparisonRule
null
class ComparisonRule(ABC): @abstractmethod def json(self): pass @abstractmethod def serialize(self, builder: Builder): pass
()
729,818
touca._rules
json
null
@abstractmethod def json(self): pass
(self)
729,819
touca._rules
serialize
null
@abstractmethod def serialize(self, builder: Builder): pass
(self, builder: flatbuffers.builder.Builder)
729,820
touca._runner
Workflow
null
class Workflow: def __init__(self, func): from functools import update_wrapper update_wrapper(self, func) _workflows.append({"callback": func, "suite": func.__name__})
(func)
729,821
touca._runner
__init__
null
def __init__(self, func): from functools import update_wrapper update_wrapper(self, func) _workflows.append({"callback": func, "suite": func.__name__})
(self, func)
729,831
touca
add_array_element
Adds a given value to a list of results for the declared test case which is associated with the specified key. Could be considered as a helper utility function. This method is particularly helpful to log a list of items as they are found: .. code-block:: python for number in numbers: if is_prime(number): touca.add_array_element("prime numbers", number) touca.add_hit_count("number of primes") This pattern can be considered as a syntactic sugar for the following alternative: .. code-block:: python primes = [] for number in numbers: if is_prime(number): primes.append(number) if primes: touca.check("prime numbers", primes) touca.check("number of primes", len(primes)) The items added to the list are not required to be of the same type. The following code is acceptable: .. code-block:: python touca.check("prime numbers", 42) touca.check("prime numbers", "forty three") :raises RuntimeError: if specified key is already associated with a test result which was not iterable :param key: name to be associated with the logged test result :param value: element to be appended to the array :see also: :py:meth:`~check`
@clientmethod def add_array_element(key: str, value: Any): Client.instance().add_array_element(key, value)
(key: str, value: Any)
729,832
touca
add_hit_count
Increments value of key every time it is executed. creates the key with initial value of one if it does not exist. Could be considered as a helper utility function. This method is particularly helpful to track variables whose values are determined in loops with indeterminate execution cycles: .. code-block:: python for number in numbers: if is_prime(number): touca.add_array_element("prime numbers", number) touca.add_hit_count("number of primes") This pattern can be considered as a syntactic sugar for the following alternative: .. code-block:: python primes = [] for number in numbers: if is_prime(number): primes.append(number) if primes: touca.check("prime numbers", primes) touca.check("number of primes", len(primes)) :raises RuntimeError: if specified key is already associated with a test result which was not an integer :param key: name to be associated with the logged test result :see also: :py:meth:`~check`
@clientmethod def add_hit_count(key: str): Client.instance().add_hit_count(key)
(key: str)
729,833
touca
add_metric
Adds an already obtained measurements to the list of captured performance benchmarks. Useful for logging a metric that is measured without using this SDK. :param key: name to be associated with this performance benchmark :param milliseconds: duration of this measurement in milliseconds
@clientmethod def add_metric(key: str, milliseconds: int): Client.instance().add_metric(key, milliseconds)
(key: str, milliseconds: int)
729,834
touca
add_serializer
Registers custom serialization logic for a given custom data type. Calling this function is rarely needed. The library already handles all custom data types by serializing all their properties. Custom serializers allow you to exclude a subset of an object properties during serialization. :param datattype: type to be serialized :param serializer: function that converts any object of the given type to a dictionary.
@clientmethod def add_serializer(datatype: Type, serializer: Callable[[Any], Dict]): Client.instance().add_serializer(datatype, serializer)
(datatype: Type, serializer: Callable[[Any], Dict])
729,835
touca
assume
Logs a given value as an assertion for the declared test case and associates it with the specified key. :param key: name to be associated with the logged test result :param value: value to be logged as a test result
@clientmethod def assume(key: str, value: Any): Client.instance().assume(key, value)
(key: str, value: Any)
729,836
touca
check
Captures the value of a given variable as a data point for the declared test case and associates it with the specified key. :param key: name to be associated with the captured data point :param value: value to be captured as a test result :param rule: comparison rule for this test result
@clientmethod def check(key: str, value: Any, *, rule: Optional[ComparisonRule] = None): Client.instance().check(key, value, rule=rule)
(key: str, value: Any, *, rule: Optional[touca._rules.ComparisonRule] = None)
729,837
touca
check_file
Captures an external file as a data point for the declared test case and associates it with the specified key. :param key: name to be associated with captured file :param path: path to the external file to be captured
@clientmethod def check_file(key: str, value: Any): Client.instance().check_file(key, value)
(key: str, value: Any)
729,838
touca
clientmethod
null
def clientmethod(f): import inspect f.__doc__ = inspect.getdoc(getattr(Client, f.__name__)) return f
(f)
729,839
touca
configuration_error
Provides the most recent error, if any, that is encountered during client configuration. :return: short description of the most recent configuration error :rtype: str
@clientmethod def configuration_error() -> str: return Client.instance().configuration_error()
() -> str
729,840
touca
configure
Configures the Touca client. Must be called before declaring test cases and adding results to the client. Should be regarded as a potentially expensive operation. Should be called only from your test environment. :py:meth:`~configure` takes a variety of configuration parameters documented below. All of these parameters are optional. Calling this function without any parameters is possible: the client can capture behavior and performance data and store them on a local filesystem but it will not be able to post them to the Touca server. In most cases, You will need to pass API Key and API URL during the configuration. The code below shows the common pattern in which API URL is given in long format (it includes the team slug and the suite slug) and API Key as well as the version of the code under test are specified as environment variables ``TOUCA_API_KEY`` and ``TOUCA_TEST_VERSION``, respectively:: touca.configure(api_url='https://api.touca.io/@/acme/students') As long as the API Key and API URL to the Touca server are known to the client, it attempts to authenticate with the Touca Server. You can explicitly disable this communication in rare cases by setting configuration option ``offline`` to ``False``. You can call :py:meth:`~configure` any number of times. The client preserves the configuration parameters specified in previous calls to this function. :type api_key: str, optional :param api_key: (optional) API Key issued by the Touca server that identifies who is submitting the data. Since the value should be treated as a secret, we recommend that you pass it as an environment variable ``TOUCA_API_KEY`` instead. :type api_url: str, optional :param api_url: (optional) URL to the Touca server API. Can be provided either in long format like ``https://api.touca.io/@/myteam/mysuite/version`` or in short format like ``https://api.touca.io``. If the team, suite, or version are specified, you do not need to specify them separately. :type team: str, optional :param team: (optional) slug of your team on the Touca server. :type suite: str, optional :param suite: slug of the suite on the Touca server that corresponds to your workflow under test. :type version: str, optional :param version: version of your workflow under test. :type offline: bool, optional :param offline: determines whether client should connect with the Touca server during the configuration. Defaults to ``False`` when ``api_url`` or ``api_key`` are provided. :type concurrency: bool, optional :param concurrency: determines whether the scope of test case declaration is bound to the thread performing the declaration, or covers all other threads. Defaults to ``True``. If set to ``True``, when a thread calls :py:meth:`~declare_testcase`, all other threads also have their most recent test case changed to the newly declared test case and any subsequent call to data capturing functions such as :py:meth:`~check` will affect the newly declared test case.
@clientmethod def configure(**kwargs) -> bool: return Client.instance().configure(**kwargs)
(**kwargs) -> bool
729,841
touca._rules
decimal_rule
null
class decimal_rule(ComparisonRule): @classmethod def absolute(cls, *, min=None, max=None): return cls( mode=schema.ComparisonRuleMode.Absolute, min=min, max=max, ) @classmethod def relative(cls, *, max=None, percent=False): return cls( mode=schema.ComparisonRuleMode.Relative, max=max, percent=percent, ) def __init__( self, *, mode: Optional[schema.ComparisonRuleMode] = None, min=None, max=None, percent=None ): self._mode = mode self._min = min self._max = max self._percent = percent def json(self): mode = ( "absolute" if self._mode == schema.ComparisonRuleMode.Absolute else "relative" ) out = { "type": "number", "mode": mode, "min": self._min, "max": self._max, "percent": self._percent, } return {k: v for k, v in out.items() if v is not None} def serialize(self, builder: Builder): schema.ComparisonRuleDoubleStart(builder) schema.ComparisonRuleDoubleAddMode(builder, self._mode) if self._min is not None: schema.ComparisonRuleDoubleAddMin(builder, self._min) if self._max is not None: schema.ComparisonRuleDoubleAddMax(builder, self._max) if self._percent is not None: schema.ComparisonRuleDoubleAddPercent(builder, self._percent) return schema.ComparisonRuleDoubleEnd(builder)
(*, mode: Optional[touca_fbs.ComparisonRuleMode] = None, min=None, max=None, percent=None)
729,842
touca._rules
__init__
null
def __init__( self, *, mode: Optional[schema.ComparisonRuleMode] = None, min=None, max=None, percent=None ): self._mode = mode self._min = min self._max = max self._percent = percent
(self, *, mode: Optional[touca_fbs.ComparisonRuleMode] = None, min=None, max=None, percent=None)
729,843
touca._rules
json
null
def json(self): mode = ( "absolute" if self._mode == schema.ComparisonRuleMode.Absolute else "relative" ) out = { "type": "number", "mode": mode, "min": self._min, "max": self._max, "percent": self._percent, } return {k: v for k, v in out.items() if v is not None}
(self)
729,844
touca._rules
serialize
null
def serialize(self, builder: Builder): schema.ComparisonRuleDoubleStart(builder) schema.ComparisonRuleDoubleAddMode(builder, self._mode) if self._min is not None: schema.ComparisonRuleDoubleAddMin(builder, self._min) if self._max is not None: schema.ComparisonRuleDoubleAddMax(builder, self._max) if self._percent is not None: schema.ComparisonRuleDoubleAddPercent(builder, self._percent) return schema.ComparisonRuleDoubleEnd(builder)
(self, builder: flatbuffers.builder.Builder)
729,845
touca
declare_testcase
Declares name of the test case to which all subsequent results will be submitted until a new test case is declared. If configuration parameter ``concurrency`` is set to ``"enabled"``, when a thread calls `declare_testcase` all other threads also have their most recent testcase changed to the newly declared one. Otherwise, each thread will submit to its own testcase. :param name: name of the testcase to be declared
@clientmethod def declare_testcase(name: str): Client.instance().declare_testcase(name)
(name: str)
729,846
touca
forget_testcase
Removes all logged information associated with a given test case. This information is removed from memory, such that switching back to an already-declared or already-submitted test case would behave similar to when that test case was first declared. This information is removed, for all threads, regardless of the configuration option ``concurrency``. Information already submitted to the server will not be removed from the server. This operation is useful in long-running regression test frameworks, after submission of test case to the server, if memory consumed by the client library is a concern or if there is a risk that a future test case with a similar name may be executed. :param name: name of the testcase to be removed from memory :raises ToucaError: when called with the name of a test case that was never declared
@clientmethod def forget_testcase(name: str): Client.instance().forget_testcase(name)
(name: str)
729,847
touca
is_configured
Checks if previous call(s) to :py:meth:`~configure` have set the right combination of configuration parameters to enable the client to perform expected tasks. We recommend that you perform this check after client configuration and before calling other functions of the library:: if not touca.is_configured(): print(touca.configuration_error()) sys.exit(1) At a minimum, the client is considered configured if it can capture test results and store them locally on the filesystem. A single call to :py:meth:`~configure` without any configuration parameters can help us get to this state. However, if a subsequent call to :py:meth:`~configure` sets the parameter ``api_url`` in short form without specifying parameters such as ``team``, ``suite`` and ``version``, the client configuration is incomplete: We infer that the user intends to submit results but the provided configuration parameters are not sufficient to perform this operation. :return: ``True`` if the client is properly configured :rtype: bool :see also: :py:meth:`~configure`
@clientmethod def is_configured() -> bool: return Client.instance().is_configured()
() -> bool
729,848
touca
post
Submits all test results recorded so far to Touca server. It is possible to call :py:meth:`~post` multiple times during runtime of the regression test tool. Test cases already submitted to the server whose test results have not changed, will not be resubmitted. It is also possible to add test results to a testcase after it is submitted to the server. Any subsequent call to :py:meth:`~post` will resubmit the modified test case. :raises ToucaError: when called on the client that is not configured to communicate with the Touca server.
@clientmethod def post(): Client.instance().post()
()
729,849
touca._runner
run
Runs registered workflows, one by one, for available test cases. This function is intended to be called once from the main module as shown in the example below:: if __name__ == "__main__": touca.run() :raises SystemExit: When configuration options specified as command line arguments, environment variables, or in a configuration file, have unexpected values or are in conflict with each other. Capturing this exception is not required.
def run(**options): """ Runs registered workflows, one by one, for available test cases. This function is intended to be called once from the main module as shown in the example below:: if __name__ == "__main__": touca.run() :raises SystemExit: When configuration options specified as command line arguments, environment variables, or in a configuration file, have unexpected values or are in conflict with each other. Capturing this exception is not required. """ from sys import exit options.setdefault("workflows", []) options["workflows"].extend(_workflows) try: if not run_workflows(options): exit(1) except Exception as err: exit(f"\nTest failed:\n{err}\n")
(**options)
729,850
touca
save_binary
Stores test results and performance benchmarks in binary format in a file of specified path. Touca binary files can be submitted at a later time to the Touca server. We do not recommend as a general practice for regression test tools to locally store their test results. This feature may be helpful for special cases such as when regression test tools have to be run in environments that have no access to the Touca server (e.g. running with no network access). :param path: path to file in which test results and performance benchmarks should be stored :param cases: names of test cases whose results should be stored. If a set is not specified or is set as empty, all test cases will be stored in the specified file.
@clientmethod def save_binary(key: str, cases: List[str] = []): Client.instance().save_binary(key, cases)
(key: str, cases: List[str] = [])
729,851
touca
save_json
Stores test results and performance benchmarks in JSON format in a file of specified path. This feature may be helpful during development of regression tests tools for quick inspection of the test results and performance metrics being captured. :param path: path to file in which test results and performance benchmarks should be stored :param cases: names of test cases whose results should be stored. If a set is not specified or is set as empty, all test cases will be stored in the specified file.
@clientmethod def save_json(key: str, cases: List[str] = []): Client.instance().save_json(key, cases)
(key: str, cases: List[str] = [])
729,852
touca._utils
scoped_timer
null
class scoped_timer: def __init__(self, name): """ Creates a timer object that captures its own lifetime and associates it with a given name. :param name: name to be associated with the captured runtime """ self._name = name def __enter__(self): Client.instance().start_timer(self._name) def __exit__(self, exc_type, exc_value, traceback): Client.instance().stop_timer(self._name)
(name)
729,853
touca._utils
__enter__
null
def __enter__(self): Client.instance().start_timer(self._name)
(self)
729,854
touca._utils
__exit__
null
def __exit__(self, exc_type, exc_value, traceback): Client.instance().stop_timer(self._name)
(self, exc_type, exc_value, traceback)
729,855
touca._utils
__init__
Creates a timer object that captures its own lifetime and associates it with a given name. :param name: name to be associated with the captured runtime
def __init__(self, name): """ Creates a timer object that captures its own lifetime and associates it with a given name. :param name: name to be associated with the captured runtime """ self._name = name
(self, name)
729,856
touca
seal
Notifies the Touca server that all test cases were executed for this version and no further test result is expected to be submitted. Expected to be called by the test tool once all test cases are executed and all test results are posted. Sealing the version is optional. The Touca server automatically performs this operation once a certain amount of time has passed since the last test case was submitted. This duration is configurable from the "Settings" tab in "Suite" Page. :raises ToucaError: when called on the client that is not configured to communicate with the Touca server.
@clientmethod def seal(): Client.instance().seal()
()
729,857
touca
start_timer
Starts timing an event with the specified name. Measurement of the event is only complete when function :py:meth:`~stop_timer` is later called for the specified name. :param key: name to be associated with the performance metric
@clientmethod def start_timer(key: str): Client.instance().start_timer(key)
(key: str)
729,858
touca
stop_timer
Stops timing an event with the specified name. Expects function :py:meth:`~start_timer` to have been called previously with the specified name. :param key: name to be associated with the performance metric
@clientmethod def stop_timer(key: str): Client.instance().stop_timer(key)
(key: str)