
    hT                    @   d dl mZ d dlmZ d dlZd dlZd dlZd dlZd dlmZ d dl	m
Z
 d dlmZ d dlZd dlmZ d dlmZ d d	lmZ d d
lmZmZmZmZ d$dZd%dZej6                  d&d       Zej6                  d'd       Zej6                  d'd       Zej6                  d'd       Z	 	 	 	 d(dZ 	 	 	 	 d(dZ!	 	 	 	 d(dZ"d)dZ#d)dZ$d)dZ%d*dZ&d*dZ'	 	 	 	 d+dZ(d)dZ)d)dZ*d)dZ+d)dZ,d)dZ-	 	 	 	 	 	 d,dZ.	 	 	 	 	 	 d,d Z/	 	 	 	 	 	 d,d!Z0	 	 	 	 	 	 d,d"Z1	 	 	 	 	 	 d,d#Z2y)-    )annotations)partialN)datetime)Path)Any)LogCaptureFixture)get_versionClient)prepare_urlparse_responselogging_handlerConfigc                 
    d} | S )zProvide a simple tuples with debug entries for testing purposes.

    Parameters:
    None

    Returns:
    tuple: A tuple containing seven debug entries
    )DEBUGzREQUEST:zREQUEST_HEADERS:zREQUEST_CONTENT:z	RESPONSE:zRESP_HEADERS:z
RESP_CODE: )entriess    b/home/www/lekema-backend.kofcorporation.com/venv/lib/python3.12/site-packages/tests/test_client.pydebug_entriesr      s    G N    c                b    	 t        j                  | |       y# t        $ r t        d      w xY w)aV  Validate the format of a given date string against a specified datetime format.

    Parameters:
    date_text (str): The date string to be validated.
    datetime_format (str): The datetime format to which the date string should be validated.

    Raises:
    ValueError: If the date string does not match the specified datetime format.
    z.Incorrect data format, should be %Y%m%d_%H%M%SN)r   strptime
ValueError)	date_textdatetime_formats     r   validate_datetime_formatr   )   s5    K)_5 KIJJKs    .c                     ddddgi} d}| |fS )a*  Provide a simple data structure and its encoding for testing purposes.

    Parameters:
    None

    Returns:
    tuple: A tuple containing two elements:
        - A dictionary representing structured data with a list of dictionaries.
        - A string representing the encoding of the data.
    Data
first_nameJohn)NameValuezutf-8r   )datadata_encodings     r   simple_datar%   9   s*     	,89-D !Mr   c                 f    t         j                  d   t         j                  d   f} t        |       S )a   Create and return a Mailjet API client instance for version 3.0.

    Parameters:
    None

    Returns:
    Client: An instance of the Mailjet API client configured for version 3.0. The client is authenticated using the public and private API keys provided as environment variables.
    MJ_APIKEY_PUBLICMJ_APIKEY_PRIVATEauthosenvironr   r)   s    r   client_mj30r.   L   s2     	

%&


&'D tr   c                     d} t        |       S )a  Create and return a Mailjet API client instance for version 3.0, but with invalid authentication credentials.

    Parameters:
    None

    Returns:
    Client: An instance of the Mailjet API client configured for version 3.0.
           The client is authenticated using invalid public and private API keys.
           If the client is used to make requests, it will raise a ValueError.
    )invalid_public_keyinvalid_private_keyr)   r
   r)   s    r   client_mj30_invalid_authr2   ]   s    D tr   c                 h    t         j                  d   t         j                  d   f} t        | d      S )a7  Create and return a Mailjet API client instance for version 3.1.

    Parameters:
    None

    Returns:
    Client: An instance of the Mailjet API client configured for version 3.1.
           The client is authenticated using the public and private API keys provided as environment variables.

    Note:
    - The function retrieves the public and private API keys from the environment variables 'MJ_APIKEY_PUBLIC' and 'MJ_APIKEY_PRIVATE' respectively.
    - The client is initialized with the provided authentication credentials and the version set to 'v3.1'.
    r'   r(   zv3.1)r*   versionr+   r)   s    r   client_mj31r5   p   s:      	

%&


&'D  r   c                    | \  }}d}|Rd}t        j                  ||      }t        |t              sJ |s$|j	                  |      }t        |t
              sJ yyy)a  
    This function tests the conversion of structured data into JSON format with the specified encoding settings.

    Parameters:
    simple_data (tuple[dict[str, list[dict[str, str]]], str]): A tuple containing two elements:
        - A dictionary representing structured data with a list of dictionaries.
        - A string representing the encoding of the data.

    Returns:
    None: The function does not return any value. It performs assertions to validate the JSON conversion.
    TNensure_asciijsondumps
isinstancestrencodebytesr%   r#   r$   r8   	json_datas        r   -test_json_data_str_or_bytes_with_ensure_asciirB      sk     &D-L".(,	JJt,?	)S)))!((7Ii///  /r   c                    | \  }}d}|Rd}t        j                  ||      }t        |t              sJ |s$|j	                  |      }t        |t
              sJ yyy)a=  This function tests the conversion of structured data into JSON format with the specified encoding settings.

    It specifically tests the case where the 'ensure_ascii' parameter is set to False.

    Parameters:
    simple_data (tuple[dict[str, list[dict[str, str]]], str]): A tuple containing two elements:
        - A dictionary representing structured data with a list of dictionaries.
        - A string representing the encoding of the data.

    Returns:
    None: The function does not return any value. It performs assertions to validate the JSON conversion.
    FNr7   r9   r@   s        r   3test_json_data_str_or_bytes_with_ensure_ascii_falserD      sk     &D-L".(,	JJt,?	)S)))!((7Ii///  /r   c                    | \  }}d}d}|Rd}t        j                  ||      }t        |t              sJ |s$|j	                  |      }t        |t
              sJ yyy)a  
    This function tests the conversion of structured data into JSON format when the data is None.

    Parameters:
    simple_data (tuple[dict[str, list[dict[str, str]]], str]): A tuple containing two elements:
        - A dictionary representing structured data with a list of dictionaries.
        - A string representing the encoding of the data.

    Returns:
    None: The function does not return any value. It performs assertions to validate the JSON conversion.
    TNr7   r9   r@   s        r   test_json_data_is_nonerF      sp     &D-L37D".(,	JJt,?	)S)))!((7Ii///  /r   c                 n    t        j                  dt        d      } | j                  d      }|ddgk(  sJ y)a1  This function tests the prepare_url function by splitting a string containing underscores and converting the first letter of each word to uppercase.

    The function then compares the resulting list with an expected list.

    Parameters:
    None

    Note:
    - The function uses the re.sub method to replace uppercase letters with the prepare_url function.
    - It splits the resulting string into a list using the underscore as the delimiter.
    - It asserts that the resulting list is equal to the expected list ["contact", "managecontactslists"].
    [A-Z]contact_managecontactslists_contactmanagecontactslistsNresubr   split)namerP   s     r   test_prepare_url_list_splittingrR      s8     x.KLDzz#EY 56666r   c                 p    t        j                  dt        d      } | j                  d      d   }|dk(  sJ y)a  This function tests the prepare_url function by splitting a string containing underscores, and retrieving the first element of the resulting list.

    Parameters:
    None

    Note:
    - The function uses the re.sub method to replace uppercase letters with the prepare_url function.
    - It splits the resulting string into a list using the underscore as the delimiter.
    - It asserts that the first element of the split list is equal to "contact".
    rH   rI   rJ   r   rK   NrM   )rQ   fnames     r   #test_prepare_url_first_list_elementrU      s7     x.KLDC#EIr   c                     t        j                  dt        d      } t        dd      }||    \  }}|dk(  sJ |ddt	                d	k(  sJ y
)a  Test the prepare_url function by splitting a string containing underscores, and retrieving the first element of the resulting list.

    Additionally, this test verifies the URL and headers generated by the prepare_url function.

    Parameters:
    None

    Note:
    - The function uses the re.sub method to replace uppercase letters with the prepare_url function.
    - It creates a Config object with the specified version and API URL.
    - It retrieves the URL and headers from the Config object using the modified string as the key.
    - It asserts that the URL is equal to "https://api.mailjet.com/v3/REST/contact" and that the headers match the expected headers.
    rH   rI   v3https://api.mailjet.com/r4   api_url'https://api.mailjet.com/v3/REST/contactapplication/jsonmailjet-apiv3-python/vzContent-typez
User-agentNrN   rO   r   r   r	   rQ   configurlheaderss       r    test_prepare_url_headers_and_urlrd      sf     x.KLDD2LMF$<LC;;;;*.{}o>   r   c                t    | j                   j                  i       j                         }d|v r|d   dk(  sJ y)a  Tests a POST request with an empty data payload.

    This test sends a POST request to the 'create' endpoint using an empty dictionary
    as the data payload. It checks that the API responds with a 400 status code,
    indicating a bad request due to missing required parameters.

    Parameters:
        client_mj30 (Client): An instance of the Mailjet API client.

    Raises:
        AssertionError: If "StatusCode" is not in the result or if its value
        is not 400.
    )r#   
StatusCode  N)sendercreater:   r.   results     r   test_post_with_no_paramrl     sC     &&B&/446F6!f\&:c&AAA&Ar   c                h    | j                   j                         j                         }d|v rd|v sJ y)a  Tests a GET request to retrieve contact data without any parameters.

    This test sends a GET request to the 'contact' endpoint without filters or
    additional parameters. It verifies that the response includes both "Data"
    and "Count" fields, confirming the endpoint returns a valid structure.

    Parameters:
        client_mj30 (Client): An instance of the Mailjet API client.

    Raises:
        AssertionError: If "Data" or "Count" are not present in the response.
    r   CountN)rK   getr:   rj   s     r   test_get_no_paramrp   +  s9     %%))+002FV6 111 1r   c                    t        j                  t              5  | j                  j	                         j                          ddd       y# 1 sw Y   yxY w)a  This function tests the initialization of a Mailjet API client with invalid authentication credentials.

    Parameters:
    client_mj30_invalid_auth (Client): An instance of the Mailjet API client configured for version 3.0.
                                       The client is authenticated using invalid public and private API keys.

    Returns:
    None: The function does not return any value. It is expected to raise a ValueError when the client is used to make requests.

    Note:
    - The function uses the pytest.raises context manager to assert that a ValueError is raised when the client's contact.get() method is called.
    N)pytestraisesr   rK   ro   r:   )r2   s    r   /test_client_initialization_with_invalid_api_keyrt   <  s@     
z	" 6 ((,,.3356 6 6s   )AAc                     t        j                  dt        d      } t        dd      }||    \  }}|dk(  sJ |ddt	                d	k(  sJ y
)a{  Test prepare_url function with mixed case input.

    This function tests the prepare_url function by providing a string with mixed case characters.
    It then compares the resulting URL with the expected URL.

    Parameters:
    None

    Note:
    - The function uses the re.sub method to replace uppercase letters with the prepare_url function.
    - It creates a Config object with the specified version and API URL.
    - It retrieves the URL and headers from the Config object using the modified string as the key.
    - It asserts that the URL is equal to the expected URL and that the headers match the expected headers.
    rH   rK   rW   rX   rY   r[   r\   r]   r^   Nr_   r`   s       r   !test_prepare_url_mixed_case_inputrv   O  e     xi8DD2LMF$<LC;;;;*.{}o>   r   c                     t        j                  dt        d      } t        dd      }||    \  }}|dk(  sJ |ddt	                d	k(  sJ y
)ak  Test prepare_url function with empty input.

    This function tests the prepare_url function by providing an empty string as input.
    It then compares the resulting URL with the expected URL.

    Parameters:
    None

    Note:
    - The function uses the re.sub method to replace uppercase letters with the prepare_url function.
    - It creates a Config object with the specified version and API URL.
    - It retrieves the URL and headers from the Config object using the modified string as the key.
    - It asserts that the URL is equal to the expected URL and that the headers match the expected headers.
    rH    rW   rX   rY   z https://api.mailjet.com/v3/REST/r\   r]   r^   Nr_   r`   s       r   test_prepare_url_empty_inputrz   h  se     66(K,DD*DEF$<LC4444*.{}o>   r   c                     t        j                  dt        d      } t        dd      }||    \  }}|dk7  sJ |ddt	                d	k(  sJ y
)a}  Test the prepare_url function with input containing numbers.

    This function tests the prepare_url function by providing a string with numbers.
    It then compares the resulting URL with the expected URL.

    Parameters:
    None

    Note:
    - The function uses the re.sub method to replace uppercase letters with the prepare_url function.
    - It creates a Config object with the specified version and API URL.
    - It retrieves the URL and headers from the Config object using the modified string as the key.
    - It asserts that the URL is not equal to the expected URL and that the headers match the expected headers.
    rH   contact1_managecontactslists1rW   rX   rY   r[   r\   r]   r^   Nr_   r`   s       r   'test_prepare_url_with_numbers_input_badr}     sf     66(K)HIDD*DEF$<LC;;;;*.{}o>   r   c                     t        j                  dt        d      } t        dd      }||    \  }}|dk7  sJ |ddt	                d	k(  sJ y
)a  Test prepare_url function with input containing leading and trailing underscores.

    This function tests the prepare_url function by providing a string with leading and trailing underscores.
    It then compares the resulting URL with the expected URL.

    Parameters:
    None

    Note:
    - The function uses the re.sub method to replace uppercase letters with the prepare_url function.
    - It creates a Config object with the specified version and API URL.
    - It retrieves the URL and headers from the Config object using the modified string as the key.
    - It asserts that the URL is not equal to the expected URL and that the headers match the expected headers.
    rH   _contact_managecontactslists_rW   rX   rY   r[   r\   r]   r^   Nr_   r`   s       r   7test_prepare_url_leading_trailing_underscores_input_badr     sf     x.MNDD2LMF$<LC;;;;*.{}o>   r   c                     t        j                  dt        d      } t        dd      }||    \  }}|dk7  sJ |ddt	                d	k(  sJ y
)a  Test prepare_url function with mixed case input.

    This function tests the prepare_url function by providing a string with mixed case characters.
    It then compares the resulting URL with the expected URL.

    Parameters:
    None

    Note:
    - The function uses the re.sub method to replace uppercase letters with the prepare_url function.
    - It creates a Config object with the specified version and API URL.
    - It retrieves the URL and headers from the Config object using the modified string as the key.
    - It asserts that the URL is not equal to the expected URL and that the headers match the expected headers.
    rH   cOntactrW   rX   rY   r[   r\   r]   r^   Nr_   r`   s       r   %test_prepare_url_mixed_case_input_badr     rw   r   c                    | j                   j                         }t        |d d       |j                  dk(  sJ t	        j
                        dk(  sJ t        fdt               D              sJ y)This function tests the debug logging to stdout, ensuring that all debug entries are present.

    Parameters:
    client_mj30 (Client): An instance of the Mailjet API client.
    caplog (LogCaptureFixture): A fixture for capturing log entries.
    c                     t        d      S NFto_filer   r   r   r   <lambda>zDtest_debug_logging_to_stdout_has_all_debug_entries.<locals>.<lambda>      ?5#A r   Tdebug      c              3  :   K   | ]  }|j                   v   y wNtext.0xcaplogs     r   	<genexpr>zEtest_debug_logging_to_stdout_has_all_debug_entries.<locals>.<genexpr>       9AqFKK9   N)rK   ro   r   status_codelenrecordsallr   r.   r   rk   s    ` r   2test_debug_logging_to_stdout_has_all_debug_entriesr     sg       $$&F6AN$$$v~~!###99999r   c                    | j                   j                         }t        |d d       d|j                  cxk  rdk  sJ  J t	        j
                        dk(  sJ t        fdt               D              sJ y)	r   c                     t        d      S r   r   r   r   r   r   z^test_debug_logging_to_stdout_has_all_debug_entries_when_unknown_or_not_found.<locals>.<lambda>  r   r   Tr   rg        c              3  :   K   | ]  }|j                   v   y wr   r   r   s     r   r   z_test_debug_logging_to_stdout_has_all_debug_entries_when_unknown_or_not_found.<locals>.<genexpr>  r   r   N)cntactro   r   r   r   r   r   r   r   s    ` r   Ltest_debug_logging_to_stdout_has_all_debug_entries_when_unknown_or_not_foundr     sr     ##%F6AN&$$++++++v~~!###99999r   c                    d}| j                   j                  |      }t        |d d       |j                  dk(  sJ t	        j
                        dk(  sJ t        fdt               D              sJ y)	a`  This function tests the debug logging to stdout by retrieving message if id type mismatch, ensuring that all debug entries are present.

    GET https://api.mailjet.com/v3/REST/message/$MESSAGE_ID

    Parameters:
    client_mj30 (Client): An instance of the Mailjet API client.
    caplog (LogCaptureFixture): A fixture for capturing log entries.
    z*************c                     t        d      S r   r   r   r   r   r   zZtest_debug_logging_to_stdout_when_retrieve_message_with_id_type_mismatch.<locals>.<lambda>  r   r   Tr   rg   r   c              3  :   K   | ]  }|j                   v   y wr   r   r   s     r   r   z[test_debug_logging_to_stdout_when_retrieve_message_with_id_type_mismatch.<locals>.<genexpr>  r   r   Nmessagero   r   r   r   r   r   r   r.   r   _idrk   s    `  r   Htest_debug_logging_to_stdout_when_retrieve_message_with_id_type_mismatchr     n     C  $$S)F6AN$$$v~~!###99999r   c                    d}| j                   j                  |      }t        |d d       |j                  dk(  sJ t	        j
                        dk(  sJ t        fdt               D              sJ y)	a`  This function tests the debug logging to stdout by retrieving message if object not found, ensuring that all debug entries are present.

    GET https://api.mailjet.com/v3/REST/message/$MESSAGE_ID

    Parameters:
    client_mj30 (Client): An instance of the Mailjet API client.
    caplog (LogCaptureFixture): A fixture for capturing log entries.
    0000000000000c                     t        d      S r   r   r   r   r   r   zZtest_debug_logging_to_stdout_when_retrieve_message_with_object_not_found.<locals>.<lambda>  r   r   Tr   r   r   c              3  :   K   | ]  }|j                   v   y wr   r   r   s     r   r   z[test_debug_logging_to_stdout_when_retrieve_message_with_object_not_found.<locals>.<genexpr>  r   r   Nr   r   s    `  r   Htest_debug_logging_to_stdout_when_retrieve_message_with_object_not_foundr     r   r   c                &   | j                   j                         }t        |t        d       t	        t        d       t        j                         }t        j                  d      }|D ]  }t        |      j                  }t        |d       t        j                  j                  ||      }|j                  dk(  sJ t        |      j                         sJ t        d| d       t        |      j!                          t        d	| d
        y)a  This function tests the debug logging to a log file.

    It sends a GET request to the 'contact' endpoint of the Mailjet API client, parses the response,
    logs the debug information to a log file, validates that the log filename has the correct datetime format provided,
    and then verifies the existence and removal of the log file.

    Parameters:
    client_mj30 (Client): An instance of the Mailjet API client.
    caplog (LogCaptureFixture): A fixture for capturing log entries.
    Tr   r   z*.logz%Y%m%d_%H%M%Sr   zRemoving log file z...zThe log file z has been removed.N)rK   ro   r   r   r   r   cwdglobstemr   r,   pathjoinr   existsprintunlink)r.   r   rk   r   	log_fileslog_filelog_file_namelog_file_paths           r   test_debug_logging_to_log_filer     s       $$&F6?$7OT*
((*C		'"I 
<X++ @S(3!!S(((M"))+++"8*C01]""$hZ'9:;
<r   )returnz(tuple[str, str, str, str, str, str, str])r   r=   r   r=   r   None)r   +tuple[dict[str, list[dict[str, str]]], str])r   r   )r%   r   r   r   )r   r   )r.   r   r   r   )r2   r   r   r   )r.   r   r   r   r   r   )3
__future__r   	functoolsr   r   r:   r,   rN   r   pathlibr   typingr   rr   _pytest.loggingr   mailjet_rest.utils.versionr	   mailjet_restr   mailjet_rest.clientr   r   r   r   r   r   fixturer%   r.   r2   r5   rB   rD   rF   rR   rU   rd   rl   rp   rt   rv   rz   r}   r   r   r   r   r   r   r   r   r   r   <module>r      s   "    	 	     - 2  T T*K   $     $  00<0	060<0	080<0	087$ 6B$2"6$6	6&22222::: 
:$::: 
:&::: 
:*::: 
:*<<!2<	<r   