loop-api-sdk 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- loop_api_sdk-0.1.0/PKG-INFO +53 -0
- loop_api_sdk-0.1.0/README.md +31 -0
- loop_api_sdk-0.1.0/pyproject.toml +4 -0
- loop_api_sdk-0.1.0/setup.cfg +39 -0
- loop_api_sdk-0.1.0/setup.py +4 -0
- loop_api_sdk-0.1.0/src/loop_api_sdk/__init__.py +21 -0
- loop_api_sdk-0.1.0/src/loop_api_sdk/client.py +182 -0
- loop_api_sdk-0.1.0/src/loop_api_sdk/exceptions.py +30 -0
- loop_api_sdk-0.1.0/src/loop_api_sdk.egg-info/PKG-INFO +53 -0
- loop_api_sdk-0.1.0/src/loop_api_sdk.egg-info/SOURCES.txt +13 -0
- loop_api_sdk-0.1.0/src/loop_api_sdk.egg-info/dependency_links.txt +1 -0
- loop_api_sdk-0.1.0/src/loop_api_sdk.egg-info/requires.txt +10 -0
- loop_api_sdk-0.1.0/src/loop_api_sdk.egg-info/top_level.txt +1 -0
- loop_api_sdk-0.1.0/tests/test_client.py +73 -0
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: loop-api-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Cliente Python para a API de sincronização do Loop
|
|
5
|
+
Classifier: Programming Language :: Python :: 3
|
|
6
|
+
Classifier: Programming Language :: Python :: 3.6
|
|
7
|
+
Classifier: Programming Language :: Python :: 3.7
|
|
8
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
15
|
+
Requires-Python: >=3.6
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
Requires-Dist: requests>=2.25
|
|
18
|
+
Requires-Dist: dataclasses; python_version < "3.7"
|
|
19
|
+
Requires-Dist: importlib-metadata; python_version < "3.8"
|
|
20
|
+
Provides-Extra: dev
|
|
21
|
+
Requires-Dist: pytest>=6.2; extra == "dev"
|
|
22
|
+
|
|
23
|
+
# loop-api-sdk
|
|
24
|
+
|
|
25
|
+
Cliente Python para a API de sincronização do Loop.
|
|
26
|
+
|
|
27
|
+
## Instalação
|
|
28
|
+
|
|
29
|
+
No `requirements.txt` do integrador:
|
|
30
|
+
|
|
31
|
+
```
|
|
32
|
+
loop-api-sdk @ git+ssh://git@bitbucket.org/<workspace>/loop-api-sdk.git@v0.1.0
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Uso
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
import logging
|
|
39
|
+
from loop_api_sdk import LoopAPI
|
|
40
|
+
|
|
41
|
+
logging.basicConfig(level=logging.INFO)
|
|
42
|
+
|
|
43
|
+
api = LoopAPI.from_env() # lê LOOP_TOKEN e, opcionalmente, LOOP_BASE_URL
|
|
44
|
+
|
|
45
|
+
result = api.send_orders(orders)
|
|
46
|
+
if not result:
|
|
47
|
+
print(f"Falhou no lote {result.failed_batch}: {result.error}")
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Para lançar exceção em vez de checar o retorno: `LoopAPI(..., raise_on_error=True)`
|
|
51
|
+
ou `api.send_orders(orders).raise_for_error()`.
|
|
52
|
+
|
|
53
|
+
Endpoint ainda sem método próprio: `api.send("novo-endpoint", body, params={...})`.
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# loop-api-sdk
|
|
2
|
+
|
|
3
|
+
Cliente Python para a API de sincronização do Loop.
|
|
4
|
+
|
|
5
|
+
## Instalação
|
|
6
|
+
|
|
7
|
+
No `requirements.txt` do integrador:
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
loop-api-sdk @ git+ssh://git@bitbucket.org/<workspace>/loop-api-sdk.git@v0.1.0
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Uso
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
import logging
|
|
17
|
+
from loop_api_sdk import LoopAPI
|
|
18
|
+
|
|
19
|
+
logging.basicConfig(level=logging.INFO)
|
|
20
|
+
|
|
21
|
+
api = LoopAPI.from_env() # lê LOOP_TOKEN e, opcionalmente, LOOP_BASE_URL
|
|
22
|
+
|
|
23
|
+
result = api.send_orders(orders)
|
|
24
|
+
if not result:
|
|
25
|
+
print(f"Falhou no lote {result.failed_batch}: {result.error}")
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Para lançar exceção em vez de checar o retorno: `LoopAPI(..., raise_on_error=True)`
|
|
29
|
+
ou `api.send_orders(orders).raise_for_error()`.
|
|
30
|
+
|
|
31
|
+
Endpoint ainda sem método próprio: `api.send("novo-endpoint", body, params={...})`.
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
[metadata]
|
|
2
|
+
name = loop-api-sdk
|
|
3
|
+
version = 0.1.0
|
|
4
|
+
description = Cliente Python para a API de sincronização do Loop
|
|
5
|
+
long_description = file: README.md
|
|
6
|
+
long_description_content_type = text/markdown
|
|
7
|
+
classifiers =
|
|
8
|
+
Programming Language :: Python :: 3
|
|
9
|
+
Programming Language :: Python :: 3.6
|
|
10
|
+
Programming Language :: Python :: 3.7
|
|
11
|
+
Programming Language :: Python :: 3.8
|
|
12
|
+
Programming Language :: Python :: 3.9
|
|
13
|
+
Programming Language :: Python :: 3.10
|
|
14
|
+
Programming Language :: Python :: 3.11
|
|
15
|
+
Programming Language :: Python :: 3.12
|
|
16
|
+
Programming Language :: Python :: 3.13
|
|
17
|
+
Programming Language :: Python :: 3.14
|
|
18
|
+
|
|
19
|
+
[options]
|
|
20
|
+
package_dir =
|
|
21
|
+
= src
|
|
22
|
+
packages = find:
|
|
23
|
+
python_requires = >=3.6
|
|
24
|
+
install_requires =
|
|
25
|
+
requests>=2.25
|
|
26
|
+
dataclasses; python_version < "3.7"
|
|
27
|
+
importlib-metadata; python_version < "3.8"
|
|
28
|
+
|
|
29
|
+
[options.packages.find]
|
|
30
|
+
where = src
|
|
31
|
+
|
|
32
|
+
[options.extras_require]
|
|
33
|
+
dev =
|
|
34
|
+
pytest>=6.2
|
|
35
|
+
|
|
36
|
+
[egg_info]
|
|
37
|
+
tag_build =
|
|
38
|
+
tag_date = 0
|
|
39
|
+
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from .client import DEFAULT_BASE_URL, LoopAPI, SyncResult
|
|
2
|
+
from .exceptions import LoopAPIError, LoopSyncError
|
|
3
|
+
|
|
4
|
+
__all__ = [
|
|
5
|
+
"LoopAPI",
|
|
6
|
+
"SyncResult",
|
|
7
|
+
"LoopAPIError",
|
|
8
|
+
"LoopSyncError",
|
|
9
|
+
"DEFAULT_BASE_URL",
|
|
10
|
+
]
|
|
11
|
+
|
|
12
|
+
# A versão vem do setup.cfg (lida dos metadados do pacote instalado).
|
|
13
|
+
try:
|
|
14
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
15
|
+
except ImportError: # Python < 3.8
|
|
16
|
+
from importlib_metadata import PackageNotFoundError, version
|
|
17
|
+
|
|
18
|
+
try:
|
|
19
|
+
__version__ = version("loop-api-sdk") # mesmo valor do "name" no setup.cfg
|
|
20
|
+
except PackageNotFoundError: # código rodando sem ter sido instalado com pip
|
|
21
|
+
__version__ = "0.0.0+unknown"
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from typing import Any, Dict, Iterator, List, Optional
|
|
5
|
+
|
|
6
|
+
import requests
|
|
7
|
+
|
|
8
|
+
from .exceptions import LoopAPIError, LoopSyncError
|
|
9
|
+
|
|
10
|
+
logger = logging.getLogger("loop_api_sdk")
|
|
11
|
+
|
|
12
|
+
DEFAULT_BASE_URL = "https://integration.readymix.io/api/sync"
|
|
13
|
+
|
|
14
|
+
# "get", "post", "put" ou "delete" (typing.Literal só existe a partir do 3.8)
|
|
15
|
+
HttpMethod = str
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class SyncResult:
|
|
20
|
+
"""Resultado de um envio em lotes.
|
|
21
|
+
|
|
22
|
+
Avalia como True/False em `if`, então `if api.send_orders(...):` continua funcionando.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
endpoint: str
|
|
26
|
+
total_items: int
|
|
27
|
+
total_batches: int
|
|
28
|
+
responses: List[Dict[str, Any]] = field(default_factory=list)
|
|
29
|
+
sent_items: int = 0
|
|
30
|
+
failed_batch: Optional[int] = None # número do lote que falhou (começa em 1)
|
|
31
|
+
error: Optional[LoopAPIError] = None
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def success(self) -> bool:
|
|
35
|
+
return self.error is None
|
|
36
|
+
|
|
37
|
+
def __bool__(self) -> bool:
|
|
38
|
+
return self.success
|
|
39
|
+
|
|
40
|
+
def raise_for_error(self) -> "SyncResult":
|
|
41
|
+
if self.error is not None:
|
|
42
|
+
raise LoopSyncError(self) from self.error
|
|
43
|
+
return self
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class LoopAPI:
|
|
47
|
+
"""Cliente da API de sincronização do Loop."""
|
|
48
|
+
|
|
49
|
+
def __init__(
|
|
50
|
+
self,
|
|
51
|
+
token: str,
|
|
52
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
53
|
+
batch_max_size: int = 50,
|
|
54
|
+
timeout: float = 120,
|
|
55
|
+
raise_on_error: bool = False,
|
|
56
|
+
session: Optional[requests.Session] = None,
|
|
57
|
+
):
|
|
58
|
+
if not token:
|
|
59
|
+
raise ValueError("token é obrigatório")
|
|
60
|
+
if batch_max_size < 1:
|
|
61
|
+
raise ValueError("batch_max_size deve ser >= 1")
|
|
62
|
+
|
|
63
|
+
self.base_url = base_url.rstrip("/")
|
|
64
|
+
self.batch_max_size = batch_max_size
|
|
65
|
+
self.timeout = timeout
|
|
66
|
+
self.raise_on_error = raise_on_error
|
|
67
|
+
|
|
68
|
+
self.session = session or requests.Session()
|
|
69
|
+
self.session.headers.update({
|
|
70
|
+
"token": token,
|
|
71
|
+
"Content-Type": "application/json",
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
@classmethod
|
|
75
|
+
def from_env(cls, prefix: str = "LOOP_", **kwargs) -> "LoopAPI":
|
|
76
|
+
"""Cria o cliente a partir de LOOP_TOKEN e (opcional) LOOP_BASE_URL."""
|
|
77
|
+
token = os.environ.get(f"{prefix}TOKEN")
|
|
78
|
+
if not token:
|
|
79
|
+
raise ValueError(f"Variável de ambiente {prefix}TOKEN não definida")
|
|
80
|
+
base_url = os.environ.get(f"{prefix}BASE_URL")
|
|
81
|
+
if base_url:
|
|
82
|
+
kwargs.setdefault("base_url", base_url)
|
|
83
|
+
return cls(token=token, **kwargs)
|
|
84
|
+
|
|
85
|
+
# ---------- context manager ----------
|
|
86
|
+
|
|
87
|
+
def close(self) -> None:
|
|
88
|
+
self.session.close()
|
|
89
|
+
|
|
90
|
+
def __enter__(self) -> "LoopAPI":
|
|
91
|
+
return self
|
|
92
|
+
|
|
93
|
+
def __exit__(self, *exc) -> None:
|
|
94
|
+
self.close()
|
|
95
|
+
|
|
96
|
+
# ---------- endpoints ----------
|
|
97
|
+
|
|
98
|
+
def send_deliveries(self, body: list) -> SyncResult:
|
|
99
|
+
return self.send("tickets", body)
|
|
100
|
+
|
|
101
|
+
def send_projects(self, body: list, create_even_if_inactive: bool = True) -> SyncResult:
|
|
102
|
+
return self.send("projects", body, params={"create_even_if_inactive": create_even_if_inactive})
|
|
103
|
+
|
|
104
|
+
def send_customers(self, body: list) -> SyncResult:
|
|
105
|
+
return self.send("customers", body)
|
|
106
|
+
|
|
107
|
+
def send_products(self, body: list) -> SyncResult:
|
|
108
|
+
return self.send("products", body)
|
|
109
|
+
|
|
110
|
+
def send_orders(self, body: list, create_plans: bool = True, update_plans: bool = True) -> SyncResult:
|
|
111
|
+
return self.send("orders", body, params={"create_plans": create_plans, "update_plans": update_plans})
|
|
112
|
+
|
|
113
|
+
def send_purchase_orders(self, body: list, update_after_start: Optional[bool] = None) -> SyncResult:
|
|
114
|
+
params = {}
|
|
115
|
+
if update_after_start is not None:
|
|
116
|
+
params["update_after_start"] = update_after_start
|
|
117
|
+
return self.send("po", body, params=params or None)
|
|
118
|
+
|
|
119
|
+
def send_invoices(self, body: list) -> SyncResult:
|
|
120
|
+
return self.send("invoices", body)
|
|
121
|
+
|
|
122
|
+
# ---------- genérico ----------
|
|
123
|
+
|
|
124
|
+
def send(self, endpoint: str, body: list, params: Optional[dict] = None) -> SyncResult:
|
|
125
|
+
"""Envia `body` em lotes via POST para {base_url}/{endpoint}.
|
|
126
|
+
|
|
127
|
+
Para no primeiro lote que falhar; os lotes anteriores já foram aceitos pela API.
|
|
128
|
+
"""
|
|
129
|
+
batches = list(_chunks(body, self.batch_max_size))
|
|
130
|
+
result = SyncResult(endpoint=endpoint, total_items=len(body), total_batches=len(batches))
|
|
131
|
+
|
|
132
|
+
for i, batch in enumerate(batches, start=1):
|
|
133
|
+
logger.info("Enviando %s: lote %d/%d (%d itens)", endpoint, i, len(batches), len(batch))
|
|
134
|
+
try:
|
|
135
|
+
data = self.request("post", endpoint, body=batch, params=params)
|
|
136
|
+
except LoopAPIError as e:
|
|
137
|
+
logger.error("Falha em %s no lote %d/%d: %s", endpoint, i, len(batches), e)
|
|
138
|
+
result.error = e
|
|
139
|
+
result.failed_batch = i
|
|
140
|
+
break
|
|
141
|
+
result.responses.append(data)
|
|
142
|
+
result.sent_items += len(batch)
|
|
143
|
+
|
|
144
|
+
if self.raise_on_error:
|
|
145
|
+
result.raise_for_error()
|
|
146
|
+
return result
|
|
147
|
+
|
|
148
|
+
def request(
|
|
149
|
+
self,
|
|
150
|
+
method: HttpMethod,
|
|
151
|
+
endpoint: str,
|
|
152
|
+
body: Any = None,
|
|
153
|
+
params: Optional[dict] = None,
|
|
154
|
+
) -> Dict[str, Any]:
|
|
155
|
+
"""Faz uma requisição única. Retorna o JSON ou lança LoopAPIError."""
|
|
156
|
+
url = f"{self.base_url}/{endpoint.lstrip('/')}"
|
|
157
|
+
|
|
158
|
+
try:
|
|
159
|
+
resp = self.session.request(
|
|
160
|
+
method.upper(), url, json=body, params=params, timeout=self.timeout
|
|
161
|
+
)
|
|
162
|
+
except requests.RequestException as e:
|
|
163
|
+
raise LoopAPIError(f"Erro de conexão com {url}: {e}") from e
|
|
164
|
+
|
|
165
|
+
try:
|
|
166
|
+
data = resp.json()
|
|
167
|
+
except ValueError:
|
|
168
|
+
raise LoopAPIError(
|
|
169
|
+
"Resposta não é JSON", status_code=resp.status_code, payload=resp.text[:2000]
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
logger.debug("%s %s -> HTTP %s: %s", method.upper(), url, resp.status_code, data)
|
|
173
|
+
|
|
174
|
+
if not isinstance(data, dict) or data.get("success") is not True:
|
|
175
|
+
raise LoopAPIError("API retornou success != true", status_code=resp.status_code, payload=data)
|
|
176
|
+
|
|
177
|
+
return data
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _chunks(items: list, size: int) -> Iterator[list]:
|
|
181
|
+
for i in range(0, len(items), size):
|
|
182
|
+
yield items[i:i + size]
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
from typing import Any, Optional
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class LoopAPIError(Exception):
|
|
5
|
+
"""Falha numa requisição à API do Loop (conexão, resposta inválida ou success=False)."""
|
|
6
|
+
|
|
7
|
+
def __init__(self, message: str, status_code: Optional[int] = None, payload: Any = None):
|
|
8
|
+
super().__init__(message)
|
|
9
|
+
self.status_code = status_code
|
|
10
|
+
self.payload = payload
|
|
11
|
+
|
|
12
|
+
def __str__(self) -> str:
|
|
13
|
+
base = super().__str__()
|
|
14
|
+
if self.status_code is not None:
|
|
15
|
+
base = f"[HTTP {self.status_code}] {base}"
|
|
16
|
+
if self.payload is not None:
|
|
17
|
+
base = f"{base} | resposta: {self.payload}"
|
|
18
|
+
return base
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class LoopSyncError(Exception):
|
|
22
|
+
"""Lançada por SyncResult.raise_for_error() ou quando raise_on_error=True."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, result):
|
|
25
|
+
self.result = result
|
|
26
|
+
super().__init__(
|
|
27
|
+
f"Falha ao enviar para '{result.endpoint}': lote {result.failed_batch} "
|
|
28
|
+
f"de {result.total_batches} falhou ({result.sent_items}/{result.total_items} "
|
|
29
|
+
f"itens já enviados). Erro: {result.error}"
|
|
30
|
+
)
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: loop-api-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Cliente Python para a API de sincronização do Loop
|
|
5
|
+
Classifier: Programming Language :: Python :: 3
|
|
6
|
+
Classifier: Programming Language :: Python :: 3.6
|
|
7
|
+
Classifier: Programming Language :: Python :: 3.7
|
|
8
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
15
|
+
Requires-Python: >=3.6
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
Requires-Dist: requests>=2.25
|
|
18
|
+
Requires-Dist: dataclasses; python_version < "3.7"
|
|
19
|
+
Requires-Dist: importlib-metadata; python_version < "3.8"
|
|
20
|
+
Provides-Extra: dev
|
|
21
|
+
Requires-Dist: pytest>=6.2; extra == "dev"
|
|
22
|
+
|
|
23
|
+
# loop-api-sdk
|
|
24
|
+
|
|
25
|
+
Cliente Python para a API de sincronização do Loop.
|
|
26
|
+
|
|
27
|
+
## Instalação
|
|
28
|
+
|
|
29
|
+
No `requirements.txt` do integrador:
|
|
30
|
+
|
|
31
|
+
```
|
|
32
|
+
loop-api-sdk @ git+ssh://git@bitbucket.org/<workspace>/loop-api-sdk.git@v0.1.0
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Uso
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
import logging
|
|
39
|
+
from loop_api_sdk import LoopAPI
|
|
40
|
+
|
|
41
|
+
logging.basicConfig(level=logging.INFO)
|
|
42
|
+
|
|
43
|
+
api = LoopAPI.from_env() # lê LOOP_TOKEN e, opcionalmente, LOOP_BASE_URL
|
|
44
|
+
|
|
45
|
+
result = api.send_orders(orders)
|
|
46
|
+
if not result:
|
|
47
|
+
print(f"Falhou no lote {result.failed_batch}: {result.error}")
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Para lançar exceção em vez de checar o retorno: `LoopAPI(..., raise_on_error=True)`
|
|
51
|
+
ou `api.send_orders(orders).raise_for_error()`.
|
|
52
|
+
|
|
53
|
+
Endpoint ainda sem método próprio: `api.send("novo-endpoint", body, params={...})`.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
setup.cfg
|
|
4
|
+
setup.py
|
|
5
|
+
src/loop_api_sdk/__init__.py
|
|
6
|
+
src/loop_api_sdk/client.py
|
|
7
|
+
src/loop_api_sdk/exceptions.py
|
|
8
|
+
src/loop_api_sdk.egg-info/PKG-INFO
|
|
9
|
+
src/loop_api_sdk.egg-info/SOURCES.txt
|
|
10
|
+
src/loop_api_sdk.egg-info/dependency_links.txt
|
|
11
|
+
src/loop_api_sdk.egg-info/requires.txt
|
|
12
|
+
src/loop_api_sdk.egg-info/top_level.txt
|
|
13
|
+
tests/test_client.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
loop_api_sdk
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
from unittest.mock import MagicMock
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
import requests
|
|
5
|
+
|
|
6
|
+
from src.loop_api_sdk import LoopAPI, LoopAPIError, LoopSyncError
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def make_response(json_data, status=200):
|
|
10
|
+
resp = MagicMock()
|
|
11
|
+
resp.status_code = status
|
|
12
|
+
resp.json.return_value = json_data
|
|
13
|
+
return resp
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def make_api(responses, **kwargs):
|
|
17
|
+
session = requests.Session()
|
|
18
|
+
session.request = MagicMock(side_effect=responses)
|
|
19
|
+
return LoopAPI(token="t", session=session, **kwargs), session.request
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def test_envia_em_lotes():
|
|
23
|
+
api, req = make_api([make_response({"success": True})] * 3, batch_max_size=2)
|
|
24
|
+
result = api.send_customers([1, 2, 3, 4, 5])
|
|
25
|
+
assert result and result.sent_items == 5 and result.total_batches == 3
|
|
26
|
+
assert req.call_count == 3
|
|
27
|
+
assert req.call_args_list[0][1]["json"] == [1, 2]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def test_para_no_primeiro_lote_com_falha():
|
|
31
|
+
api, req = make_api(
|
|
32
|
+
[make_response({"success": True}), make_response({"success": False, "msg": "x"}, 400)],
|
|
33
|
+
batch_max_size=2,
|
|
34
|
+
)
|
|
35
|
+
result = api.send_orders([1, 2, 3, 4, 5])
|
|
36
|
+
assert not result
|
|
37
|
+
assert result.failed_batch == 2 and result.sent_items == 2
|
|
38
|
+
assert req.call_count == 2
|
|
39
|
+
assert result.error.status_code == 400
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def test_params_padrao_de_orders():
|
|
43
|
+
api, req = make_api([make_response({"success": True})])
|
|
44
|
+
api.send_orders([1])
|
|
45
|
+
assert req.call_args[1]["params"] == {"create_plans": True, "update_plans": True}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def test_erro_de_conexao_vira_loop_api_error():
|
|
49
|
+
api, _ = make_api([requests.ConnectionError("down")])
|
|
50
|
+
result = api.send_products([1])
|
|
51
|
+
assert not result and isinstance(result.error, LoopAPIError)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def test_raise_on_error():
|
|
55
|
+
api, _ = make_api([make_response({"success": False})], raise_on_error=True)
|
|
56
|
+
with pytest.raises(LoopSyncError):
|
|
57
|
+
api.send_invoices([1])
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_header_token():
|
|
61
|
+
api, _ = make_api([])
|
|
62
|
+
assert api.session.headers["token"] == "t"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def test_versao_vem_do_setup_cfg():
|
|
66
|
+
import configparser
|
|
67
|
+
from pathlib import Path
|
|
68
|
+
|
|
69
|
+
import src.loop_api_sdk
|
|
70
|
+
|
|
71
|
+
cfg = configparser.ConfigParser()
|
|
72
|
+
cfg.read(Path(__file__).parent.parent / "setup.cfg")
|
|
73
|
+
assert src.loop_api_sdk.__version__ == cfg["metadata"]["version"]
|