You can't execute queries until the end of the 'atomic' block.

Kiyong Lee·2021년 11월 22일
0

Error

목록 보기
5/6

django.db.transaction.TransactionManagementError


언제 발생했는가?

Unit Test에서 Integrity Error 테스트 중에 발생


class TestSignUpView(TestCase) :
    def setUp(self) :
        User.objects.create(
            id       = 1,
            username = 'test',
            password = '1234'  
        )

...

    def test_fail_sign_up_raise_integrity_error(self) :
        client = Client()
        
        user = {
            'id'       : 2,
            'username' : 'test',
            'password' : '1234'
        }
        
        response = client.post("/users/signup", json.dumps(user), content_type='application/json')
        
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.json(), {'message': 'IntegrityError'})

...

django.db.transaction.TransactionManagementError: 
An error occurred in the current transaction. 
You can't execute queries until the end of the 'atomic' block.

기존 코드

class SignUpView(View) :
    def post(self, request) :
        try :
            data = json.loads(request.body)
        
            username = data['username']            
            password = bcrypt.hashpw(data['password'].encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
            
            User.objects.create(username = username, password = password)
            
            return JsonResponse({'message' : 'CREATE_USER'}, status=201)
        
        except KeyError :
            return JsonResponse({'message' : 'KeyError'}, status=400)

        except IntegrityError :
            return JsonResponse({'message' : 'IntegrityError'}, status=400)

회원가입에 대한 코드이며 User라는 모델은
username, password 두 개의 데이터를 받아서 저장한다.

그런데 usernameUnique=True로 설정되어 있어서,
회원가입할 때 이미 있는 거로 가입하려고 하면 integrity Error가 발생하도록 했다.


해결법

찾아보던 중, 해당 글을 따라하여 수정했는데, 방법은 간단했다.

django.testTestCase가 아닌 TransactionTestCase를 상속받아서
테스트해보라는 것이었다.

그래서 첫 부분 테스트케이스 상속 부분을 아래와 같이 바꾼다음 실행했더니

class TestSignUpView(TransactionTestCase) :

대박

profile
ISTJ인 K-개발자

0개의 댓글