Author Archives: James Lin
DIY load stop
Last DIY for 2022
Use “get” methods to help writing more testable code
Imagine you have the following code def do_something(): users = User.objects.filter(dob__gte='1980-01-01') for user in users: # do something to user If you were writing unit test against do_something(), you would need to do some complex mocking on User.objects.filter() to return some mock up data. But this can be easily prevented by refactoring into a separate… Read More »
Minimal Django script setup
import os, sys, pathlib # if script is in on 1 level deep # sys.path.append(str(pathlib.Path(__file__).parents[1].absolute())) sys.path.append(str(pathlib.Path(__file__).absolute())) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings") import django django.setup() # import your django models # do your django work
Notes about python logging
Consider the following code import logging logging.info('trying to log something') Executing above: It won’t log anything to console, because it default to level warning It won’t log anything to console, because no stream has been set import logging logging.basicConfig(level=logging.INFO) logging.info('trying to log something') logging.basicConfig(level=logging.DEBUG) logging.debug('trying to log something debug') Executing above: Running basicConfig(…) default adds… Read More »
Python instance method vs static method, which one to use on when?
I have been writing python OO for a while and every time when I create a method, I always ask myself, should this be instance method or staticmethod (or classmethod)? As you might already aware that the difference between instance method and static method is that static method doesn’t have access to the instance, same… Read More »
Meta class for DRF serializer to display JSON data
Then you can use it by:
Good references for writing tests
http://blog.codepipes.com/testing/software-testing-antipatterns.htm The above article talks about some anti-patterns in tests, personally I agree most of them especially anti-pattern on “Treating TDD as a religion”.