Facebook
From przemek, 10 Months ago, written in Python.
Embed
Download Paste or View Raw
Hits: 164
  1. # serializers.py
  2.  
  3. class AccountDetailsSerializer(serializers.ModelSerializer):
  4.     """Account serializer - details."""
  5.  
  6.     authorized = UserSerializer(many=True, read_only=True)
  7.  
  8.     class Meta:
  9.         """Meta."""
  10.  
  11.         depth = 1
  12.         fields = ('text', 'authorized')
  13.         model = Account
  14.  
  15.     def create(self, validated_data):
  16.         """Create instance."""
  17.         authorized = validated_data.pop('authorized', [])
  18.         owner = self.context['request'].user
  19.         account_instance = Account.objects.create(**{
  20.             **validated_data,
  21.             **{'owner': owner},
  22.         })
  23.         account_instance.authorized.add(*authorized)
  24.         return account_instance
  25.  
  26.     def update(self, instance, validated_data):
  27.         """Update instance."""
  28.         # do sth with instance
  29.         return instance
  30.  
  31.     def validate(self, data):
  32.         """Validate data."""
  33.         authorized = self.initial_data.get('authorized', [])
  34.         data.update({'authorized': []})
  35.         unknown = []
  36.         for user in authorized:
  37.             try:
  38.                 data['authorized'].append(User.objects.get(id=user['id']))
  39.             except User.DoesNotExist:
  40.                 unknown.append(user['username'])
  41.         if unknown:
  42.             raise ValidationError(f"Users: {', '.join(unknown)}"
  43.                                   + " does not exists")
  44.         return data
  45.        
  46. # tests.py
  47.  
  48.     def setUp(self):
  49.         """."""
  50.         # creating test users etc.
  51.  
  52.     def test_create_account(self):
  53.         """."""
  54.         self.client.login(username='foo', password='foo')
  55.         # valid authorized user
  56.         payload = {'text': 'foo user\'s account #3',
  57.                    'authorized': [{'id': 2, 'username': 'bar'}]}
  58.         response = self.client.post('/api/accounts/',
  59.                                     json.dumps(payload),
  60.                                     content_type='application/json')
  61.         self.assertEquals(response.status_code, 201)
  62.         # invalid authorized user
  63.         payload = {'text': 'foo user\'s account #3',
  64.                    'authorized': [{'id': 4, 'username': 'qaz'}]}
  65.         response = self.client.post('/api/accounts/',
  66.                                     json.dumps(payload),
  67.                                     content_type='application/json')
  68.         self.assertEquals(response.status_code, 400)
  69.        
  70.     def test_update_account(self):
  71.         """."""
  72.         self.client.login(username='foo', password='foo')
  73.         payload = {'authorized': [{'id': 2, 'username': 'bar'}]}
  74.         response = self.client.patch('/api/accounts/1',
  75.                                      json.dumps(payload),
  76.                                      content_type='application/json',
  77.                                      follow=True)
  78.         print(response.json())

Replies to DRF tests rss

Title Name Language When
Re: DRF tests - działająca przemek python 10 Months ago.