database-mongodb-local 0.0.2__tar.gz → 0.0.6__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.
Files changed (29) hide show
  1. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/PKG-INFO +1 -1
  2. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/database_mongodb_local/__init__.py +2 -1
  3. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/database_mongodb_local/src/connector.py +4 -10
  4. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/database_mongodb_local/src/constants_src.py +11 -6
  5. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/database_mongodb_local/src/decorators.py +2 -1
  6. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/database_mongodb_local/src/generic_crud.py +42 -13
  7. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/database_mongodb_local/src/generic_crud_ml.py +31 -13
  8. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/database_mongodb_local/src/generic_mapping.py +36 -20
  9. database_mongodb_local-0.0.6/database_mongodb_local/src/version.py +10 -0
  10. database_mongodb_local-0.0.6/database_mongodb_local/tests/connector_test.py +103 -0
  11. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/database_mongodb_local/tests/generic_crud_ml_system_test.py +2 -1
  12. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/database_mongodb_local/tests/generic_crud_ml_test.py +90 -53
  13. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/database_mongodb_local/tests/generic_crud_test.py +37 -10
  14. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/database_mongodb_local/tests/generic_mapping_system_test.py +10 -5
  15. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/database_mongodb_local/tests/generic_mapping_test.py +15 -9
  16. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/database_mongodb_local.egg-info/PKG-INFO +1 -1
  17. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/database_mongodb_local.egg-info/SOURCES.txt +1 -0
  18. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/pyproject.toml +1 -2
  19. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/setup.py +7 -1
  20. database_mongodb_local-0.0.2/database_mongodb_local/src/version.py +0 -5
  21. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/README.md +0 -0
  22. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/database_mongodb_local/src/__init__.py +0 -0
  23. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/database_mongodb_local/src/exceptions.py +0 -0
  24. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/database_mongodb_local/tests/__init__.py +0 -0
  25. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/database_mongodb_local/tests/generic_crud_system_test.py +0 -0
  26. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/database_mongodb_local.egg-info/dependency_links.txt +0 -0
  27. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/database_mongodb_local.egg-info/requires.txt +0 -0
  28. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/database_mongodb_local.egg-info/top_level.txt +0 -0
  29. {database_mongodb_local-0.0.2 → database_mongodb_local-0.0.6}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: database-mongodb-local
3
- Version: 0.0.2
3
+ Version: 0.0.6
4
4
  Summary: PyPI database-mongodb-local Python Package owned by Circlez.ai
5
5
  Home-page: https://github.com/circles-zone/database-mongodb-local-python-package
6
6
  Author: Circles
@@ -2,4 +2,5 @@ from .src.generic_crud import GenericCrudMongodb
2
2
  from .src.generic_crud_ml import GenericCrudMlMongoDB
3
3
  from .src.generic_mapping import GenericMappingMongodb
4
4
 
5
- __all__ = ["GenericCrudMongodb", "GenericCrudMlMongoDB", "GenericMappingMongodb"]
5
+ __all__ = ["GenericCrudMongodb",
6
+ "GenericCrudMlMongoDB", "GenericMappingMongodb"]
@@ -11,10 +11,6 @@ DEFAULT_HOST = "localhost"
11
11
  DEFAULT_PORT = 27017
12
12
 
13
13
 
14
- def _is_mock() -> bool:
15
- return os.getenv("MONGODB_MOCK", "false").lower() in ("1", "true", "yes")
16
-
17
-
18
14
  @lru_cache(maxsize=None)
19
15
  def _get_real_client() -> MongoClient:
20
16
  host = os.getenv("MONGODB_HOST", DEFAULT_HOST)
@@ -23,7 +19,8 @@ def _get_real_client() -> MongoClient:
23
19
  password = os.getenv("MONGODB_PASSWORD")
24
20
 
25
21
  if username and password:
26
- return MongoClient(host=host, port=port, username=username, password=password)
22
+ return MongoClient(
23
+ host=host, port=port, username=username, password=password)
27
24
  return MongoClient(host=host, port=port)
28
25
 
29
26
 
@@ -31,15 +28,12 @@ class Connector:
31
28
  """Single owner of MongoDB connection creation (information hiding).
32
29
 
33
30
  Callers never build a client themselves — they ask Connector for a
34
- database. When ``MONGODB_MOCK`` is set, a fresh in-memory mongomock
35
- database is returned so tests run without a real MongoDB.
31
+ database. Tests substitute an in-memory database by patching
32
+ ``get_database`` directly (see the mock_mongo fixture in conftest.py).
36
33
  """
37
34
 
38
35
  @staticmethod
39
36
  def get_database(database_name: str) -> Database:
40
- if _is_mock():
41
- import mongomock
42
- return mongomock.MongoClient()[database_name]
43
37
  return _get_real_client()[database_name]
44
38
 
45
39
  @staticmethod
@@ -2,22 +2,27 @@ from logger_local.LoggerComponentEnum import LoggerComponentEnum
2
2
 
3
3
  DEVELOPER_EMAIL_ADDRESS = "dor3382@gmail.com"
4
4
 
5
- CRUD_MONGODB_CODE_LOGGER_OBJECT = {
6
- "component_id": 1,
5
+ # TODO Use Sql2Code to get real component IDs from the database
6
+ GENERIC_CRUD_MONGODB_COMPONENT_ID = 1
7
+ GENERIC_CRUD_ML_MONGODB_COMPONENT_ID = 2
8
+ GENERIC_MAPPING_MONGODB_COMPONENT_ID = 3
9
+
10
+ GENERIC_CRUD_MONGODB_CODE_LOGGER_INIT_OBJECT = {
11
+ "component_id": GENERIC_CRUD_MONGODB_COMPONENT_ID,
7
12
  "component_name": "database-mongodb-local/GenericCrudMongodb",
8
13
  "component_category": LoggerComponentEnum.ComponentCategory.Code.value,
9
14
  "developer_email_address": DEVELOPER_EMAIL_ADDRESS,
10
15
  }
11
16
 
12
- CRUD_ML_CODE_LOGGER_OBJECT = {
13
- "component_id": 2,
17
+ GENERIC_CRUD_ML_MONGODB_CODE_LOGGER_INIT_OBJECT = {
18
+ "component_id": GENERIC_CRUD_ML_MONGODB_COMPONENT_ID,
14
19
  "component_name": "database-mongodb-local/GenericCrudMlMongoDB",
15
20
  "component_category": LoggerComponentEnum.ComponentCategory.Code.value,
16
21
  "developer_email_address": DEVELOPER_EMAIL_ADDRESS,
17
22
  }
18
23
 
19
- MAPPING_CODE_LOGGER_OBJECT = {
20
- "component_id": 3,
24
+ GENERIC_MAPPING_MONGODB_CODE_LOGGER_INIT_OBJECT = {
25
+ "component_id": GENERIC_MAPPING_MONGODB_COMPONENT_ID,
21
26
  "component_name": "database-mongodb-local/GenericMappingMongodb",
22
27
  "component_category": LoggerComponentEnum.ComponentCategory.Code.value,
23
28
  "developer_email_address": DEVELOPER_EMAIL_ADDRESS,
@@ -7,7 +7,8 @@ from pymongo.errors import (
7
7
  ServerSelectionTimeoutError,
8
8
  )
9
9
 
10
- from .exceptions import DatabaseConnectionError, DatabaseDuplicateError, DatabaseOperationError
10
+ from .exceptions import (
11
+ DatabaseConnectionError, DatabaseDuplicateError, DatabaseOperationError)
11
12
 
12
13
 
13
14
  def handle_db_errors(func):
@@ -3,19 +3,20 @@ from typing import Any, Optional
3
3
 
4
4
  from bson import ObjectId
5
5
  from pymongo.collection import Collection
6
- from pymongo.errors import DuplicateKeyError
6
+ from pymongo.errors import BulkWriteError, DuplicateKeyError
7
7
 
8
8
  from logger_local.MetaLogger import ABCMetaLogger
9
9
 
10
- from database_infrastructure_local.generic_crud_abstract import GenericCrudAbstract
10
+ from database_infrastructure_local.generic_crud_abstract import (
11
+ GenericCrudAbstract)
11
12
 
12
13
  from .connector import Connector
13
- from .constants_src import CRUD_MONGODB_CODE_LOGGER_OBJECT
14
+ from .constants_src import GENERIC_CRUD_MONGODB_CODE_LOGGER_INIT_OBJECT
14
15
  from .decorators import handle_db_errors
15
16
 
16
17
 
17
18
  class GenericCrudMongodb(GenericCrudAbstract, metaclass=ABCMetaLogger,
18
- object=CRUD_MONGODB_CODE_LOGGER_OBJECT):
19
+ object=GENERIC_CRUD_MONGODB_CODE_LOGGER_INIT_OBJECT):
19
20
  """MongoDB implementation of the shared GenericCrud interface.
20
21
 
21
22
  To keep the interface consistent across MySQL, PostgreSQL and MongoDB,
@@ -47,6 +48,19 @@ class GenericCrudMongodb(GenericCrudAbstract, metaclass=ABCMetaLogger,
47
48
  f["end_timestamp"] = None
48
49
  return f
49
50
 
51
+ # ------------------------------------------------------------------ index
52
+
53
+ def ensure_index(self, *, table_name: str = None,
54
+ keys: list, unique: bool = False) -> None:
55
+ """Create an index on the collection if it doesn't already exist.
56
+
57
+ keys: list of (field, direction) tuples,
58
+ e.g. [("google_id", 1), ("user_id", 1)]
59
+ unique: if True, MongoDB rejects duplicate key combinations at insert.
60
+ """
61
+ table_name = table_name or self.default_table_name
62
+ self._collection(table_name).create_index(keys, unique=unique)
63
+
50
64
  # ------------------------------------------------------------------ insert
51
65
 
52
66
  @handle_db_errors
@@ -82,7 +96,8 @@ class GenericCrudMongodb(GenericCrudAbstract, metaclass=ABCMetaLogger,
82
96
  @handle_db_errors
83
97
  def insert_if_not_exists(self, *, table_name: str = None,
84
98
  data_dict: dict = None,
85
- data_dict_compare: dict = None) -> Optional[ObjectId]:
99
+ data_dict_compare: dict = None
100
+ ) -> Optional[ObjectId]:
86
101
  table_name = table_name or self.default_table_name
87
102
  data_dict_compare = data_dict_compare or data_dict
88
103
  existing = self._collection(table_name).find_one(
@@ -104,8 +119,12 @@ class GenericCrudMongodb(GenericCrudAbstract, metaclass=ABCMetaLogger,
104
119
  doc.setdefault("is_test_data", self.is_test_data)
105
120
  doc.setdefault("created_timestamp", now)
106
121
  doc.setdefault("updated_timestamp", now)
107
- result = self._collection(table_name).insert_many(docs)
108
- return len(result.inserted_ids)
122
+ try:
123
+ result = self._collection(
124
+ table_name).insert_many(docs, ordered=False)
125
+ return len(result.inserted_ids)
126
+ except BulkWriteError as e:
127
+ return e.details.get("nInserted", 0)
109
128
 
110
129
  # ------------------------------------------------------------------ upsert
111
130
 
@@ -153,7 +172,9 @@ class GenericCrudMongodb(GenericCrudAbstract, metaclass=ABCMetaLogger,
153
172
  def update_by_where(self, *, table_name: str = None,
154
173
  where: dict,
155
174
  data_dict: dict) -> int:
156
- """``where`` is a MongoDB filter dict (the MongoDB equivalent of a SQL WHERE clause)."""
175
+ """``where`` is a MongoDB filter dict
176
+ (the MongoDB equivalent of a SQL WHERE clause).
177
+ """
157
178
  table_name = table_name or self.default_table_name
158
179
  data_dict = dict(data_dict)
159
180
  data_dict["updated_timestamp"] = datetime.now(timezone.utc)
@@ -181,7 +202,9 @@ class GenericCrudMongodb(GenericCrudAbstract, metaclass=ABCMetaLogger,
181
202
  @handle_db_errors
182
203
  def delete_by_where(self, *, table_name: str = None,
183
204
  where: dict) -> int:
184
- """``where`` is a MongoDB filter dict (the MongoDB equivalent of a SQL WHERE clause)."""
205
+ """``where`` is a MongoDB filter dict
206
+ (the MongoDB equivalent of a SQL WHERE clause).
207
+ """
185
208
  table_name = table_name or self.default_table_name
186
209
  result = self._collection(table_name).update_many(
187
210
  self._live_filter(where),
@@ -211,7 +234,8 @@ class GenericCrudMongodb(GenericCrudAbstract, metaclass=ABCMetaLogger,
211
234
  table_name: str = None,
212
235
  column_name: str,
213
236
  column_value: Any,
214
- fields: dict = None) -> Optional[dict]:
237
+ fields: dict = None
238
+ ) -> Optional[dict]:
215
239
  return self.select_one_dict_by_where(
216
240
  table_name=table_name,
217
241
  where={column_name: column_value},
@@ -222,7 +246,9 @@ class GenericCrudMongodb(GenericCrudAbstract, metaclass=ABCMetaLogger,
222
246
  table_name: str = None,
223
247
  where: dict = None,
224
248
  fields: dict = None) -> Optional[dict]:
225
- """``where`` is a MongoDB filter dict (the MongoDB equivalent of a SQL WHERE clause)."""
249
+ """``where`` is a MongoDB filter dict
250
+ (the MongoDB equivalent of a SQL WHERE clause).
251
+ """
226
252
  table_name = table_name or self.default_table_name
227
253
  return self._collection(table_name).find_one(
228
254
  self._live_filter(where or {}), fields)
@@ -234,7 +260,8 @@ class GenericCrudMongodb(GenericCrudAbstract, metaclass=ABCMetaLogger,
234
260
  column_value: Any,
235
261
  fields: dict = None,
236
262
  limit: int = 0,
237
- order_by: list = None) -> list[dict]:
263
+ order_by: list = None
264
+ ) -> list[dict]:
238
265
  return self.select_multi_dict_by_where(
239
266
  table_name=table_name,
240
267
  where={column_name: column_value},
@@ -247,7 +274,9 @@ class GenericCrudMongodb(GenericCrudAbstract, metaclass=ABCMetaLogger,
247
274
  fields: dict = None,
248
275
  limit: int = 0,
249
276
  order_by: list = None) -> list[dict]:
250
- """``where`` is a MongoDB filter dict (the MongoDB equivalent of a SQL WHERE clause)."""
277
+ """``where`` is a MongoDB filter dict
278
+ (the MongoDB equivalent of a SQL WHERE clause).
279
+ """
251
280
  table_name = table_name or self.default_table_name
252
281
  cursor = self._collection(table_name).find(
253
282
  self._live_filter(where or {}), fields)
@@ -4,16 +4,18 @@ from typing import Optional, Tuple
4
4
  from bson import ObjectId
5
5
  from logger_local.MetaLogger import ABCMetaLogger
6
6
 
7
- from .constants_src import CRUD_ML_CODE_LOGGER_OBJECT
7
+ from .constants_src import GENERIC_CRUD_ML_MONGODB_CODE_LOGGER_INIT_OBJECT
8
8
  from .decorators import handle_db_errors
9
9
  from .generic_crud import GenericCrudMongodb
10
10
 
11
11
  TRANSLATIONS_FIELD = "translations"
12
12
 
13
13
 
14
- class GenericCrudMlMongoDB(GenericCrudMongodb, metaclass=ABCMetaLogger,
15
- object=CRUD_ML_CODE_LOGGER_OBJECT):
16
- """Extends GenericCrudMongodb with multi-language support via an embedded translations array.
14
+ class GenericCrudMlMongoDB( # noqa: E501
15
+ GenericCrudMongodb, metaclass=ABCMetaLogger,
16
+ object=GENERIC_CRUD_ML_MONGODB_CODE_LOGGER_INIT_OBJECT):
17
+ """Extends GenericCrudMongodb with multi-language support
18
+ via an embedded translations array.
17
19
 
18
20
  Each document looks like:
19
21
  {
@@ -64,7 +66,8 @@ class GenericCrudMlMongoDB(GenericCrudMongodb, metaclass=ABCMetaLogger,
64
66
  is_main: bool = None) -> Tuple[ObjectId, int]:
65
67
  """Add or replace a translation on an existing document.
66
68
 
67
- If lang_code already exists, updates it. Returns (document_id, translation_index).
69
+ If lang_code already exists, updates it.
70
+ Returns (document_id, translation_index).
68
71
  """
69
72
  table_name = table_name or self.default_table_name
70
73
  translation = dict(data_ml_dict)
@@ -101,7 +104,9 @@ class GenericCrudMlMongoDB(GenericCrudMongodb, metaclass=ABCMetaLogger,
101
104
  lang_code: str,
102
105
  document_id: ObjectId = None,
103
106
  is_main: bool = None) -> Tuple[ObjectId, int]:
104
- """Backward-compatible wrapper — use create_with_translation or add_translation instead."""
107
+ """Backward-compatible wrapper — use create_with_translation
108
+ or add_translation instead.
109
+ """
105
110
  if document_id is None:
106
111
  return self.create_with_translation(
107
112
  table_name=table_name,
@@ -195,10 +200,13 @@ class GenericCrudMlMongoDB(GenericCrudMongodb, metaclass=ABCMetaLogger,
195
200
  is_main=is_main)
196
201
  return doc_id, lang_code
197
202
 
198
- # ------------------------------------------------------------------ helpers
203
+ # ----------------------------------------------------------------- helpers
199
204
 
200
- def _clear_all_is_main(self, table_name: str, document_id: ObjectId) -> None:
201
- """Set is_main=False on every translation. Used before promoting a new main."""
205
+ def _clear_all_is_main(self, table_name: str,
206
+ document_id: ObjectId) -> None:
207
+ """Set is_main=False on every translation.
208
+ Used before promoting a new main.
209
+ """
202
210
  doc = self._collection(table_name).find_one(
203
211
  {"_id": document_id}, {TRANSLATIONS_FIELD: 1})
204
212
  if doc:
@@ -209,8 +217,11 @@ class GenericCrudMlMongoDB(GenericCrudMongodb, metaclass=ABCMetaLogger,
209
217
  {"$set": {TRANSLATIONS_FIELD: cleared}})
210
218
 
211
219
  @staticmethod
212
- def _find_translation(translations: list, lang_code: str) -> Optional[dict]:
213
- return next((t for t in translations if t.get("lang_code") == lang_code), None)
220
+ def _find_translation(translations: list,
221
+ lang_code: str) -> Optional[dict]:
222
+ return next(
223
+ (t for t in translations if t.get("lang_code") == lang_code),
224
+ None)
214
225
 
215
226
  @staticmethod
216
227
  def _find_main_translation(translations: list) -> Optional[dict]:
@@ -226,7 +237,8 @@ class GenericCrudMlMongoDB(GenericCrudMongodb, metaclass=ABCMetaLogger,
226
237
  document_id=document_id, table_name=table_name)
227
238
  if not doc:
228
239
  return None
229
- return self._find_translation(doc.get(TRANSLATIONS_FIELD, []), lang_code)
240
+ return self._find_translation(
241
+ doc.get(TRANSLATIONS_FIELD, []), lang_code)
230
242
 
231
243
  @handle_db_errors
232
244
  def get_main_translation(self, *, table_name: str = None,
@@ -273,6 +285,11 @@ class GenericCrudMlMongoDB(GenericCrudMongodb, metaclass=ABCMetaLogger,
273
285
  doc = self._collection(table_name).find_one(
274
286
  {"_id": document_id}, {TRANSLATIONS_FIELD: 1})
275
287
  translations = doc.get(TRANSLATIONS_FIELD, []) if doc else []
288
+ if len(translations) <= 1:
289
+ raise ValueError(
290
+ f"Cannot delete the last translation "
291
+ f"(lang_code='{lang_code}') on document "
292
+ f"{document_id} — delete the document instead")
276
293
  deleted_was_main = any(
277
294
  t.get("lang_code") == lang_code and t.get("is_main")
278
295
  for t in translations)
@@ -284,7 +301,8 @@ class GenericCrudMlMongoDB(GenericCrudMongodb, metaclass=ABCMetaLogger,
284
301
  if deleted_was_main:
285
302
  remaining = self._collection(table_name).find_one(
286
303
  {"_id": document_id}, {TRANSLATIONS_FIELD: 1})
287
- remaining_translations = remaining.get(TRANSLATIONS_FIELD, []) if remaining else []
304
+ remaining_translations = remaining.get(
305
+ TRANSLATIONS_FIELD, []) if remaining else []
288
306
  if remaining_translations:
289
307
  first_lang_code = remaining_translations[0]["lang_code"]
290
308
  self._collection(table_name).update_one(
@@ -3,13 +3,14 @@ from typing import Optional
3
3
  from bson import ObjectId
4
4
  from logger_local.MetaLogger import ABCMetaLogger
5
5
 
6
- from .constants_src import MAPPING_CODE_LOGGER_OBJECT
6
+ from .constants_src import GENERIC_MAPPING_MONGODB_CODE_LOGGER_INIT_OBJECT
7
7
  from .decorators import handle_db_errors
8
8
  from .generic_crud import GenericCrudMongodb
9
9
 
10
10
 
11
- class GenericMappingMongodb(GenericCrudMongodb, metaclass=ABCMetaLogger,
12
- object=MAPPING_CODE_LOGGER_OBJECT):
11
+ class GenericMappingMongodb( # noqa: E501
12
+ GenericCrudMongodb, metaclass=ABCMetaLogger,
13
+ object=GENERIC_MAPPING_MONGODB_CODE_LOGGER_INIT_OBJECT):
13
14
  """Extends GenericCrudMongodb with entity-to-entity mapping operations.
14
15
 
15
16
  A mapping links two entities, e.g. person ↔ group, stored in a
@@ -51,7 +52,8 @@ class GenericMappingMongodb(GenericCrudMongodb, metaclass=ABCMetaLogger,
51
52
  entity_name1: str = None, entity_name2: str = None,
52
53
  data_dict: dict = None,
53
54
  ignore_duplicate: bool = False) -> Optional[ObjectId]:
54
- entity_name1, entity_name2 = self._resolve_names(entity_name1, entity_name2)
55
+ entity_name1, entity_name2 = self._resolve_names(
56
+ entity_name1, entity_name2)
55
57
  table_name = self._mapping_table_name(entity_name1, entity_name2)
56
58
  data_dict = dict(data_dict or {})
57
59
  data_dict[f"{entity_name1}_id"] = entity_id1
@@ -60,15 +62,19 @@ class GenericMappingMongodb(GenericCrudMongodb, metaclass=ABCMetaLogger,
60
62
  ignore_duplicate=ignore_duplicate)
61
63
 
62
64
  @handle_db_errors
63
- def insert_mapping_if_not_exists(self, *, entity_id1: ObjectId, entity_id2: ObjectId,
64
- entity_name1: str = None, entity_name2: str = None,
65
- data_dict: dict = None) -> Optional[ObjectId]:
66
- entity_name1, entity_name2 = self._resolve_names(entity_name1, entity_name2)
65
+ def insert_mapping_if_not_exists(
66
+ self, *,
67
+ entity_id1: ObjectId, entity_id2: ObjectId,
68
+ entity_name1: str = None, entity_name2: str = None,
69
+ data_dict: dict = None) -> Optional[ObjectId]:
70
+ entity_name1, entity_name2 = self._resolve_names(
71
+ entity_name1, entity_name2)
67
72
  table_name = self._mapping_table_name(entity_name1, entity_name2)
68
73
  data_dict = dict(data_dict or {})
69
74
  data_dict[f"{entity_name1}_id"] = entity_id1
70
75
  data_dict[f"{entity_name2}_id"] = entity_id2
71
- compare = {f"{entity_name1}_id": entity_id1, f"{entity_name2}_id": entity_id2}
76
+ compare = {f"{entity_name1}_id": entity_id1,
77
+ f"{entity_name2}_id": entity_id2}
72
78
  return self.insert_if_not_exists(table_name=table_name,
73
79
  data_dict=data_dict,
74
80
  data_dict_compare=compare)
@@ -77,26 +83,32 @@ class GenericMappingMongodb(GenericCrudMongodb, metaclass=ABCMetaLogger,
77
83
  def upsert_mapping(self, *, entity_id1: ObjectId, entity_id2: ObjectId,
78
84
  entity_name1: str = None, entity_name2: str = None,
79
85
  data_dict: dict = None) -> Optional[ObjectId]:
80
- entity_name1, entity_name2 = self._resolve_names(entity_name1, entity_name2)
86
+ entity_name1, entity_name2 = self._resolve_names(
87
+ entity_name1, entity_name2)
81
88
  table_name = self._mapping_table_name(entity_name1, entity_name2)
82
89
  data_dict = dict(data_dict or {})
83
90
  data_dict[f"{entity_name1}_id"] = entity_id1
84
91
  data_dict[f"{entity_name2}_id"] = entity_id2
85
- compare = {f"{entity_name1}_id": entity_id1, f"{entity_name2}_id": entity_id2}
92
+ compare = {f"{entity_name1}_id": entity_id1,
93
+ f"{entity_name2}_id": entity_id2}
86
94
  return self.upsert(table_name=table_name, data_dict=data_dict,
87
95
  data_dict_compare=compare)
88
96
 
89
97
  # ------------------------------------------------------------------ delete
90
98
 
91
99
  @handle_db_errors
92
- def delete_mapping_by_two_ids(self, *, entity_id1: ObjectId, entity_id2: ObjectId,
93
- entity_name1: str = None,
94
- entity_name2: str = None) -> int:
95
- entity_name1, entity_name2 = self._resolve_names(entity_name1, entity_name2)
100
+ def delete_mapping_by_two_ids(
101
+ self, *,
102
+ entity_id1: ObjectId, entity_id2: ObjectId,
103
+ entity_name1: str = None,
104
+ entity_name2: str = None) -> int:
105
+ entity_name1, entity_name2 = self._resolve_names(
106
+ entity_name1, entity_name2)
96
107
  table_name = self._mapping_table_name(entity_name1, entity_name2)
97
108
  return self.delete_by_where(
98
109
  table_name=table_name,
99
- where=self._mapping_filter(entity_name1, entity_name2, entity_id1, entity_id2))
110
+ where=self._mapping_filter(
111
+ entity_name1, entity_name2, entity_id1, entity_id2))
100
112
 
101
113
  # ------------------------------------------------------------------ select
102
114
 
@@ -105,7 +117,8 @@ class GenericMappingMongodb(GenericCrudMongodb, metaclass=ABCMetaLogger,
105
117
  entity_id1: ObjectId,
106
118
  entity_name1: str = None,
107
119
  entity_name2: str = None) -> list[dict]:
108
- entity_name1, entity_name2 = self._resolve_names(entity_name1, entity_name2)
120
+ entity_name1, entity_name2 = self._resolve_names(
121
+ entity_name1, entity_name2)
109
122
  table_name = self._mapping_table_name(entity_name1, entity_name2)
110
123
  return self.select_multi_dict_by_where(
111
124
  table_name=table_name,
@@ -116,7 +129,8 @@ class GenericMappingMongodb(GenericCrudMongodb, metaclass=ABCMetaLogger,
116
129
  entity_id2: ObjectId,
117
130
  entity_name1: str = None,
118
131
  entity_name2: str = None) -> list[dict]:
119
- entity_name1, entity_name2 = self._resolve_names(entity_name1, entity_name2)
132
+ entity_name1, entity_name2 = self._resolve_names(
133
+ entity_name1, entity_name2)
120
134
  table_name = self._mapping_table_name(entity_name1, entity_name2)
121
135
  return self.select_multi_dict_by_where(
122
136
  table_name=table_name,
@@ -128,8 +142,10 @@ class GenericMappingMongodb(GenericCrudMongodb, metaclass=ABCMetaLogger,
128
142
  entity_id2: ObjectId,
129
143
  entity_name1: str = None,
130
144
  entity_name2: str = None) -> Optional[dict]:
131
- entity_name1, entity_name2 = self._resolve_names(entity_name1, entity_name2)
145
+ entity_name1, entity_name2 = self._resolve_names(
146
+ entity_name1, entity_name2)
132
147
  table_name = self._mapping_table_name(entity_name1, entity_name2)
133
148
  return self.select_one_dict_by_where(
134
149
  table_name=table_name,
135
- where=self._mapping_filter(entity_name1, entity_name2, entity_id1, entity_id2))
150
+ where=self._mapping_filter(
151
+ entity_name1, entity_name2, entity_id1, entity_id2))
@@ -0,0 +1,10 @@
1
+ from importlib.metadata import version, PackageNotFoundError
2
+
3
+ try:
4
+ VERSION = version("database-mongodb-local")
5
+ except PackageNotFoundError:
6
+ VERSION = "unknown"
7
+
8
+
9
+ def get_package_version() -> str:
10
+ return f" version={VERSION}"
@@ -0,0 +1,103 @@
1
+ from unittest.mock import MagicMock
2
+
3
+ import pytest
4
+
5
+ from database_mongodb_local.src import connector
6
+ from database_mongodb_local.src.connector import Connector
7
+
8
+
9
+ @pytest.fixture(autouse=True)
10
+ def _clear_client_cache():
11
+ """Reset the lru_cache around _get_real_client before and after each test.
12
+
13
+ _get_real_client is module-level cached, so without this a client built
14
+ under one set of env vars would leak into the next test.
15
+ """
16
+ reset = getattr(connector._get_real_client, "cache_clear", None)
17
+ if reset:
18
+ reset()
19
+ yield
20
+ reset = getattr(connector._get_real_client, "cache_clear", None)
21
+ if reset:
22
+ reset()
23
+
24
+
25
+ def _clear_mongo_env(monkeypatch):
26
+ for key in ("MONGODB_HOST", "MONGODB_PORT",
27
+ "MONGODB_USERNAME", "MONGODB_PASSWORD"):
28
+ monkeypatch.delenv(key, raising=False)
29
+
30
+
31
+ def test_get_real_client_without_auth_uses_defaults(monkeypatch):
32
+ _clear_mongo_env(monkeypatch)
33
+ mock_client_cls = MagicMock()
34
+ monkeypatch.setattr(connector, "MongoClient", mock_client_cls)
35
+
36
+ connector._get_real_client()
37
+
38
+ mock_client_cls.assert_called_once_with(host="localhost", port=27017)
39
+
40
+
41
+ def test_get_real_client_with_auth_passes_credentials(monkeypatch):
42
+ _clear_mongo_env(monkeypatch)
43
+ monkeypatch.setenv("MONGODB_HOST", "db.example.com")
44
+ monkeypatch.setenv("MONGODB_PORT", "27018")
45
+ monkeypatch.setenv("MONGODB_USERNAME", "admin")
46
+ monkeypatch.setenv("MONGODB_PASSWORD", "secret")
47
+ mock_client_cls = MagicMock()
48
+ monkeypatch.setattr(connector, "MongoClient", mock_client_cls)
49
+
50
+ connector._get_real_client()
51
+
52
+ mock_client_cls.assert_called_once_with(
53
+ host="db.example.com", port=27018,
54
+ username="admin", password="secret")
55
+
56
+
57
+ def test_get_real_client_without_password_omits_credentials(monkeypatch):
58
+ # username present but no password -> must fall to the no-auth branch
59
+ _clear_mongo_env(monkeypatch)
60
+ monkeypatch.setenv("MONGODB_USERNAME", "admin")
61
+ mock_client_cls = MagicMock()
62
+ monkeypatch.setattr(connector, "MongoClient", mock_client_cls)
63
+
64
+ connector._get_real_client()
65
+
66
+ mock_client_cls.assert_called_once_with(host="localhost", port=27017)
67
+
68
+
69
+ def test_get_real_client_is_cached(monkeypatch):
70
+ _clear_mongo_env(monkeypatch)
71
+ mock_client_cls = MagicMock()
72
+ monkeypatch.setattr(connector, "MongoClient", mock_client_cls)
73
+
74
+ first = connector._get_real_client()
75
+ second = connector._get_real_client()
76
+
77
+ assert first is second
78
+ mock_client_cls.assert_called_once()
79
+
80
+
81
+ def test_get_database_returns_named_database(monkeypatch):
82
+ mock_client = MagicMock()
83
+ monkeypatch.setattr(connector, "_get_real_client", lambda: mock_client)
84
+
85
+ result = Connector.get_database("my_db")
86
+
87
+ assert result is mock_client["my_db"]
88
+
89
+
90
+ def test_is_mongo_available_returns_true_on_successful_ping(monkeypatch):
91
+ mock_client = MagicMock()
92
+ monkeypatch.setattr(connector, "_get_real_client", lambda: mock_client)
93
+
94
+ assert Connector.is_mongo_available() is True
95
+ mock_client.admin.command.assert_called_once_with("ping")
96
+
97
+
98
+ def test_is_mongo_available_returns_false_when_ping_raises(monkeypatch):
99
+ mock_client = MagicMock()
100
+ mock_client.admin.command.side_effect = Exception("unreachable")
101
+ monkeypatch.setattr(connector, "_get_real_client", lambda: mock_client)
102
+
103
+ assert Connector.is_mongo_available() is False
@@ -68,7 +68,8 @@ def test_real_same_lang_code_replaces(crud_ml):
68
68
  data_ml_dict={"title": "Italia"},
69
69
  lang_code="fr")
70
70
  doc = crud_ml.select_one_dict_by_id(document_id=doc_id)
71
- fr_translations = [t for t in doc["translations"] if t["lang_code"] == "fr"]
71
+ fr_translations = [t for t in doc["translations"]
72
+ if t["lang_code"] == "fr"]
72
73
  assert len(fr_translations) == 1
73
74
  assert fr_translations[0]["title"] == "Italia"
74
75
 
@@ -1,4 +1,5 @@
1
1
  import pytest
2
+ from language_remote.lang_code import LangCode
2
3
 
3
4
  from database_mongodb_local.src.generic_crud_ml import GenericCrudMlMongoDB
4
5
 
@@ -7,8 +8,7 @@ COLLECTION = "country"
7
8
 
8
9
 
9
10
  @pytest.fixture
10
- def crud_ml(monkeypatch):
11
- monkeypatch.setenv("MONGODB_MOCK", "true")
11
+ def crud_ml(mock_mongo):
12
12
  return GenericCrudMlMongoDB(
13
13
  default_schema_name=DB_NAME,
14
14
  default_table_name=COLLECTION)
@@ -18,7 +18,7 @@ def test_create_with_translation_creates_document(crud_ml):
18
18
  doc_id, _ = crud_ml.create_with_translation(
19
19
  data_dict={"code": "FR"},
20
20
  data_ml_dict={"title": "France"},
21
- lang_code="en")
21
+ lang_code=LangCode.ENGLISH.value)
22
22
  doc = crud_ml.select_one_dict_by_id(document_id=doc_id)
23
23
  assert doc is not None
24
24
  assert doc["code"] == "FR"
@@ -29,7 +29,7 @@ def test_create_with_translation_first_translation_is_main(crud_ml):
29
29
  doc_id, _ = crud_ml.create_with_translation(
30
30
  data_dict={"code": "FR"},
31
31
  data_ml_dict={"title": "France"},
32
- lang_code="en")
32
+ lang_code=LangCode.ENGLISH.value)
33
33
  doc = crud_ml.select_one_dict_by_id(document_id=doc_id)
34
34
  assert doc["translations"][0]["is_main"] is True
35
35
 
@@ -38,11 +38,11 @@ def test_add_translation_appends_second_translation(crud_ml):
38
38
  doc_id, _ = crud_ml.create_with_translation(
39
39
  data_dict={"code": "FR"},
40
40
  data_ml_dict={"title": "France"},
41
- lang_code="en")
41
+ lang_code=LangCode.ENGLISH.value)
42
42
  crud_ml.add_translation(
43
43
  document_id=doc_id,
44
44
  data_ml_dict={"title": "France"},
45
- lang_code="fr")
45
+ lang_code=LangCode.FRENCH.value)
46
46
  doc = crud_ml.select_one_dict_by_id(document_id=doc_id)
47
47
  assert len(doc["translations"]) == 2
48
48
 
@@ -51,11 +51,11 @@ def test_add_value_if_not_exists_no_duplicate(crud_ml):
51
51
  id1, _ = crud_ml.add_value_if_not_exists(
52
52
  data_dict={"code": "DE"},
53
53
  data_ml_dict={"title": "Germany"},
54
- lang_code="en")
54
+ lang_code=LangCode.ENGLISH.value)
55
55
  id2, _ = crud_ml.add_value_if_not_exists(
56
56
  data_dict={"code": "DE"},
57
57
  data_ml_dict={"title": "Germany"},
58
- lang_code="en")
58
+ lang_code=LangCode.ENGLISH.value)
59
59
  assert id1 == id2
60
60
  assert crud_ml.get_num_of_rows() == 1
61
61
 
@@ -64,9 +64,13 @@ def test_get_translation_returns_correct_language(crud_ml):
64
64
  doc_id, _ = crud_ml.create_with_translation(
65
65
  data_dict={"code": "ES"},
66
66
  data_ml_dict={"title": "Spain"},
67
- lang_code="en")
68
- crud_ml.add_translation(document_id=doc_id, data_ml_dict={"title": "España"}, lang_code="es")
69
- translation = crud_ml.get_translation(document_id=doc_id, lang_code="es")
67
+ lang_code=LangCode.ENGLISH.value)
68
+ crud_ml.add_translation(
69
+ document_id=doc_id,
70
+ data_ml_dict={"title": "España"},
71
+ lang_code=LangCode.SPANISH.value)
72
+ translation = crud_ml.get_translation(
73
+ document_id=doc_id, lang_code=LangCode.SPANISH.value)
70
74
  assert translation["title"] == "España"
71
75
 
72
76
 
@@ -74,7 +78,7 @@ def test_get_main_translation(crud_ml):
74
78
  doc_id, _ = crud_ml.create_with_translation(
75
79
  data_dict={"code": "IT"},
76
80
  data_ml_dict={"title": "Italy"},
77
- lang_code="en")
81
+ lang_code=LangCode.ENGLISH.value)
78
82
  main = crud_ml.get_main_translation(document_id=doc_id)
79
83
  assert main["title"] == "Italy"
80
84
  assert main["is_main"] is True
@@ -84,8 +88,9 @@ def test_get_id_by_title(crud_ml):
84
88
  doc_id, _ = crud_ml.create_with_translation(
85
89
  data_dict={"code": "JP"},
86
90
  data_ml_dict={"title": "Japan"},
87
- lang_code="en")
88
- found_id = crud_ml.get_id_by_title(title="Japan", lang_code="en")
91
+ lang_code=LangCode.ENGLISH.value)
92
+ found_id = crud_ml.get_id_by_title(
93
+ title="Japan", lang_code=LangCode.ENGLISH.value)
89
94
  assert found_id == doc_id
90
95
 
91
96
 
@@ -93,10 +98,13 @@ def test_update_value_by_id(crud_ml):
93
98
  doc_id, _ = crud_ml.create_with_translation(
94
99
  data_dict={"code": "CN"},
95
100
  data_ml_dict={"title": "Chnia"},
96
- lang_code="en")
101
+ lang_code=LangCode.ENGLISH.value)
97
102
  crud_ml.update_value_by_id(
98
- document_id=doc_id, lang_code="en", data_ml_dict={"title": "China"})
99
- translation = crud_ml.get_translation(document_id=doc_id, lang_code="en")
103
+ document_id=doc_id,
104
+ lang_code=LangCode.ENGLISH.value,
105
+ data_ml_dict={"title": "China"})
106
+ translation = crud_ml.get_translation(
107
+ document_id=doc_id, lang_code=LangCode.ENGLISH.value)
100
108
  assert translation["title"] == "China"
101
109
 
102
110
 
@@ -104,7 +112,7 @@ def test_upsert_value_inserts_when_not_exists(crud_ml):
104
112
  doc_id, _ = crud_ml.upsert_value(
105
113
  data_dict={"code": "BR"},
106
114
  data_ml_dict={"title": "Brazil"},
107
- lang_code="en")
115
+ lang_code=LangCode.ENGLISH.value)
108
116
  assert doc_id is not None
109
117
  assert crud_ml.get_num_of_rows() == 1
110
118
 
@@ -113,13 +121,14 @@ def test_add_translation_same_lang_code_replaces_not_duplicates(crud_ml):
113
121
  doc_id, _ = crud_ml.create_with_translation(
114
122
  data_dict={"code": "FR"},
115
123
  data_ml_dict={"title": "France"},
116
- lang_code="en")
124
+ lang_code=LangCode.ENGLISH.value)
117
125
  crud_ml.add_translation(
118
126
  document_id=doc_id,
119
127
  data_ml_dict={"title": "Francia"},
120
- lang_code="en")
128
+ lang_code=LangCode.ENGLISH.value)
121
129
  doc = crud_ml.select_one_dict_by_id(document_id=doc_id)
122
- en_translations = [t for t in doc["translations"] if t["lang_code"] == "en"]
130
+ en_translations = [t for t in doc["translations"]
131
+ if t["lang_code"] == LangCode.ENGLISH.value]
123
132
  assert len(en_translations) == 1
124
133
  assert en_translations[0]["title"] == "Francia"
125
134
 
@@ -128,10 +137,15 @@ def test_delete_translation_removes_language(crud_ml):
128
137
  doc_id, _ = crud_ml.create_with_translation(
129
138
  data_dict={"code": "AU"},
130
139
  data_ml_dict={"title": "Australia"},
131
- lang_code="en")
132
- crud_ml.add_translation(document_id=doc_id, data_ml_dict={"title": "Australie"}, lang_code="fr")
133
- crud_ml.delete_translation(document_id=doc_id, lang_code="fr")
134
- translation = crud_ml.get_translation(document_id=doc_id, lang_code="fr")
140
+ lang_code=LangCode.ENGLISH.value)
141
+ crud_ml.add_translation(
142
+ document_id=doc_id,
143
+ data_ml_dict={"title": "Australie"},
144
+ lang_code=LangCode.FRENCH.value)
145
+ crud_ml.delete_translation(
146
+ document_id=doc_id, lang_code=LangCode.FRENCH.value)
147
+ translation = crud_ml.get_translation(
148
+ document_id=doc_id, lang_code=LangCode.FRENCH.value)
135
149
  assert translation is None
136
150
 
137
151
 
@@ -139,65 +153,85 @@ def test_delete_main_translation_promotes_next(crud_ml):
139
153
  doc_id, _ = crud_ml.create_with_translation(
140
154
  data_dict={"code": "AU"},
141
155
  data_ml_dict={"title": "Australia"},
142
- lang_code="en")
143
- crud_ml.add_translation(document_id=doc_id, data_ml_dict={"title": "Australie"}, lang_code="fr")
144
- crud_ml.delete_translation(document_id=doc_id, lang_code="en")
156
+ lang_code=LangCode.ENGLISH.value)
157
+ crud_ml.add_translation(
158
+ document_id=doc_id,
159
+ data_ml_dict={"title": "Australie"},
160
+ lang_code=LangCode.FRENCH.value)
161
+ crud_ml.delete_translation(
162
+ document_id=doc_id, lang_code=LangCode.ENGLISH.value)
145
163
  main = crud_ml.get_main_translation(document_id=doc_id)
146
164
  assert main is not None
147
- assert main["lang_code"] == "fr"
165
+ assert main["lang_code"] == LangCode.FRENCH.value
148
166
  assert main["is_main"] is True
149
167
 
150
168
 
169
+ def test_delete_translation_raises_when_only_one_translation(crud_ml):
170
+ doc_id, _ = crud_ml.create_with_translation(
171
+ data_dict={"code": "FR"},
172
+ data_ml_dict={"title": "France"},
173
+ lang_code=LangCode.ENGLISH.value)
174
+ with pytest.raises(ValueError, match="Cannot delete the last translation"):
175
+ crud_ml.delete_translation(
176
+ document_id=doc_id, lang_code=LangCode.ENGLISH.value)
177
+
178
+
151
179
  def test_get_all_translations(crud_ml):
152
180
  doc_id, _ = crud_ml.create_with_translation(
153
181
  data_dict={"code": "FR"},
154
182
  data_ml_dict={"title": "France"},
155
- lang_code="en")
156
- crud_ml.add_translation(document_id=doc_id, data_ml_dict={"title": "צרפת"}, lang_code="he")
183
+ lang_code=LangCode.ENGLISH.value)
184
+ crud_ml.add_translation(document_id=doc_id, data_ml_dict={
185
+ "title": "צרפת"}, lang_code=LangCode.HEBREW.value)
157
186
  translations = crud_ml.get_all_translations(document_id=doc_id)
158
187
  assert len(translations) == 2
159
188
  lang_codes = [t["lang_code"] for t in translations]
160
- assert "en" in lang_codes
161
- assert "he" in lang_codes
189
+ assert LangCode.ENGLISH.value in lang_codes
190
+ assert LangCode.HEBREW.value in lang_codes
162
191
 
163
192
 
164
193
  def test_get_lang_codes(crud_ml):
165
194
  doc_id, _ = crud_ml.create_with_translation(
166
195
  data_dict={"code": "DE"},
167
196
  data_ml_dict={"title": "Germany"},
168
- lang_code="en")
169
- crud_ml.add_translation(document_id=doc_id, data_ml_dict={"title": "Deutschland"}, lang_code="de")
197
+ lang_code=LangCode.ENGLISH.value)
198
+ crud_ml.add_translation(
199
+ document_id=doc_id,
200
+ data_ml_dict={"title": "Deutschland"},
201
+ lang_code=LangCode.GERMAN.value)
170
202
  lang_codes = crud_ml.get_lang_codes(document_id=doc_id)
171
- assert sorted(lang_codes) == ["de", "en"]
203
+ assert sorted(lang_codes) == sorted(
204
+ [LangCode.GERMAN.value, LangCode.ENGLISH.value])
172
205
 
173
206
 
174
207
  def test_add_translation_with_is_main_true_changes_main(crud_ml):
175
208
  doc_id, _ = crud_ml.create_with_translation(
176
209
  data_dict={"code": "FR"},
177
210
  data_ml_dict={"title": "France"},
178
- lang_code="en")
211
+ lang_code=LangCode.ENGLISH.value)
179
212
  crud_ml.add_translation(
180
213
  document_id=doc_id,
181
214
  data_ml_dict={"title": "France"},
182
- lang_code="fr",
215
+ lang_code=LangCode.FRENCH.value,
183
216
  is_main=True)
184
217
  main = crud_ml.get_main_translation(document_id=doc_id)
185
- assert main["lang_code"] == "fr"
218
+ assert main["lang_code"] == LangCode.FRENCH.value
186
219
 
187
220
 
188
221
  def test_update_value_by_id_with_data_dict(crud_ml):
189
222
  doc_id, _ = crud_ml.create_with_translation(
190
223
  data_dict={"code": "DE"},
191
224
  data_ml_dict={"title": "Germany"},
192
- lang_code="en")
225
+ lang_code=LangCode.ENGLISH.value)
193
226
  crud_ml.update_value_by_id(
194
227
  document_id=doc_id,
195
- lang_code="en",
228
+ lang_code=LangCode.ENGLISH.value,
196
229
  data_ml_dict={"title": "Deutschland"},
197
230
  data_dict={"code": "DE2"})
198
231
  doc = crud_ml.select_one_dict_by_id(document_id=doc_id)
199
232
  assert doc["code"] == "DE2"
200
- translation = crud_ml.get_translation(document_id=doc_id, lang_code="en")
233
+ translation = crud_ml.get_translation(
234
+ document_id=doc_id, lang_code=LangCode.ENGLISH.value)
201
235
  assert translation["title"] == "Deutschland"
202
236
 
203
237
 
@@ -205,29 +239,29 @@ def test_update_value_by_id_with_is_main_true(crud_ml):
205
239
  doc_id, _ = crud_ml.create_with_translation(
206
240
  data_dict={"code": "ES"},
207
241
  data_ml_dict={"title": "Spain"},
208
- lang_code="en")
242
+ lang_code=LangCode.ENGLISH.value)
209
243
  crud_ml.add_translation(
210
244
  document_id=doc_id,
211
245
  data_ml_dict={"title": "España"},
212
- lang_code="es")
246
+ lang_code=LangCode.SPANISH.value)
213
247
  crud_ml.update_value_by_id(
214
248
  document_id=doc_id,
215
- lang_code="es",
249
+ lang_code=LangCode.SPANISH.value,
216
250
  data_ml_dict={"title": "España"},
217
251
  is_main=True)
218
252
  main = crud_ml.get_main_translation(document_id=doc_id)
219
- assert main["lang_code"] == "es"
253
+ assert main["lang_code"] == LangCode.SPANISH.value
220
254
 
221
255
 
222
256
  def test_upsert_value_updates_existing(crud_ml):
223
257
  doc_id, _ = crud_ml.create_with_translation(
224
258
  data_dict={"code": "IT"},
225
259
  data_ml_dict={"title": "Italy"},
226
- lang_code="en")
260
+ lang_code=LangCode.ENGLISH.value)
227
261
  crud_ml.upsert_value(
228
262
  data_dict={"code": "IT2"},
229
263
  data_ml_dict={"title": "Italy"},
230
- lang_code="en")
264
+ lang_code=LangCode.ENGLISH.value)
231
265
  doc = crud_ml.select_one_dict_by_id(document_id=doc_id)
232
266
  assert doc["code"] == "IT2"
233
267
  assert crud_ml.get_num_of_rows() == 1
@@ -235,7 +269,8 @@ def test_upsert_value_updates_existing(crud_ml):
235
269
 
236
270
  def test_get_translation_nonexistent_doc_returns_none(crud_ml):
237
271
  from bson import ObjectId
238
- result = crud_ml.get_translation(document_id=ObjectId(), lang_code="en")
272
+ result = crud_ml.get_translation(
273
+ document_id=ObjectId(), lang_code=LangCode.ENGLISH.value)
239
274
  assert result is None
240
275
 
241
276
 
@@ -249,16 +284,18 @@ def test_merge_ml_entities_combines_translations(crud_ml):
249
284
  id1, _ = crud_ml.create_with_translation(
250
285
  data_dict={"code": "FR"},
251
286
  data_ml_dict={"title": "France"},
252
- lang_code="en")
253
- crud_ml.add_translation(document_id=id1, data_ml_dict={"title": "צרפת"}, lang_code="he")
287
+ lang_code=LangCode.ENGLISH.value)
288
+ crud_ml.add_translation(document_id=id1, data_ml_dict={
289
+ "title": "צרפת"}, lang_code=LangCode.HEBREW.value)
254
290
 
255
291
  id2, _ = crud_ml.create_with_translation(
256
292
  data_dict={"code": "FR"},
257
293
  data_ml_dict={"title": "Francia"},
258
- lang_code="es")
294
+ lang_code=LangCode.SPANISH.value)
259
295
 
260
296
  crud_ml.merge_ml_entities(entity_id1=id1, entity_id2=id2)
261
297
 
262
298
  assert crud_ml.select_one_dict_by_id(document_id=id1) is None
263
299
  lang_codes = crud_ml.get_lang_codes(document_id=id2)
264
- assert sorted(lang_codes) == ["en", "es", "he"]
300
+ assert sorted(lang_codes) == sorted([
301
+ LangCode.ENGLISH.value, LangCode.SPANISH.value, LangCode.HEBREW.value])
@@ -10,8 +10,7 @@ COLLECTION = "test_collection"
10
10
 
11
11
 
12
12
  @pytest.fixture
13
- def crud(monkeypatch):
14
- monkeypatch.setenv("MONGODB_MOCK", "true")
13
+ def crud(mock_mongo):
15
14
  return GenericCrudMongodb(
16
15
  default_schema_name=DB_NAME,
17
16
  default_table_name=COLLECTION)
@@ -44,26 +43,50 @@ def test_insert_if_not_exists_does_not_duplicate(crud):
44
43
 
45
44
  def test_insert_if_not_exists_by_field_inserts_new(crud):
46
45
  inserted_id = crud.insert_if_not_exists_by_field(
47
- field="external_id", data_dict={"external_id": "abc123", "name": "Alice"})
46
+ field="external_id",
47
+ data_dict={"external_id": "abc123", "name": "Alice"})
48
48
  assert inserted_id is not None
49
49
  assert crud.get_num_of_rows() == 1
50
50
 
51
51
 
52
52
  def test_insert_if_not_exists_by_field_returns_none_on_duplicate(crud):
53
53
  crud.insert_if_not_exists_by_field(
54
- field="external_id", data_dict={"external_id": "abc123", "name": "Alice"})
54
+ field="external_id",
55
+ data_dict={"external_id": "abc123", "name": "Alice"})
55
56
  second = crud.insert_if_not_exists_by_field(
56
- field="external_id", data_dict={"external_id": "abc123", "name": "Alice"})
57
+ field="external_id",
58
+ data_dict={"external_id": "abc123", "name": "Alice"})
57
59
  assert second is None
58
60
  assert crud.get_num_of_rows() == 1
59
61
 
60
62
 
61
63
  def test_insert_many(crud):
62
- count = crud.insert_many(data_dicts=[{"name": "A"}, {"name": "B"}, {"name": "C"}])
64
+ count = crud.insert_many(
65
+ data_dicts=[{"name": "A"}, {"name": "B"}, {"name": "C"}])
63
66
  assert count == 3
64
67
  assert crud.get_num_of_rows() == 3
65
68
 
66
69
 
70
+ def test_insert_many_skips_duplicates_and_inserts_new(crud):
71
+ from bson import ObjectId
72
+ shared_id = ObjectId()
73
+ crud.insert_many(data_dicts=[{"_id": shared_id, "name": "A"}])
74
+ count = crud.insert_many(data_dicts=[
75
+ {"_id": shared_id, "name": "A"},
76
+ {"name": "B"},
77
+ ])
78
+ assert count == 1
79
+ assert crud.get_num_of_rows() == 2
80
+
81
+
82
+ def test_ensure_index_prevents_duplicate_on_unique_field(crud):
83
+ crud.ensure_index(keys=[("name", 1)], unique=True)
84
+ crud.insert(data_dict={"name": "Alice"})
85
+ result = crud.insert(data_dict={"name": "Alice"}, ignore_duplicate=True)
86
+ assert result is None
87
+ assert crud.get_num_of_rows() == 1
88
+
89
+
67
90
  def test_upsert_inserts_when_not_exists(crud):
68
91
  doc_id = crud.upsert(data_dict={"name": "Carol", "age": 30},
69
92
  data_dict_compare={"name": "Carol"})
@@ -119,7 +142,8 @@ def test_select_multi_dict_by_where(crud):
119
142
 
120
143
  def test_select_one_value_by_where(crud):
121
144
  crud.insert(data_dict={"name": "Grace", "score": 99})
122
- value = crud.select_one_value_by_where(where={"name": "Grace"}, field="score")
145
+ value = crud.select_one_value_by_where(
146
+ where={"name": "Grace"}, field="score")
123
147
  assert value == 99
124
148
 
125
149
 
@@ -152,14 +176,16 @@ def test_database_error_raises_runtime_error(crud):
152
176
  mock_col = MagicMock()
153
177
  mock_col.find_one.side_effect = OperationFailure("forced error")
154
178
  mock_get_col.return_value = mock_col
155
- with pytest.raises(DatabaseOperationError, match="Database error in select_one_dict_by_where"):
179
+ with pytest.raises(DatabaseOperationError,
180
+ match="Database error in select_one_dict_by_where"):
156
181
  crud.select_one_dict_by_where(where={"name": "test"})
157
182
 
158
183
 
159
184
  def test_insert_ignore_duplicate_returns_none(crud):
160
185
  crud._collection().create_index("name", unique=True)
161
186
  crud.insert(data_dict={"name": "UniqueAlice"})
162
- result = crud.insert(data_dict={"name": "UniqueAlice"}, ignore_duplicate=True)
187
+ result = crud.insert(
188
+ data_dict={"name": "UniqueAlice"}, ignore_duplicate=True)
163
189
  assert result is None
164
190
 
165
191
 
@@ -191,7 +217,8 @@ def test_select_multi_dict_with_limit(crud):
191
217
  def test_select_multi_value_by_where(crud):
192
218
  crud.insert(data_dict={"tag": "python", "score": 10})
193
219
  crud.insert(data_dict={"tag": "python", "score": 20})
194
- scores = crud.select_multi_value_by_where(where={"tag": "python"}, field="score")
220
+ scores = crud.select_multi_value_by_where(
221
+ where={"tag": "python"}, field="score")
195
222
  assert sorted(scores) == [10, 20]
196
223
 
197
224
 
@@ -26,7 +26,8 @@ def mapping():
26
26
  def test_real_insert_mapping(mapping):
27
27
  person_id = ObjectId()
28
28
  group_id = ObjectId()
29
- mapping_id = mapping.insert_mapping(entity_id1=person_id, entity_id2=group_id)
29
+ mapping_id = mapping.insert_mapping(
30
+ entity_id1=person_id, entity_id2=group_id)
30
31
  assert mapping_id is not None
31
32
 
32
33
 
@@ -35,7 +36,8 @@ def test_real_select_mapping_by_two_ids(mapping):
35
36
  person_id = ObjectId()
36
37
  group_id = ObjectId()
37
38
  mapping.insert_mapping(entity_id1=person_id, entity_id2=group_id)
38
- result = mapping.select_mapping_by_two_ids(entity_id1=person_id, entity_id2=group_id)
39
+ result = mapping.select_mapping_by_two_ids(
40
+ entity_id1=person_id, entity_id2=group_id)
39
41
  assert result is not None
40
42
  assert result["person_id"] == person_id
41
43
  assert result["group_id"] == group_id
@@ -55,8 +57,10 @@ def test_real_delete_mapping(mapping):
55
57
  person_id = ObjectId()
56
58
  group_id = ObjectId()
57
59
  mapping.insert_mapping(entity_id1=person_id, entity_id2=group_id)
58
- mapping.delete_mapping_by_two_ids(entity_id1=person_id, entity_id2=group_id)
59
- result = mapping.select_mapping_by_two_ids(entity_id1=person_id, entity_id2=group_id)
60
+ mapping.delete_mapping_by_two_ids(
61
+ entity_id1=person_id, entity_id2=group_id)
62
+ result = mapping.select_mapping_by_two_ids(
63
+ entity_id1=person_id, entity_id2=group_id)
60
64
  assert result is None
61
65
 
62
66
 
@@ -65,5 +69,6 @@ def test_real_alphabetical_table_name(mapping):
65
69
  person_id = ObjectId()
66
70
  group_id = ObjectId()
67
71
  mapping.insert_mapping(entity_id1=person_id, entity_id2=group_id)
68
- result = mapping.select_mapping_by_two_ids(entity_id1=person_id, entity_id2=group_id)
72
+ result = mapping.select_mapping_by_two_ids(
73
+ entity_id1=person_id, entity_id2=group_id)
69
74
  assert result is not None
@@ -7,8 +7,7 @@ DB_NAME = "test_db"
7
7
 
8
8
 
9
9
  @pytest.fixture
10
- def mapping(monkeypatch):
11
- monkeypatch.setenv("MONGODB_MOCK", "true")
10
+ def mapping(mock_mongo):
12
11
  return GenericMappingMongodb(
13
12
  default_schema_name=DB_NAME,
14
13
  default_table_name="person_group",
@@ -19,15 +18,18 @@ def mapping(monkeypatch):
19
18
  def test_insert_mapping(mapping):
20
19
  person_id = ObjectId()
21
20
  group_id = ObjectId()
22
- mapping_id = mapping.insert_mapping(entity_id1=person_id, entity_id2=group_id)
21
+ mapping_id = mapping.insert_mapping(
22
+ entity_id1=person_id, entity_id2=group_id)
23
23
  assert mapping_id is not None
24
24
 
25
25
 
26
26
  def test_insert_mapping_if_not_exists_no_duplicate(mapping):
27
27
  person_id = ObjectId()
28
28
  group_id = ObjectId()
29
- id1 = mapping.insert_mapping_if_not_exists(entity_id1=person_id, entity_id2=group_id)
30
- id2 = mapping.insert_mapping_if_not_exists(entity_id1=person_id, entity_id2=group_id)
29
+ id1 = mapping.insert_mapping_if_not_exists(
30
+ entity_id1=person_id, entity_id2=group_id)
31
+ id2 = mapping.insert_mapping_if_not_exists(
32
+ entity_id1=person_id, entity_id2=group_id)
31
33
  assert id1 == id2
32
34
 
33
35
 
@@ -35,7 +37,8 @@ def test_select_mapping_by_two_ids(mapping):
35
37
  person_id = ObjectId()
36
38
  group_id = ObjectId()
37
39
  mapping.insert_mapping(entity_id1=person_id, entity_id2=group_id)
38
- result = mapping.select_mapping_by_two_ids(entity_id1=person_id, entity_id2=group_id)
40
+ result = mapping.select_mapping_by_two_ids(
41
+ entity_id1=person_id, entity_id2=group_id)
39
42
  assert result is not None
40
43
  assert result["person_id"] == person_id
41
44
  assert result["group_id"] == group_id
@@ -61,8 +64,10 @@ def test_delete_mapping_by_two_ids(mapping):
61
64
  person_id = ObjectId()
62
65
  group_id = ObjectId()
63
66
  mapping.insert_mapping(entity_id1=person_id, entity_id2=group_id)
64
- mapping.delete_mapping_by_two_ids(entity_id1=person_id, entity_id2=group_id)
65
- result = mapping.select_mapping_by_two_ids(entity_id1=person_id, entity_id2=group_id)
67
+ mapping.delete_mapping_by_two_ids(
68
+ entity_id1=person_id, entity_id2=group_id)
69
+ result = mapping.select_mapping_by_two_ids(
70
+ entity_id1=person_id, entity_id2=group_id)
66
71
  assert result is None
67
72
 
68
73
 
@@ -73,6 +78,7 @@ def test_upsert_mapping_updates_existing(mapping):
73
78
  data_dict={"role": "member"})
74
79
  mapping.upsert_mapping(entity_id1=person_id, entity_id2=group_id,
75
80
  data_dict={"role": "admin"})
76
- result = mapping.select_mapping_by_two_ids(entity_id1=person_id, entity_id2=group_id)
81
+ result = mapping.select_mapping_by_two_ids(
82
+ entity_id1=person_id, entity_id2=group_id)
77
83
  assert result["role"] == "admin"
78
84
  assert mapping.get_num_of_rows(table_name="group_person") == 1
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: database-mongodb-local
3
- Version: 0.0.2
3
+ Version: 0.0.6
4
4
  Summary: PyPI database-mongodb-local Python Package owned by Circlez.ai
5
5
  Home-page: https://github.com/circles-zone/database-mongodb-local-python-package
6
6
  Author: Circles
@@ -17,6 +17,7 @@ database_mongodb_local/src/generic_crud_ml.py
17
17
  database_mongodb_local/src/generic_mapping.py
18
18
  database_mongodb_local/src/version.py
19
19
  database_mongodb_local/tests/__init__.py
20
+ database_mongodb_local/tests/connector_test.py
20
21
  database_mongodb_local/tests/generic_crud_ml_system_test.py
21
22
  database_mongodb_local/tests/generic_crud_ml_test.py
22
23
  database_mongodb_local/tests/generic_crud_system_test.py
@@ -12,12 +12,11 @@ omit = [
12
12
  "*/generic_crud_abstract.py",
13
13
  "*/constants_src.py",
14
14
  "*/version.py",
15
- "*/connector.py",
16
15
  ]
17
16
 
18
17
  [tool.poetry]
19
18
  name = "database-mongodb-local"
20
- version = "0.0.4"
19
+ version = "0.0.6"
21
20
  description = "database-mongodb-local Python Package"
22
21
  readme = "README.md"
23
22
  authors = [
@@ -1,12 +1,18 @@
1
+ import tomllib
2
+ import os
1
3
  import setuptools
2
4
 
5
+ _here = os.path.dirname(os.path.abspath(__file__))
6
+ with open(os.path.join(_here, "pyproject.toml"), "rb") as f:
7
+ _version = tomllib.load(f)["tool"]["poetry"]["version"]
8
+
3
9
  PACKAGE_NAME = "database-mongodb-local"
4
10
  package_dir = PACKAGE_NAME.replace("-", "_")
5
11
  PACKAGE_DESCRIPTION = f"PyPI {PACKAGE_NAME} Python Package owned by Circlez.ai"
6
12
 
7
13
  setuptools.setup(
8
14
  name=PACKAGE_NAME,
9
- version='0.0.2',
15
+ version=_version,
10
16
  author="Circles",
11
17
  author_email="info@circlez.ai",
12
18
  description=PACKAGE_DESCRIPTION,
@@ -1,5 +0,0 @@
1
- VERSION = "0.0.2"
2
-
3
-
4
- def get_package_version() -> str:
5
- return f" version={VERSION}"