1- import os
21import pytest
2+ import logging
3+ import re
34
45import requests_mock
56
89from unstructured_client .utils .retries import BackoffStrategy , RetryConfig
910
1011
11- def get_api_key ():
12- api_key = os .getenv ("UNS_API_KEY" )
13- if api_key is None :
14- raise ValueError ("""UNS_API_KEY environment variable not set.
15- Set it in your current shell session with `export UNS_API_KEY=<api_key>`""" )
16- return api_key
12+ FAKE_KEY = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
1713
18- # this test requires UNS_API_KEY be set in your shell session. Ex: `export UNS_API_KEY=<api_key>`
19- def test_backoff_strategy ():
14+
15+ def test_retry_with_backoff_does_retry (caplog ):
16+ caplog .set_level (logging .INFO )
2017 filename = "README.md"
2118 backoff_strategy = BackoffStrategy (
2219 initial_interval = 100 , max_interval = 1000 , exponent = 1.5 , max_elapsed_time = 3000
@@ -28,13 +25,10 @@ def test_backoff_strategy():
2825 with requests_mock .Mocker () as mock :
2926 # mock a 500 status code for POST requests to the api
3027 mock .post ("https://api.unstructured.io/general/v0/general" , status_code = 500 )
31- session = UnstructuredClient (api_key_auth = get_api_key () )
28+ session = UnstructuredClient (api_key_auth = FAKE_KEY )
3229
3330 with open (filename , "rb" ) as f :
34- files = shared .Files (
35- content = f .read (),
36- file_name = filename ,
37- )
31+ files = shared .Files (content = f .read (), file_name = filename )
3832
3933 req = shared .PartitionParameters (files = files )
4034
@@ -45,3 +39,28 @@ def test_backoff_strategy():
4539
4640 # the number of retries varies
4741 assert len (mock .request_history ) > 1
42+
43+
44+ def test_backoff_strategy_logs_retries (caplog ):
45+ caplog .set_level (logging .INFO )
46+ filename = "README.md"
47+ backoff_strategy = BackoffStrategy (
48+ initial_interval = 100 , max_interval = 1000 , exponent = 1.5 , max_elapsed_time = 3000
49+ )
50+ retries = RetryConfig (
51+ strategy = "backoff" , backoff = backoff_strategy , retry_connection_errors = True
52+ )
53+
54+ with requests_mock .Mocker () as mock :
55+ # mock a 500 status code for POST requests to the api
56+ mock .post ("https://api.unstructured.io/general/v0/general" , status_code = 500 )
57+ session = UnstructuredClient (api_key_auth = FAKE_KEY )
58+
59+ with open (filename , "rb" ) as f :
60+ files = shared .Files (content = f .read (), file_name = filename )
61+
62+ req = shared .PartitionParameters (files = files )
63+ with pytest .raises (Exception ):
64+ session .general .partition (req , retries = retries )
65+ pattern = re .compile (f"{ re .escape ('Retry attempt #1. Sleeping' )} .*{ 'seconds before retry' } " )
66+ assert bool (pattern .search (caplog .text ))
0 commit comments