Posts

Showing posts from 2019

Django logging configuration

I wanted to configure logging in my django project. I had the following requirements: - All logs will be written to a file named app.log and the file will be rotated on each day - All error logs will be written to a file named app.error.log and the file will be rotated on each day - Logs will be written to console if DEBUG=True is set After experimenting with different configurations, I finally was able to achieve my goal using the following configuration. DJANGO_LOG_LEVEL = 'DEBUG' # need to change this value to enable/disable debug logs LOGGING = { 'version' : 1 , 'disable_existing_loggers' : False , 'formatters' : { 'simple' : { 'format' : '%(levelname)s %(asctime)s %(module)s %(funcName)s:%(lineno)d %(message)s' }, }, 'filters' : { 'require_debug_true' : { '()' : 'django.utils.log.RequireDebugTrue' , },

Unit testing of Spring Service with constructor dependencies

Constructor based dependency injection is the recommended way to use dependency injection in Spring. In this post I'm going to demonstrate how to write unit test of a service class which has dependencies on other beans e.g. repositories. Let's assume our service class is like the following: @Service class MyService { private final UserRepository userRepository;     private final AddressRepository addressRepository;     @Autowired     public MyService(UserRepository userRepository, AddressRepository addressRepository) {         this.userRepository = userRepository;         this.addressRepository = addressRepository;     }     public boolean isUserHasAddress(String username){     // omitting the method details, will return true always     return true;     } } Now we need to write unit test for the above class. Here is a way to do it: @RunWith(SpringRunner.class) public class MyServiceTest {     private MyService myService;     @MockBean     privat