Beispiel #1
0
def test_should_raise_an_exception_when_unwrap_or_throw_with_a_failure_result(
):

    result = Failure(Error())

    with pytest.raises(Error):
        _ = result.unwrap_or_throw()
Beispiel #2
0
    def run(self, name: str, dependency_config: DependencyConfig,
            logger: ILogger) -> Result:
        dependency_path = os.path.join(self.base_path, name)
        if os.path.exists(dependency_path):
            logger.log(
                INFO,
                f"{self.__class__.__name__} - dependency {name} already exists"
            )
            return Success()
        os.makedirs(dependency_path, exist_ok=True)

        if not dependency_config.auth_required:
            auth = None
        else:
            credentials_var = os.environ.get(dependency_config.credentials_env)
            if credentials_var is None:
                return Failure(
                    CrendentialsEnvError(dependency_config.credentials_env))
            username, password = credentials_var.split(":")
            auth = HTTPBasicAuth(username, password)

        self.__download_file(dependency_path, dependency_config.url, auth)

        if dependency_config.unzip:
            try:
                unzip_file(dependency_path, dependency_config.url)
            except BadZipFile:
                return Failure(BadZipFileError(name))

        return Success()
Beispiel #3
0
def test_should_be_the_same_a_result_with_an_error_failure_with_a_failure_class(
):

    result = Result(failure=Error())
    failure = Failure()
    failure_with_error = Failure(Error())

    assert result == failure
    assert result == failure_with_error
    assert result == isFailure
Beispiel #4
0
 def from_filename(filename: str) -> Result[Any, Error]:
     if not os.path.isfile(filename):
         return Failure(ConfigFileNotFoundError(filename))
     try:
         with open(filename) as file:
             petisco_dict = yaml.load(file, Loader=yaml.FullLoader)
             config_event = ConfigEvents.from_dict(petisco_dict)
             return Success(config_event)
     except (ParserError, ScannerError) as e:
         message = f"Error loading {filename} file: {repr(e.__class__)} {e} | {traceback.format_exc()}"
         return Failure(ConfigFileNotValidError(message))
def test_should_transform_a_failure_result_encapsulated_value():
    def transform(domain_error):
        if isinstance(domain_error, Error):
            return "Error"
        else:
            return domain_error

    result = Failure(Error())
    result.map(transform)

    assert result.value == "Error"
Beispiel #6
0
    def to_result(self) -> Result[Any, Error]:
        name = None if self == "None" else self

        if name is not None:
            if len(self) > self.length_limit:
                return Failure(InputExceedLengthLimitError(message=name))
            else:
                if not re.search(r"^[a-zA-Z]*(([',. -][a-zA-Z ])?[a-zA-Z]*)*$",
                                 name):
                    return Failure(GivenInputIsNotValidError(message=name))
        return Success(name)
Beispiel #7
0
    def get_commands(self, action) -> Result[List[str], Error]:
        if action == "install":
            if not self.config.install:
                return Failure(EmptyConfigError())
            commands = self.config.install.run
        else:
            step = self.config.steps.get(action)
            if not step:
                return Failure(EmptyConfigError())
            commands = step.run

        return Success(commands)
Beispiel #8
0
    def to_result(self) -> Result[Any, Error]:
        client_id = None if self == "None" else self

        if client_id is not None:
            if len(client_id) > self.length:
                return Failure(InputExceedLengthLimitError(message=client_id))
            else:
                if not re.search(r"^[a-zA-Z]*(([',. -][a-zA-Z ])?[a-zA-Z]*)*$",
                                 client_id):
                    return Failure(
                        GivenInputIsNotValidError(message=client_id))
        return Success(client_id)
Beispiel #9
0
def get_config(filename: str = r"lume.yml") -> Result[Config, Error]:
    if not os.path.isfile(filename):
        return Failure(ConfigFileNotFoundError(filename))

    try:
        with open(filename) as file:
            lume_dict = yaml.load(file, Loader=yaml.FullLoader)
            config = Config(lume_dict)
            return Success(config)
    except ParserError as e:
        message = f"Error loading {filename} file: {repr(e.__class__)} {e} | {traceback.format_exc()}"
        return Failure(ConfigFileNotValidError(message))
Beispiel #10
0
 def from_filename(filename: str) -> Result[Any, Error]:
     if not os.path.isfile(filename):
         return Failure(ConfigFileNotFoundError(filename))
     try:
         petisco_yml_folder = os.path.dirname(filename)
         with open(filename) as file:
             petisco_dict = yaml.load(file, Loader=yaml.FullLoader)
             petisco_dict["petisco_yml_folder"] = petisco_yml_folder
             config = Config.from_dict(petisco_dict).unwrap_or_return()
             return Success(config)
     except (ParserError, ScannerError) as e:
         message = f"Error loading {filename} file: {repr(e.__class__)} {e} | {traceback.format_exc()}"
         return Failure(ConfigFileNotValidError(message))
Beispiel #11
0
def test_should_call_on_failure_when_unwrap_or_else_with_a_result_failure():

    global called_on_failure
    called_on_failure = False

    def on_failure(failure_value):
        global called_on_failure
        called_on_failure = True
        assert isinstance(failure_value, Error)

    result = Failure(Error())

    _ = result.unwrap_or_else(on_failure)

    assert called_on_failure
Beispiel #12
0
def test_should_call_on_failure_when_unwrap_or_else_with_a_result_failure_without_passing_arguments(
):

    global called_on_failure
    called_on_failure = False

    def on_failure():
        global called_on_failure
        called_on_failure = True

    result = Failure(Error())

    _ = result.unwrap_or_else(on_failure)

    assert called_on_failure
    def create_certificate(
            self,
            user_id: str,
            template_name: str = "default",
            verbose: bool = False) -> Result[Dict, OnboardingError]:
        """
        This call is used to create a Certificate (Signed PDF Report) of the onboarding process for a specific user.
        It returns a identifier (certificate_id) as a reference of created resource.
        This resource contains all evidence defined in the template.


        Parameters
        ----------
        user_id
            User identifier
        template_name
            'default' (only available)
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns a str with a pdf_report_id.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.create_certificate(
            user_id=user_id, template_name=template_name, verbose=verbose)

        if response.status_code == 200:
            return Success(response.json()["certificate_id"])
        else:
            return Failure(
                OnboardingError.from_response(operation="create_certificate",
                                              response=response))
    def create_report(self,
                      user_id: str,
                      verbose: bool = False) -> Result[Dict, OnboardingError]:
        """

        This call is used to get the report of the onboarding process for a specific user.
        It returns information on all evidence that has been added and analyzed for that user,
        including documents and facial verifications.


        Parameters
        ----------
        user_id
            User identifier
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns a Dict with the generated report.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.create_report(user_id=user_id,
                                                        verbose=verbose)

        if response.status_code == 200:
            return Success(response.json()["report"])
        else:
            return Failure(
                OnboardingError.from_response(operation="create_report",
                                              response=response))
    def document_properties(
            self,
            user_id: str,
            document_id: str,
            verbose: bool = False) -> Result[str, OnboardingError]:
        """

        Returns the properties of a previously added document, such as face, MRZ or NFC availability

        Parameters
        ----------
        user_id
            User identifier

        document_id
            Document identifier

        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns dict with document properties.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.document_properties(
            user_id=user_id, document_id=document_id, verbose=verbose)

        if response.status_code == 200:
            return Success(response.json())
        else:
            return Failure(
                OnboardingError.from_response(operation="document_properties",
                                              response=response))
    def void_document(self,
                      user_id: str,
                      document_id: str,
                      verbose: bool = False) -> Result[bool, OnboardingError]:
        """

        Mark a document as invalid.


        Parameters
        ----------
        user_id
            User identifier
        document_id
            Document identifier
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns True.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.void_document(
            user_id=user_id, document_id=document_id, verbose=verbose)

        if response.status_code == 200:
            return isSuccess
        else:
            return Failure(
                OnboardingError.from_response(operation="void_document",
                                              response=response))
    def supported_documents(
            self,
            user_id: str,
            verbose: bool = False) -> Result[Dict[str, str], OnboardingError]:
        """
        This method is used to obtain a hierarchical-ordered dict with the information of the documents supported by the API.

        Parameters
        ----------
        user_id
            User identifier
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns dict with supported document.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.supported_documents(user_id=user_id,
                                                              verbose=verbose)
        if response.status_code == 200:
            return Success(response.json())
        else:
            return Failure(
                OnboardingError.from_response(operation="supported_documents",
                                              response=response))
    def void_selfie(self,
                    user_id: str,
                    verbose: bool = False) -> Result[bool, OnboardingError]:
        """

        This call is used to void the video of the user's face to the onboarding service.
        This will NOT erase the biometric face profile.

        Parameters
        ----------
        user_id
            User identifier
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns True.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.void_selfie(user_id=user_id,
                                                      verbose=verbose)

        if response.status_code == 200:
            return isSuccess
        else:
            return Failure(
                OnboardingError.from_response(operation="void_selfie",
                                              response=response))
    def delete_user(self,
                    user_id: str,
                    verbose: bool = False) -> Result[bool, OnboardingError]:
        """

        Delete all the information of a user

        Parameters
        ----------
        user_id
            User identifier
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns True.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.delete_user(user_id=user_id,
                                                      verbose=verbose)

        if response.status_code == 200:
            return isSuccess
        else:
            return Failure(
                OnboardingError.from_response(operation="delete_user",
                                              response=response))
    def get_authentication(
            self,
            user_id: str,
            authentication_id: str,
            verbose: bool = False) -> Result[Dict, OnboardingError]:
        """

        Returns the result of a authentication given a authentication_id

        Parameters
        ----------
        user_id
            User identifier
        authentication_id
            Authentication identifier
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns a Dict with the information of one authentication.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.get_authentication(
            user_id=user_id,
            authentication_id=authentication_id,
            verbose=verbose)

        if response.status_code == 200:
            return Success(response.json()["authentication"])
        else:
            return Failure(
                OnboardingError.from_response(operation="get_authentication",
                                              response=response))
    def authenticate_user(
            self,
            user_id: str,
            media_data: bytes,
            verbose: bool = False) -> Result[str, OnboardingError]:
        """

        Authenticate a previously registered User against a given media to verify the identity

        Parameters
        ----------
        user_id
            User identifier
        media_data
            Binary media data.
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns a authentication_id.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.authenticate_user(
            user_id=user_id, media_data=media_data, verbose=verbose)

        if response.status_code == 200:
            return Success(response.json()["authentication_id"])
        else:
            return Failure(
                OnboardingError.from_response(operation="authenticate_user",
                                              response=response))
    def retrieve_certificate(
            self,
            user_id: str,
            certificate_id: str,
            verbose: bool = False) -> Result[bytes, OnboardingError]:
        """

        Returns the binary data of an existent pdf report

        Parameters
        ----------
        user_id
            User identifier
        certificate_id
           Certificate Unique Identifier. You can obtain it using create_certificate method.
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns a binary pdf (bytes).
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.retrieve_certificate(
            user_id=user_id, certificate_id=certificate_id, verbose=verbose)

        if response.status_code == 200:
            return Success(response.content)
        else:
            return Failure(
                OnboardingError.from_response(operation="retrieve_certificate",
                                              response=response))
    def retrieve_certificates(
            self,
            user_id: str,
            verbose: bool = False) -> Result[List, OnboardingError]:
        """

        Returns summary info for created certificates

        Parameters
        ----------
        user_id
            User identifier
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns a list of dictionaries.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.retrieve_certificates(
            user_id=user_id, verbose=verbose)

        if response.status_code == 200:
            return Success(response.json()["certificates"])
        else:
            return Failure(
                OnboardingError.from_response(
                    operation="retrieve_certificates", response=response))
    def get_user_status(
            self,
            user_id: str,
            verbose: bool = False) -> Result[Dict, OnboardingError]:
        """

        Returns User status to be used as feedback from the onboarding process

        Parameters
        ----------
        user_id
            User identifier
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns a Dict with the status info.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.get_user_status(user_id=user_id,
                                                          verbose=verbose)

        if response.status_code == 200:
            return Success(response.json()["user"])
        else:
            return Failure(
                OnboardingError.from_response(operation="get_user_status",
                                              response=response))
    def get_authentications_ids(
            self,
            user_id: str,
            verbose: bool = False) -> Result[List[str], OnboardingError]:
        """

        Returns all authentications ids you have performed for a User, sorted by creation date in descending order.

        Parameters
        ----------
        user_id
            User identifier
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns a List of string with all the authentication_ids.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.get_authentications_ids(
            user_id=user_id, verbose=verbose)

        if response.status_code == 200:
            return Success(response.json()["authentication_ids"])
        else:
            return Failure(
                OnboardingError.from_response(
                    operation="get_authentications_ids", response=response))
    def get_users(self,
                  verbose: bool = False) -> Result[List[str], OnboardingError]:
        """

        Returns all users you have created, sorted by creation date in descending order.

        Parameters
        ----------
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns list of string with already created user_ids.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.get_users()

        if response.status_code == 200:
            return Success(response.json()["users"])
        else:
            return Failure(
                OnboardingError.from_response(operation="get_users",
                                              response=response))
    def retrieve_media(
            self,
            user_id: str,
            media_id: str,
            verbose: bool = False) -> Result[bytes, OnboardingError]:
        """

        Returns the binary data of a media resource

        Parameters
        ----------
        user_id
            User identifier
        media_id
            Identifier obtained, for example from the report
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns a binary image (bytes).
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.retrieve_media(user_id=user_id,
                                                         media_id=media_id,
                                                         verbose=verbose)

        if response.status_code == 200:
            return Success(response.content)
        else:
            return Failure(
                OnboardingError.from_response(operation="retrieve_media",
                                              response=response))
    def get_users_stats(self,
                        verbose: bool = False
                        ) -> Result[Dict, OnboardingError]:
        """

        Returns statistics about users in the Onboarding platform.

        Parameters
        ----------
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns a dict with users information
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.get_users_stats(verbose=verbose)

        if response.status_code == 200:
            return Success(response.json()["stats"])
        else:
            return Failure(
                OnboardingError.from_response(operation="get_users_stats",
                                              response=response))
Beispiel #29
0
 def exists(self, user_id: UserId) -> Result[bool, Error]:
     with self.session_scope() as session:
         user = (session.query(self.UserModel).filter(
             self.UserModel.user_id == user_id.value).first())
         if user:
             return isSuccess
         return Failure(UserNotFoundError(user_id))
    def add_selfie(self,
                   user_id: str,
                   media_data: bytes,
                   verbose: bool = False) -> Result[bool, OnboardingError]:
        """

        This call is used to upload for the first time the video of the user's face to the onboarding service.
        This video will be used to extract the biometric face profile.

        Parameters
        ----------
        user_id
            User identifier
        media_data
            Binary media data.
        verbose
            Used for print service response as well as the time elapsed


        Returns
        -------
            A Result where if the operation is successful it returns True.
            Otherwise, it returns an OnboardingError.
        """
        response = self.onboarding_client.add_selfie(user_id=user_id,
                                                     media_data=media_data,
                                                     verbose=verbose)

        if response.status_code == 200:
            return isSuccess
        else:
            return Failure(
                OnboardingError.from_response(operation="add_selfie",
                                              response=response))