pyracmon.testing API documentation

# Module `pyracmon.testing`

Expand source code

    from datetime import datetime, date, time, timedelta
    from .model import TestingMixin, truncate
    from .util import default_test_config

    __all__ = [
        "TestingMixin",
        "default_test_config",
        "truncate",
        #"near",
        #"let",
        #"one_of",
    ]

## Sub-modules

`pyracmon.testing.model`
`pyracmon.testing.util`

## Functions

`def default_test_config() ‑> PyracmonConfiguration`
  Expand source code

      def default_test_config() -> PyracmonConfiguration:
          return config.get()

`def truncate(db: Connection, *models: type[TruncateMixin])`

  Truncate tables in order.

  ## Args

  `db`
    DB connection.
  `tables`
    Models of tables to truncate.
  Expand source code

      def truncate(db: Connection, *models: type[TruncateMixin]):
          """
          Truncate tables in order.

          Args:
              db: DB connection.
              tables: Models of tables to truncate.
          """
          if len(models) == 0:
              raise ValueError(f"No tables are specified. Did you forget to pass DB connection at the first argument?")

          for m in models:
              m.truncate(db)

## Classes

`class TestingMixin`

  Mixin class for model types providing methods designed for testing.

  Expand source code

      class TestingMixin(TestingModel):
          """
          Mixin class for model types providing methods designed for testing.
          """
          @classmethod
          def by(cls, index: int) -> Self:
              """
              Set current fixture index.

              Args:
                  index: Fixture index.
              Returns:
                  This type.
              """
              TestingState.set_index(cls, index)
              return cls # type: ignore

          @overload
          @classmethod
          def fixture(
              cls,
              db: Optional[Connection],
              variable: None = None,
              index: Optional[int] = None,
              cfg: Optional[PyracmonConfiguration] = None,
          ) -> list[Self]: ...
          @overload
          @classmethod
          def fixture(
              cls,
              db: Optional[Connection],
              variable: int,
              index: Optional[int] = None,
              cfg: Optional[PyracmonConfiguration] = None,
          ) -> list[Self]: ...
          @overload
          @classmethod
          def fixture(
              cls,
              db: Optional[Connection],
              variable: Self,
              index: Optional[int] = None,
              cfg: Optional[PyracmonConfiguration] = None,
          ) -> Self: ...
          @overload
          @classmethod
          def fixture(
              cls,
              db: Optional[Connection],
              variable: dict[str, Any],
              index: Optional[int] = None,
              cfg: Optional[PyracmonConfiguration] = None,
          ) -> Self: ...
          @overload
          @classmethod
          def fixture(
              cls,
              db: Optional[Connection],
              variable: list[Self],
              index: Optional[int] = None,
              cfg: Optional[PyracmonConfiguration] = None,
          ) -> list[Self]: ...
          @overload
          @classmethod
          def fixture(
              cls,
              db: Optional[Connection],
              variable: list[dict[str, Any]],
              index: Optional[int] = None,
              cfg: Optional[PyracmonConfiguration] = None,
          ) -> list[Self]: ...
          @classmethod
          def fixture(
              cls,
              db: Optional[Connection],
              variable: Optional[Union[int, dict[str, Any], Self, list[dict[str, Any]], list[Self]]] = None,
              index: Optional[int] = None,
              cfg: Optional[PyracmonConfiguration] = None,
          ) -> Union[Self, list[Self]]:
              """
              Inserts record(s) with auto-generated column values.

              Args:
                  db: DB connection. If a value evaluated to be `False` in boolean context, generated model is not inserted and just returned.
                  variable: When `int`, inserts records as many as the number. All of their column values are generated.
                      When `dict`, model object or a list of them, inserts record(s) represented by them. Unspecified column values are generated.
                  index: Use this to specify index used to generate column values explicitly. If set, indexing state is not updated.
                  cfg: Configuration used to control the generation of fixuture values.
                      This argument is prepared only for internal use and can be changed or removed in future version.
              Returns:
                  Inserted model(s).
              """
              if variable is None or isinstance(variable, int):
                  num = variable or 1
                  index = TestingState.inc(cls, num) if index is None else index
                  models = [_generate_model(cls, index+i, None, cfg) for i in range(num)]
                  if db:
                      cls.inserts(db, models)
                  return models
              elif isinstance(variable, (cls, dict)):
                  num = 1
                  index = TestingState.inc(cls, num) if index is None else index
                  model = _generate_model(cls, index, variable, cfg)
                  if db:
                      cls.insert(db, model)
                  return model
              elif isinstance(variable, list):
                  num = len(variable)
                  index = TestingState.inc(cls, num) if index is None else index
                  models = [_generate_model(cls, index+i, v, cfg) for i, v in enumerate(variable)]
                  if db:
                      cls.inserts(db, models)
                  return models
              else:
                  raise ValueError(f"Second argument of fixture() must be an int, dict, model or list of dict or model but {type(variable)} is passed.")

          def match(self, **expected: Union[Matcher, Any]) -> bool:
              """
              Tests columns values matches to expected values.

              .. warning::
                  This method will be replaced in different implementation.

              Args:
                  expected: Expected values.
              Returns
                  Matches or not.
              """
              for k, v in expected.items():
                  actual = getattr(self, k)

                  if isinstance(v, Matcher):
                      if not v.match(actual):
                          return False
                  else:
                      if v != actual:
                          return False
              return True

  ### Ancestors

  - TestingModel

  ### Static methods

  `def by(index: int) ‑> typing_extensions.Self`

    Set current fixture index.

    ## Args

    `index`
      Fixture index.

    ## Returns

    This type.

    Expand source code

        @classmethod
        def by(cls, index: int) -> Self:
            """
            Set current fixture index.

            Args:
                index: Fixture index.
            Returns:
                This type.
            """
            TestingState.set_index(cls, index)
            return cls # type: ignore

  `def fixture(db: Optional[Connection], variable: Union[int, dict[str, Any], typing_extensions.Self, list[dict[str, Any]], list[typing_extensions.Self], ForwardRef(None)] = None, index: Optional[int] = None, cfg: Optional[PyracmonConfiguration] = None) ‑> Union[typing_extensions.Self, list[typing_extensions.Self]]`

    Inserts record(s) with auto-generated column values.

    ## Args

    `db`
      DB connection. If a value evaluated to be `False` in boolean context, generated model is not inserted and just returned.
    `variable`
      When `int`, inserts records as many as the number. All of their column values are generated. When `dict`, model object or a list of them, inserts record(s) represented by them. Unspecified column values are generated.
    `index`
      Use this to specify index used to generate column values explicitly. If set, indexing state is not updated.
    `cfg`
      Configuration used to control the generation of fixuture values. This argument is prepared only for internal use and can be changed or removed in future version.

    ## Returns

    Inserted model(s).

    Expand source code

        @classmethod
        def fixture(
            cls,
            db: Optional[Connection],
            variable: Optional[Union[int, dict[str, Any], Self, list[dict[str, Any]], list[Self]]] = None,
            index: Optional[int] = None,
            cfg: Optional[PyracmonConfiguration] = None,
        ) -> Union[Self, list[Self]]:
            """
            Inserts record(s) with auto-generated column values.

            Args:
                db: DB connection. If a value evaluated to be `False` in boolean context, generated model is not inserted and just returned.
                variable: When `int`, inserts records as many as the number. All of their column values are generated.
                    When `dict`, model object or a list of them, inserts record(s) represented by them. Unspecified column values are generated.
                index: Use this to specify index used to generate column values explicitly. If set, indexing state is not updated.
                cfg: Configuration used to control the generation of fixuture values.
                    This argument is prepared only for internal use and can be changed or removed in future version.
            Returns:
                Inserted model(s).
            """
            if variable is None or isinstance(variable, int):
                num = variable or 1
                index = TestingState.inc(cls, num) if index is None else index
                models = [_generate_model(cls, index+i, None, cfg) for i in range(num)]
                if db:
                    cls.inserts(db, models)
                return models
            elif isinstance(variable, (cls, dict)):
                num = 1
                index = TestingState.inc(cls, num) if index is None else index
                model = _generate_model(cls, index, variable, cfg)
                if db:
                    cls.insert(db, model)
                return model
            elif isinstance(variable, list):
                num = len(variable)
                index = TestingState.inc(cls, num) if index is None else index
                models = [_generate_model(cls, index+i, v, cfg) for i, v in enumerate(variable)]
                if db:
                    cls.inserts(db, models)
                return models
            else:
                raise ValueError(f"Second argument of fixture() must be an int, dict, model or list of dict or model but {type(variable)} is passed.")

  ### Methods

  `def match(self, **expected: Union[Matcher, Any]) ‑> bool`

    Tests columns values matches to expected values.

    Warning

    This method will be replaced in different implementation.

    ## Args

    `expected`
      Expected values.

    Returns Matches or not.

    Expand source code

        def match(self, **expected: Union[Matcher, Any]) -> bool:
            """
            Tests columns values matches to expected values.

            .. warning::
                This method will be replaced in different implementation.

            Args:
                expected: Expected values.
            Returns
                Matches or not.
            """
            for k, v in expected.items():
                actual = getattr(self, k)

                if isinstance(v, Matcher):
                    if not v.match(actual):
                        return False
                else:
                    if v != actual:
                        return False
            return True