Django-Styleguide icon indicating copy to clipboard operation
Django-Styleguide copied to clipboard

Models testing, class-based services, celery tasks usage

Open Horbatenko opened this issue 4 years ago • 2 comments

Hey there! Thanks a lot for your hard work and such a comprehensive style guide! Tho I'm curious to hear your thoughts on the following points: point1:

Models need to be tested only if there’s something additional to them - like validation, properties or methods. (here)

what do you think about mentioning complex db constrains here? have you ever written a test case for checking that? f.e we have a following model

class Foo(models.Model):
    class Meta:
        constraints = [models.CheckConstraint(name='...',  check=((models.Q() | models.Q()) & (models.Q | models.Q())))]

and we want to ensure that we didn't mess up in check condition so the test case goes like this

with raises(IntegrityError):
    Foo.objects.create()

wdyt?

point2:

Additionally, we can have “class-based” services, which is a fancy way of saying - wrap the logic in a class. (here) As stated in the comment, we are using this approach for 2 main reasons:

  1. Namespace. We have a single namespace for our create & update.
  2. Reuse of the _infer_file_name_and_type logic.

don't you think that mentioned reasoning is still weak enough to implement a class because of it? f.e a separate python file provides good enough namespacing and we can achive the same just via functions what do you thing about the following cases when a class migh be useful?:

  • there is a shared component which needs to be instantiated only once and used across other service functionality
  • there is a use-case of methods chaining (similar to querysets)

in the conjunction the mentioned points look like this:

class ImageProcessingService:
    def __init__(self, img, settings={}):
        self._img = img
        self._img_processor = ImageProcessor(**settings)

    .....

ImageProcessingService(img).rotate(degrees=90).add_border(px=1, color='red')

^ in this case it's harder to operate only with functions, because we'll need to pass ImageProcessor to all of them (or create a separate one upon each func call); we can skip passing output img between diff func calls, because we have everything stored in the class obj prop

point3:

2 important things to point out here:

  1. We are importing the task (which has the same name as the service), but we are giving it a _task suffix.
  2. And when the transaction commits, we’ll call the task.

what do you think about not calling celery tasks directly in the code, but create call wrappers for all of them? using tasks in a way of .._task.delay() feels way too celery specific, so maybe we can avoid this by doing the following:

/services.py
def foo_create(): ...

/tasks.py
@shared_task
def foo_create_task():
    from services import foo_create
    foo_create()

/services.py
def foo_create_async():  # always use this instead of the task itself
    from tasks import foo_create_task
    transaction.on_commit(lambda: foo_create_task.delay())

the reasoning is:

  • caller do not care which lib is used, it just knows that the service call is async (under the hood it might be driven by celery/rq/threading/etc)
  • mocking in tests is simplified (we do not care about patching exactly .delay method)
  • we do not import anything from tasks folder every time and it remains just a registry of things, specific only to celery

let me know what you think regarding all this! will be happy to hear your thoughts cheers!

Horbatenko avatar Nov 22 '22 17:11 Horbatenko

@Horbatenko hello :wave:

About the model with complex constraints:

Yes! If you have something that's non-standard / non-trivial, make sure to test it properly. I'm covering exactly this here - https://www.youtube.com/watch?v=PChaEAIsQls (DjangoCon Europe, 2022 👀)

Additionally, with the latest Django, it'll raise a ValidationError, which is great (context - https://twitter.com/Rado_g/status/1587799386859479044)


About class-based services:

  1. I agree that in the end, it's a matter of personal choice for how to namespace your things. For me, classes are more compact than modules.
  2. If your class-service requires an instance, I'd add a class method to construct it. Something like: ClassBasedService.from_x(X).do_some_actions(). This way you'll have the compactness of a function call :+1:
  3. Additionally, if your service does not make sense to be instantiated, you can work with either class methods or static methods & use the class only for namespacing / encapsulation. This also works fine :+1:

The end goal here is to have enough tools, to keep things cohesive. Sometimes this can be a function, or a single module, or a single class or a larger module.

What I often do is the following:

  1. Start simple with functions
  2. When I have a rough idea about the implementation & boundaries, I can start thinking about quick refactoring towards something else (a class, for example)

I can agree with that. If calling Celery directly "pokes your eyes (it's a saying in :bulgaria: )", then you can go ahead and wrap that :+1:

Few thoughts here:

  1. For me, the added extra level of indirection is not necessarily a benefit, since with Celery, I can easily grep for .delay() and find all places where this is happening.
  2. Around testing, I agree that mocking a function is way cleaner than mocking the .delay(). For us, specifically, we allow .delay() to be called (running Celery in-memory during tests) & then mock accordingly in the other services, that are doing something external, because we use Celery only as a wrapper around "execute this outside the request-response cycle" - https://github.com/HackSoftware/Django-Styleguide#celery

But again, if it makes sense for you and you & your team are going to feel better wrapping the Celery goes - do it :ok_hand:

For example - we have this exact same feeling towards React components coming from external UI libraries :D We wrap all components from MUI in our own, even if sometimes this means import-exporting them.

Hopefully, I've managed to provide some adequate answers for you :raised_hands:

RadoRado avatar Nov 23 '22 06:11 RadoRado

niice! thanks a lot for your valuable feedback and the shared materials, will check everything asap

pokes your eyes (it's a saying in 🇧🇬 )

haha we have the same one in 🇺🇦

Horbatenko avatar Nov 30 '22 18:11 Horbatenko