現在、unittestを使いテストの勉強をしています。
ログイン状態、ログアウト状態の場合のHTTPの値を期待通りに出したいと考えています。
色々なサイト様を拝見し、HTTPレスポンスが期待通り返ってくることができたのですが、ちゃんとした理解ができていないため、不明点をお伺いしたいと考えています。
以下、実際のテストコードです。
※ユーザーのPKを通常のIDからUUIDに変えています。
テストコード
失敗例1
python
1class Html_tests(TestCase): 2 def test_profile_after_login(self): 3 user = User( 4 username = 'test', 5 password = '1111' 6 ) 7 user.save() 8 c = Client() 9 p = c.post('/user/login/',{'username':'test','password':'1111'}) 10 uuid = user.uuid 11 url = '/user/profile/%s/' % uuid 12 response = p.get(url) 13 self.assertEqual(response.status_code, 200)
期待・・・HTTPレスポンス200が返ってくる。
結果・・・HTTPレスポンス302が返ってきました。
失敗例2
python
1 def test_profile_after_login(self): 2 user = User( 3 username = 'test', 4 password = '1111' 5 ) 6 user.save() 7 self.client.login(username='test', password='1111') 8 uuid = user.uuid 9 url = '/user/profile/%s/' % uuid 10 response = self.client.get(url) 11
期待・・・HTTPレスポンス200が返ってくる。
結果・・・HTTPレスポンス302が返ってきました。
成功例1
python
1class Html_tests(TestCase): 2 def test_profile_after_login(self): 3 s = User.objects.create_user( 4 username = 'test', 5 password = '1111', 6 ) 7 self.client.login(username='test', password='1111') 8 uuid = s.uuid 9 url = '/user/profile/%s/' % uuid 10 response = self.client.get(url) 11 self.assertEqual(response.status_code, 200) 12
期待・・・HTTPレスポンス200が返ってくる。
結果・・・HTTPレスポンス200が返ってきました。
成功例2
python
1class Html_tests(TestCase): 2 def test_profile_after_login(self): 3 s = User.objects.create_user( 4 username = 'test', 5 password = '1111', 6 ) 7 c = Client() 8 p = c.post('/user/login/',{'username':'test','password':'1111'}) 9 uuid = s.uuid 10 url = '/user/profile/%s/' % uuid 11 response = c.get(url) 12 self.assertEqual(response.status_code, 200) 13
期待・・・HTTPレスポンス200が返ってくる。
結果・・・HTTPレスポンス200が返ってきました。
不明点
- Userを作る際はcreate_user()を使用しないといけないのか?
→他のテスト(後述)で実際にユーザーが作られていると確認。
しかし、失敗例にあるようになぜかHTTPレスポンス302が返ってきてしまった。
class Usermodel_test(TestCase): def test_user_model(self): user = User( username = 'test', password = '1111', ) user.save() users = User.objects.all() self.assertEqual(users.count(), 1)
結果はTrueなのでちゃんとユーザーが作られていると思っています。
なぜこのようなテストを行う場合、create_user()を使わなければいけないのでしょうか?
どなたか、教えていただけますと幸いです。
よろしくお願いいたします。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。