Skip to content

Commit 4922d50

Browse files
Fix typecheking and simplify call(raw=True) (#183)
1 parent 036a45a commit 4922d50

File tree

6 files changed

+182
-19
lines changed

6 files changed

+182
-19
lines changed

README.md

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,12 +128,22 @@ b.call('crm.deal.update', tasks)
128128
### call(raw=True)
129129
Вызов `call` с парамтером `raw=True` отправляет на сервер переданные ему параметры в оригинальном, необработанном виде (пропуская упаковку в батчи), и возвращает ответ сервера без какой-либо обработки.
130130

131-
Подобный вызов можно использовать в отладочных целях, но кроме того, придется его использовать для отправки запросов, в параметрах которых есть `None` (None применяется для стирания значения полей, а упаковка в батчи мешает передавать `None`).
131+
Подобный вызов можно использовать в отладочных целях, но кроме того, придется его использовать для отправки запросов, которые:
132+
- в параметрах имеют `None` (None применяется для стирания значения полей, а упаковка в батчи мешает передавать `None`),
133+
- используют устревшие методы Битрикс24, которые принимают на вход список (см. [#157](https://github.com/leshchenko1979/fast_bitrix24/issues/157)).
134+
132135

133136
```python
134137
# стереть DESCRIPTION в лиде 123
135138
params = {"ID": 123, "fields": {"DESCRIPTION": None}}
136139
b.call('crm.lead.update', params, raw=True)
140+
141+
# добавить комментарий к задаче
142+
b.call(
143+
'task.commentitem.add',
144+
[123, {"POST_MESSAGE": "Комментарий к задаче"}],
145+
raw=True
146+
)
137147
```
138148

139149
### `call_batch()`

fast_bitrix24/server_response.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def extract_results(self) -> Union[Dict, List[Dict]]:
5555
return self.extract_from_single_response(self.result)
5656

5757
def is_batch(self) -> bool:
58-
return "result" in self.response and "result" in self.response["result"]
58+
return isinstance(self.result, dict) and "result" in self.result
5959

6060
@staticmethod
6161
def extract_from_single_response(result: dict):

fast_bitrix24/user_request.py

Lines changed: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,7 @@ def prepare_item_list(self):
260260
]
261261

262262

263-
class RawCallUserRequest(UserRequestAbstract):
263+
class RawCallUserRequest():
264264
"""Отправляем на сервер один элемент, не обрабатывая его и не заворачивая в батчи.
265265
266266
Нужно для устревших методов, которые принимают на вход список
@@ -271,22 +271,13 @@ class RawCallUserRequest(UserRequestAbstract):
271271
"""
272272

273273
@beartype
274-
def __init__(self, bitrix, method: str, item: Union[Dict, None]):
275-
super().__init__(bitrix, method, item)
276-
277-
def standardized_params(self, p):
278-
"""Пропускаем все проверки и изменения параметров."""
279-
return p
280-
281-
def standardized_method(self, method: str):
282-
"""Пропускаем все проверки и изменения методов."""
283-
return method
284-
285-
def check_special_limitations(self):
286-
return True
274+
def __init__(self, bitrix, method: str, item):
275+
self.srh = bitrix.srh
276+
self.method = method
277+
self.item = item
287278

288279
async def run(self):
289-
return await self.srh.single_request(self.method, self.params)
280+
return await self.srh.single_request(self.method, self.item)
290281

291282

292283
class ListAndGetUserRequest:

tests/real_responses/single_add.py

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
response = {
2+
"result": {
3+
"task": {
4+
"id": "456",
5+
"title": "Алм",
6+
"description": "Курс на социально-ориентированный национальный проект станет частью наших традиций",
7+
"descriptionInBbcode": "Y",
8+
"declineReason": None,
9+
"priority": "1",
10+
"status": "2",
11+
"notViewed": "N",
12+
"statusComplete": "1",
13+
"multitask": "N",
14+
"stageId": "0",
15+
"responsibleId": "1",
16+
"responsibleName": "Korvin",
17+
"responsibleLastName": "-Control",
18+
"responsibleSecondName": None,
19+
"responsibleLogin": "admin",
20+
"responsibleWorkPosition": None,
21+
"responsiblePhoto": None,
22+
"dateStart": None,
23+
"durationFact": None,
24+
"timeEstimate": "0",
25+
"timeSpentInLogs": None,
26+
"replicate": "N",
27+
"deadline": "2022-05-09T01:00:00+04:00",
28+
"deadlineOrig": "2022-05-09 00:00:00",
29+
"startDatePlan": None,
30+
"endDatePlan": None,
31+
"createdBy": "1",
32+
"createdByName": "Korvin",
33+
"createdByLastName": "-Control",
34+
"createdBySecondName": None,
35+
"createdByLogin": "admin",
36+
"createdByWorkPosition": None,
37+
"createdByPhoto": None,
38+
"createdDate": "2022-06-08T21:54:00+04:00",
39+
"changedBy": "1",
40+
"changedDate": "2022-06-08T21:54:00+04:00",
41+
"statusChangedBy": "1",
42+
"statusChangedDate": "2022-06-08T21:54:00+04:00",
43+
"closedBy": None,
44+
"closedDate": None,
45+
"activityDate": "2022-06-08T21:54:00+04:00",
46+
"guid": "{bbe24f38-df7f-42d4-b172-9ebf432559ed}",
47+
"xmlId": None,
48+
"mark": None,
49+
"allowChangeDeadline": "N",
50+
"allowTimeTracking": "N",
51+
"matchWorkTime": "N",
52+
"taskControl": "N",
53+
"addInReport": "N",
54+
"groupId": "0",
55+
"forumTopicId": None,
56+
"parentId": None,
57+
"commentsCount": None,
58+
"serviceCommentsCount": None,
59+
"forumId": None,
60+
"siteId": "s1",
61+
"subordinate": "N",
62+
"exchangeModified": None,
63+
"exchangeId": None,
64+
"outlookVersion": "1",
65+
"viewedDate": None,
66+
"deadlineCounted": "0",
67+
"forkedByTemplateId": None,
68+
"favorite": "N",
69+
"sorting": None,
70+
"durationPlanSeconds": None,
71+
"durationTypeAll": "days",
72+
"durationPlan": None,
73+
"durationType": "days",
74+
"isMuted": "N",
75+
"isPinned": "N",
76+
"isPinnedInGroup": "N",
77+
"ufCrmTask": False,
78+
"ufTaskWebdavFiles": False,
79+
"ufMailMessage": None,
80+
"auditors": [],
81+
"accomplices": [],
82+
"tags": ["скпэ22-2"],
83+
"checklist": [],
84+
"files": [],
85+
"dependsOn": [],
86+
"group": [],
87+
"creator": {
88+
"id": "1",
89+
"name": "Korvin -Control",
90+
"link": "/company/personal/user/1/",
91+
"icon": "/bitrix/images/tasks/default_avatar.png",
92+
},
93+
"responsible": {
94+
"id": "1",
95+
"name": "Korvin -Control",
96+
"link": "/company/personal/user/1/",
97+
"icon": "/bitrix/images/tasks/default_avatar.png",
98+
},
99+
"newCommentsCount": 0,
100+
"action": {
101+
"accept": False,
102+
"decline": False,
103+
"complete": True,
104+
"approve": False,
105+
"disapprove": False,
106+
"start": True,
107+
"pause": False,
108+
"delegate": True,
109+
"remove": True,
110+
"edit": True,
111+
"defer": True,
112+
"renew": False,
113+
"create": True,
114+
"changeDeadline": True,
115+
"checklistAddItems": True,
116+
"addFavorite": True,
117+
"deleteFavorite": False,
118+
"rate": True,
119+
"edit.originator": False,
120+
"checklist.reorder": True,
121+
"elapsedtime.add": True,
122+
"dayplan.timer.toggle": False,
123+
"edit.plan": True,
124+
"checklist.add": True,
125+
"favorite.add": True,
126+
"favorite.delete": False,
127+
},
128+
}
129+
},
130+
"time": {
131+
"start": 1654710840.774196,
132+
"finish": 1654710840.852366,
133+
"duration": 0.0781700611114502,
134+
"processing": 0.06392693519592285,
135+
"date_start": "2022-06-08T20:54:00+03:00",
136+
"date_finish": "2022-06-08T20:54:00+03:00",
137+
},
138+
}

tests/test_server_responses.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,3 +140,22 @@ def test_stagehistory(bx_dummy, recwarn):
140140
print(w.message for w in recwarn.list)
141141
with pytest.raises(Exception):
142142
recwarn.pop(RuntimeWarning)
143+
144+
145+
def test_single_add(bx_dummy):
146+
from tests.real_responses.single_add import response
147+
148+
bx_dummy.srh = MockSRH(response)
149+
results = bx_dummy.call(
150+
"tasks.task.add",
151+
{
152+
"fields": {
153+
"TITLE": "АГ",
154+
"DESCRIPTION": "Сложно сказать, почему потускнели светлые лики икон",
155+
"RESPONSIBLE_ID": 1,
156+
"TAGS": "скпэ22-4",
157+
"DEADLINE": "2022/07/30",
158+
}
159+
},
160+
)
161+
assert isinstance(results, dict)

tests/test_sync.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import pytest
44

5+
56
@pytest.mark.skipif(
67
not os.getenv("FAST_BITRIX24_TEST_WEBHOOK"),
78
reason="Нет аккаунта, на котором можно проверить",
@@ -137,7 +138,9 @@ def test_issue_132(self, create_100_tasks):
137138
def test_case(self, get_test):
138139
b = get_test
139140

140-
with pytest.raises(RuntimeError, match="Could not find value for parameter"):
141+
with pytest.raises(
142+
RuntimeError, match="Could not find value for parameter"
143+
):
141144
b.call("disk.file.get", [{"ID": 1}])
142145

143146
with pytest.raises(RuntimeError, match="Could not find entity with id"):
@@ -150,7 +153,6 @@ def test_long_task_description(self, get_test):
150153
)
151154
b.get_by_ID("crm.lead.delete", [lead_no])
152155

153-
154156
class TestParamsEncoding:
155157
def test_mobile_phone(self, get_test):
156158
b = get_test
@@ -204,6 +206,7 @@ def test_product_rows(self, create_a_lead):
204206

205207
assert len(product_rows) == len(result_rows)
206208

209+
207210
class TestErrors:
208211
def test_get_all(self, bx_dummy):
209212
b = bx_dummy
@@ -242,3 +245,5 @@ async def stub(*args, **kwargs):
242245

243246
with pytest.raises(Exception):
244247
b.call("_", {})
248+
249+
b.call("_", [1, {"a": 2}], raw=True)

0 commit comments

Comments
 (0)