Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(Besoins): vérifier que les paramètres siae_id et user_id existent en BDD #1150

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions lemarche/utils/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
def get_object_by_id_or_none(classmodel, id: int | str | None):
"""
https://stackoverflow.com/a/20674112/4293684
"""
if id:
try:
return classmodel.objects.get(id=int(id))
except classmodel.DoesNotExist:
pass
return None
24 changes: 24 additions & 0 deletions lemarche/utils/tests_models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from django.test import TestCase

from lemarche.siaes.models import Siae
from lemarche.utils.models import get_object_by_id_or_none


class ModelsTest(TestCase):
@classmethod
def setUpTestData(cls):
cls.siae = Siae.objects.create()

def test_get_object_by_id_or_none(self):
# None
result = get_object_by_id_or_none(Siae, None)
self.assertIsNone(result)
# wrong id
result = get_object_by_id_or_none(Siae, self.siae.id + 1)
self.assertIsNone(result)
# id exists (but string)
result = get_object_by_id_or_none(Siae, str(self.siae.id))
self.assertEqual(result, self.siae)
# id exists
result = get_object_by_id_or_none(Siae, self.siae.id)
self.assertEqual(result, self.siae)
Loading