Common utilities

This module gives common utilities.

No external import of other code_aster packages.

base_utils — General purpose utilities

This modules gives some basic utilities.

code_aster.Utilities.base_utils.no_new_attributes(wrapped_setattr)[source]

Raise an error on attempts to add a new attribute, while allowing existing attributes to be set to new values.

Taken from ? ‘Python Cookbook’ by Alex Martelli, Anna Ravenscroft, David Ascher, ?6.3. ‘Restricting Attribute Setting’

code_aster.Utilities.base_utils.import_object(uri)[source]

Load and return a python object (class, function…). Its uri looks like “mainpkg.subpkg.module.object”, this means that “mainpkg.subpkg.module” is imported and “object” is the object to return.

Parameters:

uri (str) – Path to the object to import.

Returns:

Imported object.

Return type:

object

code_aster.Utilities.base_utils.get_caller_context(level)[source]

Return the context some levels upper.

Parameters:

level (int) – Number of parents in the calling stack. 0 means where get_caller_context is called.

Returns:

‘globals’ context at this level.

Return type:

dict

code_aster.Utilities.base_utils.force_list(values)[source]

Ensure values is iterable (list, tuple, array…) and return it as a list.

code_aster.Utilities.base_utils.force_tuple(values)[source]

Ensure values is iterable (list, tuple, array…) and return it as a tuple.

code_aster.Utilities.base_utils.cmp(a, b, rel_tol=None, abs_tol=None)[source]

Compare two values using relative or absolute tolerance (similar to math.isclose()).

Parameters:
  • a (float) – first argument.

  • b (float) – second argument.

  • rel_tol (float, optional) – relative tolerancev, None if not used.

  • abs_tol (float, optional) – minimum absolute tolerance, None if not used.

Returns:

-1 if a < b, 0 if a == b, +1 if a > b using tolerances.

Return type:

int

code_aster.Utilities.base_utils.is_int(obj, onvalue=False)[source]

Tell if an object is an integer.

Parameters:
  • obj (misc) – Object to be tested.

  • onvalue (bool, optional) – If onvalue is True, accept a float number that is equal to its integer part. If False, acceptance is only based on the object type.

code_aster.Utilities.base_utils.is_float(obj)[source]

Tell if an object is a float number.

code_aster.Utilities.base_utils.is_float_or_int(obj)[source]

Tell if an object is a float or an integer.

code_aster.Utilities.base_utils.is_complex(obj)[source]

Tell if an object is a complex number.

code_aster.Utilities.base_utils.is_number(obj)[source]

Tell if an object is a number.

code_aster.Utilities.base_utils.is_str(obj)[source]

Tell if an object is a string.

code_aster.Utilities.base_utils.is_sequence(obj)[source]

Is a sequence (allow iteration, not a string)?

code_aster.Utilities.base_utils.value_is_sequence(obj)

Is a sequence (allow iteration, not a string)?

code_aster.Utilities.base_utils.array_to_list(obj)[source]

Convert an object to a list if possible (using tolist()) or keep it unchanged otherwise.

Parameters:

obj (misc) – Object to convert.

Returns:

Object unchanged or a list.

Return type:

misc

code_aster.Utilities.base_utils.accept_array(func)[source]

Decorator that automatically converts numpy arrays to lists.

Needed to pass an array as argument to a Python/C++ method.

class code_aster.Utilities.base_utils.Singleton[source]

Bases: type

Singleton implementation in python (Metaclass).

class code_aster.Utilities.base_utils.ReadOnlyDict(dict=None, /, **kwargs)[source]

Bases: UserDict

Read-only dict object with default value to None.

Items can be added but their values can not be changed later.

__getitem__(key)[source]

Disable setitem

__setitem__(key, value)[source]

Disable __setitem__

compatibility — Manage compatibility with legacy version

This modules will help for transitional features. It defines decorators or conversion functions for step by step migration from legacy code_aster source code and C++ code_aster code.

code_aster.Utilities.compatibility.warn_to_stdout(message, category, filename, lineno, file=None, line=None)[source]

Same as showwarning but on stdout

code_aster.Utilities.compatibility.deprecate(feature, case=1, help=None, level=4)[source]

Deprecate a feature, emit a deprecation warning depending on the case.

Parameters:
  • feature (str) – Deprecated feature.

  • case (int) – Case 1: the feature still works but it will be removed. Case 2: the feature does nothing, it has been removed. Case 3: the feature still works but has a new implementation. Case 4: the feature does nothing but has a new implementation.

  • help (str) – Additional help message, should be present for case 3.

  • level (int) – Level of the caller in the stack.

code_aster.Utilities.compatibility.deprecated(case=1, help=None)[source]

Decorator to mark a function as deprecated.

It will do nothing at the beginning of the transitional phase. Then, it will warn about deprecated functions. And finally, it will raise an error to remove all of them.

Parameters:
  • case (int) – Case 1: the feature still works but it will be removed. Case 2: the feature does nothing, it has been removed. Case 3: the feature still works but has a new implementation. Case 4: the feature does nothing but has a new implementation.

  • help (str) – Additional help message.

code_aster.Utilities.compatibility.compat_listr8(keywords, factor_keyword, list_keyword, float_keyword)[source]

Pass values given to a keyword that expects a listr8 to the similar keyword that takes a list of floats, eventually under a factor keyword.

Parameters:
  • keywords (dict) – Dict of keywords passed to a command, changed in place.

  • factor_keyword (str) – Name of the factor keyword or an empty string if the keywords are at the top level.

  • list_keyword (str) – Name of the keyword that needs a listr8.

  • float_keyword (str) – Name of the keyword that takes a list of floats.

code_aster.Utilities.compatibility._if_exists(keywords, factor_keyword, simple_keyword, callback)[source]

Call a callback if the couple (factor_keyword, simple_keyword) is found in the user’s keywords.

Parameters:
  • keywords (dict) – Dict of keywords passed to a command, changed in place.

  • factor_keyword (str) – Name of the factor keyword or an empty string if the keywords are at the top level.

  • simple_keyword (str) – Name of the simple keyword. It it is an empty string the factor keyword is entirely removed.

  • callback (function) – Callback function with signature (container, key) where (container, key) is (keywords, factor_keyword) if factor_keyword is empty or (factor keyword dict, simple_keyword) otherwise.

code_aster.Utilities.compatibility._if_not_exists(keywords, factor_keyword, simple_keyword, callback)[source]

Call a callback if the couple (factor_keyword, simple_keyword) is not found in the user’s keywords.

Parameters:
  • keywords (dict) – Dict of keywords passed to a command, changed in place.

  • factor_keyword (str) – Name of the factor keyword or an empty string if the keywords are at the top level.

  • simple_keyword (str) – Name of the simple keyword. It it is an empty string the factor keyword is entirely removed.

  • callback (function) – Callback function with signature (container, key) where (container, key) is (keywords, factor_keyword) if factor_keyword is empty or (factor keyword dict, simple_keyword) otherwise.

code_aster.Utilities.compatibility.remove_keyword(keywords, factor_keyword, simple_keyword, warning=False)[source]

Remove a couple (factor_keyword, simple_keyword) for the user’s keywords.

Parameters:
  • keywords (dict) – Dict of keywords passed to a command, changed in place.

  • factor_keyword (str) – Name of the factor keyword or an empty string if the keywords are at the top level.

  • simple_keyword (str) – Name of the simple keyword. It it is an empty string the factor keyword is entirely removed.

  • warning (bool) – If True a warning message is emitted.

code_aster.Utilities.compatibility.unsupported(keywords, factor_keyword, simple_keyword, warning=False)[source]

Raises a NotImplementedError exception or a SyntaxWarning if the couple (factor_keyword, simple_keyword) exists in the user’s keywords.

Parameters:
  • keywords (dict) – Dict of keywords passed to a command, changed in place.

  • factor_keyword (str) – Name of the factor keyword or an empty string if the keywords are at the top level.

  • simple_keyword (str) – Name of the simple keyword. It it is an empty string the factor keyword is entirely removed.

  • warning (bool) – If True DeprecationWarning is emitted. Otherwise a NotImplementedError is raised.

code_aster.Utilities.compatibility.required(keywords, factor_keyword, simple_keyword)[source]

Raises a NotImplementedError exception if the couple (factor_keyword, simple_keyword) does not exists in the user’s keywords.

Parameters:
  • keywords (dict) – Dict of keywords passed to a command, changed in place.

  • factor_keyword (str) – Name of the factor keyword or an empty string if the keywords are at the top level.

  • simple_keyword (str) – Name of the simple keyword. It it is an empty string the factor keyword is entirely removed.

ExecutionParameter — Management of the execution parameters

A singleton object ExecutionParameter is created during the initialization. Its main feature is to parse and store the arguments read from the command line or passed to the init() function. It also stores Python objects that have to be available from libaster. They will be available though properties of the ExecutionParameter object.

class code_aster.Utilities.ExecutionParameter.ExecutionParameter(*args, **kws)[source]

Bases: object

This class stores and provides the execution parameters.

The execution parameters are defined by reading the command line or using the method set_option().

_args

Command line arguments and execution parameters.

Type:

dict

_bool

Bitwise combination of boolean parameters.

Type:

int

_catalc

Object that gives access to the catalog of behaviors.

Type:

CataLoiComportement

_unit

Class that manages the logical units.

Type:

LogicalUnitFile

_syntax

Class that passes user keywords up to Fortran operator.

Type:

CommandSyntax

__init__()[source]

Initialization of attributes

_computed()[source]

Fill some “computed” values

set_argv(argv)[source]

Store command line arguments.

Useful for interactive execution with IPython that “executes and exits” to remember the arguments passed to the code_aster script.

Parameters:

argv (list[str]) – Arguments passed to code_aster script.

set_option(option, value)[source]

Set the value of an execution parameter.

Parameters:
  • option (str) – Name of the parameter.

  • value (misc) – Parameter value.

get_option(option)[source]

Return the value of an execution parameter. If the option is unknown, it returns None.

Parameters:

option (str) – Name of the parameter.

Returns:

Parameter value.

Return type:

misc

enable(option)[source]

Enable a boolean option.

Parameters:

option (int) – An ‘Options’ value.

disable(option)[source]

Disable a boolean option.

Parameters:

option (int) – An ‘Options’ value.

property option

Attribute that holds the boolean options.

Returns:

Bitwise combination of boolean execution parameters.

Return type:

int

property timer

Attribute that holds the timer object.

Returns:

Timer object.

Return type:

Timer

property export

Attribute that holds the ‘export’ property.

Type:

Export

parse_args(argv=None)[source]

Parse the command line arguments to set the execution parameters.

Parameters:

argv (list[str]) – List of arguments inserted before those set with set_argv() or sys.argv.

sub_tpmax(tsub)[source]

Reduce the cpu time limit of tsub.

incr_command_counter()[source]

Increment the counter of Commands.

Returns:

Current value of the counter.

Return type:

int

register_global_object(key, obj)[source]

Register an object to be callable from libaster.

Parameters:
  • key (str) – Access key.

  • obj (misc) – Registered object, usually a class or a function.

property catalc

Attribute that holds the catalog of behavior.

property logical_unit

Attribute that holds the logical units manager.

property syntax

Attribute that holds the command syntax class.

property print_header

Attribute that holds the ‘print_header’ function.

Type:

func

property checksd

Attribute that holds the ‘checksd’ property.

Type:

func

property testresu_print

Attribute that holds the ‘testresu_print’ property.

Type:

func

property iniran

Attribute that holds the ‘iniran’ function.

Type:

func

property getran

Attribute that holds the ‘getran’ function.

Type:

func

class code_aster.Utilities.ExecutionParameter.MemoryAction(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)[source]

Bases: Action

Specific action to store the memory limit argument.

__call__(parser, namespace, value, optstr)[source]

Check and store the memory limit.

:param See argparse.Action().:

code_aster.Utilities.ExecutionParameter.get_program_path(program)[source]

Return the path to program as stored by ‘waf configure’.

Returns:

Path stored during configuration or program itself otherwise.

Return type:

str

code_aster.Utilities.ExecutionParameter.disable_fpe()[source]

Context manager to locally disable FPE interception.

Definition of options/flags for execution.

class code_aster.Utilities.options.Options(value)[source]

Bases: IntFlag

Enumerator for execution options.

Some options are enabled and/or disabled from command line options. Some others are internally used by programming.

  • Debug: Debug mode.

  • Abort: Abort instead of raising an exception in case of errors.

  • WarningAsError: Turns warnings into errors.

  • ForceStart: Start a new calculation even if a database exists.

  • Continue: Restart from an existing database.

  • StrictUnpickling: Fail when an object can not be unpickled.

  • UseLegacyMode: Create ‘CO’ objects instead of namedtuple.

  • ShowDeprecated: Show deprecation warnings.

  • ShowSyntax: Show syntax of commands.

  • ShowChildCmd: Show children commands called in depth.

  • TestMode: Testcase mode.

  • SlaveMode: Execution embedded by another program (do not abort, do not exit in case of time limit…).

  • InteractiveInterpreter: Indicates an interactive execution.

  • LastStep: Last step of a study, database won’t be reloaded from the temporary directory.

  • SaveBase: The database will be copied at the end of the calculation.

  • HPCMode: High Performance Computing mode, parallel computing using domain decomposition.

classmethod by_name(name)[source]

Return an option value by its name. AttributeError is raised if the option does not exist.

Parameters:

name (str) – Option name.

Returns:

Option value.

Return type:

int

i18n — Internationalization support

Internationalization support for code_aster.

code_aster.Utilities.i18n.get_language()[source]

Return default language (2 letters)

class code_aster.Utilities.i18n.Language(*args, **kws)[source]

Bases: object

Simple class to switch between languages.

__init__()[source]

Initialization

property translate

Attribute providing the translation function

set_localedir(path)[source]

Change the locale directory

set_domain()[source]

set the current domain

get_current_settings()[source]

Return the current language.

translation(lang=None)[source]

Return an instance of the translation object for the given ‘lang’.

code_aster.Utilities.i18n.translate(source_text)[source]

Get translation text for source text.

Parameters:

source_text (str) – Text being translated.

Returns:

Translated text.

Return type:

str

injector — Methods injection in pybind11 Objects

code_aster.Utilities.injector.injector(pybind_class)[source]

Decorator to inject methods into pybind11 objects.

Private methods are not injected, except a sublist: __add__, __call__, __eq__, __getattr__, __getinitargs__, __getitem__, __getstate__, __getstate_manages_dict__, __iadd__, __imul__, __init__, __len__, __mul__, __setstate__.

Parameters:

pybind_class (pybind11 class) – pybind11 class to enrich.

Returns:

Decorated class.

Return type:

class

logger — Logging and messages output

This module defines a logger object and error functions. All message outputs should pass by this object. Probably additional levels should be added to distinguish low-debug messages, debug messages that may be interesting for the user (equivalent to INFO=2)… It might be necessary to refactor it in C++ for better performance and a global access (no C interface currently)…

class code_aster.Utilities.logger.PerLevelFormatter(fmt=None, datefmt=None, style='%', validate=True)[source]

Bases: Formatter

Formatter for messages

format(record)[source]

Enhance error and warning messages

class code_aster.Utilities.logger.PerLevelColorFormatter(fmt=None, datefmt=None, style='%', validate=True)[source]

Bases: PerLevelFormatter

Formatter for messages

_adjust_color(level)[source]

Choose a color function according to the level

format(record)[source]

Enhance error and warning messages

class code_aster.Utilities.logger.HgStreamHandler(stream=None)[source]

Bases: StreamHandler

StreamHandler switching between sys.stdout and sys.stderr like the mercurial ui does

_adjust_stream(level)[source]

Adjust the stream according to the given level

emit(record)[source]

Enhance error and warning messages

code_aster.Utilities.logger.build_logger(level=20, raise_exception=True)[source]

Initialize the logger with its handlers.

Parameters:
  • level (int) – Logging level.

  • raise_exception (bool) – If True (default), an exception is raised in case of error.

Returns:

logger object.

Return type:

Logger

code_aster.Utilities.logger.loglevel(level)[source]

Change the logging level.

Parameters:

level (int) – Logger level.

code_aster.Utilities.logger.with_loglevel(level=10, with_result=False)[source]

Decorator to temporarly change the logging level for a function (only for debuging a priori).

Example:

@with_loglevel()
def my_function(its_args):
    [...]
Parameters:
  • level (int) – Logger level.

  • with_result (bool) – If True, the result is logged (debug mode).

code_aster.Utilities.logger._colorize(color, string)[source]

Return the colored string

code_aster.Utilities.logger.red(string)

Return the colored string

code_aster.Utilities.logger.green(string)

Return the colored string

code_aster.Utilities.logger.blue(string)

Return the colored string

code_aster.Utilities.logger.magenta(string)

Return the colored string

code_aster.Utilities.logger.cyan(string)

Return the colored string

code_aster.Utilities.logger.yellow(string)

Return the colored string

code_aster.Utilities.logger.grey(string)

Return the colored string

outputs — Utilities for outputs on console

This module defines helper functions for outputs of code_aster.

class code_aster.Utilities.outputs.CommandRepresentation(limit=0, indent=0)[source]

Bases: object

Return a representation of a dict of an executed command with its keywords.

Parameters:
  • limit (int) – Limits the output to the first occurrences of factor keywords or in the lists of values. Warning: Using limit may generate an invalid commands file.

  • indent (int) – Indentation of the first line.

_limit

Maximum number of occurrences for sequences.

Type:

int

_limit_reached

Tell if the limit has been reached at least once.

Type:

bool

_lines

List of lines.

Type:

list[str]

_curline

List of strings composing the current line.

Type:

list[str]

_indent

Stack of indentation levels.

Type:

list[int]

__init__(limit=0, indent=0)[source]
_newline()[source]

Initialize a new line.

_endline()[source]

Add the current line.

_add_indent()[source]

Set the next indent spacing.

_reset_indent()[source]

Revert indent spacing to its previous level.

get_text()[source]

Return the text

repr_command(name, keywords, result)[source]

Write the representation of a command.

Parameters:
  • name (str) – Command name.

  • keywords (dict) – Dict of keywords.

  • result (str) – Name of the result.

repr_keywords(item, parent=None)[source]

Write the representation of an object.

Parameters:

item (misc) – Item to represent. It may be a dict of keywords, a sequence (list or tuple)…

repr_sequence(sequence)[source]

Write the representation of sequence.

repr_value(value)[source]

Write the representation of a keyword value.

_limited(idx, sequence, string)[source]

Tell if the output must be limited.

end()[source]

Close the export

classmethod clean(text)[source]

Clean a text generated by ExportToCommVisitor.

code_aster.Utilities.outputs.decorate_name(name)[source]

Decorate a DataStructure’s name.

Parameters:

name (str) – Name of the object.

code_aster.Utilities.outputs.command_text(command_name, keywords, result='', limit=0)[source]

Return a text representation of a command.

Use limit=NN to limit the output to the fist NN occurrences in sequences.

Parameters:
  • command_name (str) – Command name.

  • keywords (dict) – Dictionary of keywords.

  • result (str) – Name of the result.

  • limit (int) – If limit is a positive number, only the limit first occurrences are printed (default is 0, unlimited.

Returns:

String representation.

Return type:

str

class code_aster.Utilities.statistics_manager.Profiler[source]

Bases: object

This object defines a decorator to count the number of calls and to measure the execution time of a function or a method.

__init__()[source]
measure(func)[source]

Main decorator.

reset_stats()[source]

Reset statistics.

print_stats(by_class=True)[source]

Show profiler statistics.

Parameters:

by_class (bool) – Group functions by class if True.

static key(callable, *args)[source]

Build a name to be used as a key to identify the called function.

Parameters:
  • callable (function) – Wrapped function or method.

  • args (tuple) – Positional arguments.

code_aster.Utilities.statistics_manager.profile(func)

Main decorator.

code_aster.Utilities.statistics_manager.print_stats(by_class=True)

Show profiler statistics.

Parameters:

by_class (bool) – Group functions by class if True.

code_aster.Utilities.statistics_manager.reset_stats()

Reset statistics.

strfunc — String manipulations utilities

This module defines utilities functions for strings manipulation.

code_aster.Utilities.strfunc.get_encoding()[source]

Return local encoding

code_aster.Utilities.strfunc.to_unicode(string)[source]

Try to convert string into a unicode string.

Parameters:

string (str) – String to convert to unicode.

Returns:

Unicode string.

Return type:

str

code_aster.Utilities.strfunc.from_unicode(ustring, encoding, errors='replace')[source]

Try to encode a unicode string using encoding.

Parameters:
  • ustring (str) – Unicode string to encode.

  • encoding (str) – Encoding name.

  • errors (str) – Behaviour in case of encoding error (see string.encode()).

Returns:

Encoded string.

Return type:

str

code_aster.Utilities.strfunc.convert(content, encoding=None, errors='replace')[source]

Convert content using encoding or default encoding if None.

Parameters:
  • content (str/unicode) – Text to convert.

  • encoding (str) – Encoding name.

  • errors (str) – Behaviour in case of encoding error (see string.encode()).

Returns:

Encoded string.

Return type:

str

code_aster.Utilities.strfunc.ufmt(uformat, *args)[source]

Helper function to format a string by converting all its arguments to unicode

code_aster.Utilities.strfunc.clean_string(chaine)[source]

Supprime tous les caractères non imprimables.

code_aster.Utilities.strfunc.cut_long_lines(txt, maxlen, sep='\n', l_separ=(' ', ',', ';', '.', ':'))[source]

Coupe les morceaux de txt (isolés avec sep) de plus de maxlen caractères. On utilise successivement les séparateurs de l_separ.

code_aster.Utilities.strfunc.maximize_lines(l_fields, maxlen, sep)[source]

Construit des lignes dont la longueur est au plus de maxlen caractères. Les champs sont assemblés avec le séparateur sep.

code_aster.Utilities.strfunc.force_split(txt, maxlen)[source]

Force le découpage de la ligne à ‘maxlen’ caractères.

code_aster.Utilities.strfunc.copy_text_to(text, files)[source]

Print a message into one or more files.

Files may be filenames (as string) or file-object.

Parameters:
  • text (str) – Message to be printed

  • files (str|file, list[str|file]) – Filename(s) or file-object(s)

code_aster.Utilities.strfunc._fixed_length(lines, maxlen, align='<')[source]

Fix lines length at maxlen.

Parameters:
  • lines (list[str]) – List of lines.

  • maxlen (int) – Lines length.

  • align (str) – One of “<”, “^”, “>”

Returns:

List of formatted lines.

Return type:

list[str]

code_aster.Utilities.strfunc.textbox(text, maxlen=90)[source]

Format a text into a box to be highlighted.

Parameters:
  • text (str) – Text to be decorated.

  • maxlen (int) – Lines length.

Returns:

Decorated text.

Return type:

str

code_aster.Utilities.strfunc.center(text, maxlen=90)[source]

Format a text as centered.

Parameters:
  • text (str) – Text to be centered.

  • maxlen (int) – Lines length.

Returns:

Centered text.

Return type:

str

Tester — Checking code_aster execution of testcases

code_aster.Utilities.Tester.addSuccess(method)[source]

Decorator to wrap TestCase methods by calling writeResult

code_aster.Utilities.Tester.where(level=3)[source]

Return the filename/line number where the test is called.

Parameters:

level (Optional[int]) – Number of frames to rewind to find the caller. Defaults to 3 (1: here, 2: write_xxx, 3: assertXxx).

Returns:

Filename and line number.

Return type:

(str, int)

class code_aster.Utilities.Tester.AssertRaisesContext(expected, test_case, expected_regexp=None)[source]

Bases: _AssertRaisesContext

Wrap Context of TestCase object

__init__(expected, test_case, expected_regexp=None)[source]
class code_aster.Utilities.Tester.TestCase(methodName='runTest', silent=False)[source]

Bases: TestCase

Similar to a unittest.TestCase Does not fail but print result OK/NOOK in the .resu file

__init__(methodName='runTest', silent=False)[source]

Initialization

property last_failed

Tell if the last test failed.

Type:

bool

runTest()[source]

Does nothing

printSummary()[source]

Print a summary of the tests

writeResult(ok, funcTest, msg, exc=None)[source]

Write a message in the result file

assertRaises(excClass, callableObj=None, *args, **kwargs)[source]

Fail unless an exception of class excClass is raised

assertRaisesRegex(expected_exception, expected_regexp, callable_obj=None, *args, **kwargs)[source]

Asserts that the message in a raised exception matches a regexp.

assertArrayEqual(actual, reference, rtol=1e-07, atol=1e-06)[source]

Compare numpy arrays using isclose tolerance.

If assertion fails a message will be printed detailling failing rows.

Parameters:
  • actual (numpy.ndarray) – 1D or 2D

  • reference (numpy.ndarray) – 1D or 2D

  • rtol (float) – relative tolerance

  • atol (float) – absolute tolerance

assertAlmostEqual(first, second, places=None, msg=None, delta=None)[source]

Fail if the two objects are unequal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is more than the given delta.

Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit).

If the two objects compare equal then they will automatically compare almost equal.

assertCountEqual(first, second, msg=None)[source]

Asserts that two iterables have the same elements, the same number of times, without regard to order.

self.assertEqual(Counter(list(first)),

Counter(list(second)))

Example:
  • [0, 1, 1] and [1, 0, 1] compare equal.

  • [0, 0, 1] and [0, 1] compare unequal.

assertDictContainsSubset(subset, dictionary, msg=None)[source]

Checks whether dictionary is a superset of subset.

assertEqual(first, second, msg=None)[source]

Fail if the two objects are unequal as determined by the ‘==’ operator.

assertFalse(expr, msg=None)[source]

Check that the expression is false.

assertGreater(a, b, msg=None)[source]

Just like self.assertTrue(a > b), but with a nicer default message.

assertGreaterEqual(a, b, msg=None)[source]

Just like self.assertTrue(a >= b), but with a nicer default message.

assertIn(member, container, msg=None)[source]

Just like self.assertTrue(a in b), but with a nicer default message.

assertIs(expr1, expr2, msg=None)[source]

Just like self.assertTrue(a is b), but with a nicer default message.

assertIsInstance(obj, cls, msg=None)[source]

Same as self.assertTrue(isinstance(obj, cls)), with a nicer default message.

assertIsNone(obj, msg=None)[source]

Same as self.assertTrue(obj is None), with a nicer default message.

assertIsNot(expr1, expr2, msg=None)[source]

Just like self.assertTrue(a is not b), but with a nicer default message.

assertIsNotNone(obj, msg=None)[source]

Included for symmetry with assertIsNone.

assertLess(a, b, msg=None)[source]

Just like self.assertTrue(a < b), but with a nicer default message.

assertLessEqual(a, b, msg=None)[source]

Just like self.assertTrue(a <= b), but with a nicer default message.

assertMultiLineEqual(first, second, msg=None)[source]

Assert that two multi-line strings are equal.

assertNotAlmostEqual(first, second, places=None, msg=None, delta=None)[source]

Fail if the two objects are equal as determined by their difference rounded to the given number of decimal places (default 7) and comparing to zero, or by comparing that the difference between the two objects is less than the given delta.

Note that decimal places (from zero) are usually not the same as significant digits (measured from the most significant digit).

Objects that are equal automatically fail.

assertNotEqual(first, second, msg=None)[source]

Fail if the two objects are equal as determined by the ‘!=’ operator.

assertNotIn(member, container, msg=None)[source]

Just like self.assertTrue(a not in b), but with a nicer default message.

assertNotIsInstance(obj, cls, msg=None)[source]

Included for symmetry with assertIsInstance.

assertNotRegex(text, unexpected_regex, msg=None)[source]

Fail the test if the text matches the regular expression.

assertRegex(text, expected_regex, msg=None)[source]

Fail the test unless the text matches the regular expression.

assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)[source]

An equality assertion for ordered sequences (like lists and tuples).

For the purposes of this function, a valid ordered sequence type is one which can be indexed, has a length, and has an equality operator.

Parameters:
  • seq1 – The first sequence to compare.

  • seq2 – The second sequence to compare.

  • seq_type – The expected datatype of the sequences, or None if no datatype should be enforced.

  • msg – Optional message to use on failure instead of a list of differences.

assertSetEqual(set1, set2, msg=None)[source]

A set-specific equality assertion.

Parameters:
  • set1 – The first set to compare.

  • set2 – The second set to compare.

  • msg – Optional message to use on failure instead of a list of differences.

assertSetEqual uses ducktyping to support different types of sets, and is optimized for sets specifically (parameters must support a difference method).

assertTrue(expr, msg=None)[source]

Check that the expression is true.

assertTupleEqual(tuple1, tuple2, msg=None)[source]

A tuple-specific equality assertion.

Parameters:
  • tuple1 – The first tuple to compare.

  • tuple2 – The second tuple to compare.

  • msg – Optional message to use on failure instead of a list of differences.