@@ -492,8 +492,40 @@ def test_list_messages_supports_limit_offset_pagination(self):
492492 self .assertEqual (len (response .data ['results' ]), 1 )
493493 self .assertEqual (response .data ['count' ], 2 )
494494
495- def test_create_message_for_current_user (self ):
496- response = self .client .post (reverse ('user_messages-list' ), {
495+ def test_service_message_create (self ):
496+ from api .models import Application
497+ from urllib .parse import urlencode
498+
499+ # Setup application
500+ Application .objects .create (
501+ name = 'test_app' ,
502+ client_type = 'confidential' ,
503+ client_id = 'my_test_client_id' ,
504+ client_secret = 'my_test_client_secret' ,
505+ authorization_grant_type = 'client-credentials' ,
506+ user = self .user
507+ )
508+
509+ # 1. Fetch access token via client-credentials flow
510+ data = urlencode ({
511+ 'grant_type' : 'client_credentials' ,
512+ 'client_id' : 'my_test_client_id' ,
513+ 'client_secret' : 'my_test_client_secret' ,
514+ 'scope' : 'passport:message'
515+ })
516+
517+ token_response = self .client .post (
518+ '/oauth/token/' ,
519+ data = data ,
520+ content_type = 'application/x-www-form-urlencoded'
521+ )
522+
523+ self .assertEqual (token_response .status_code , 200 , token_response .json ())
524+ access_token = token_response .json ()['access_token' ]
525+
526+ # 2. Use the access token to create a message
527+ response = self .client .post ('/messages/' , {
528+ 'username' : self .user .username ,
497529 'category' : 'alert' ,
498530 'title' : 'Created from API' ,
499531 'content' : 'API created content' ,
@@ -502,12 +534,10 @@ def test_create_message_for_current_user(self):
502534 'is_read' : False ,
503535 'action_link' : '/messages' ,
504536 'action_text' : 'Open' ,
505- })
537+ }, HTTP_AUTHORIZATION = f'Bearer { access_token } ' )
506538
507- self .assertEqual (response .status_code , status .HTTP_201_CREATED )
508- created = Message .objects .get (id = response .data ['id' ])
509- self .assertEqual (created .user , self .user )
510- self .assertEqual (created .category , 'alert' )
539+ self .assertEqual (response .status_code , 201 )
540+ self .assertTrue (Message .objects .filter (user = self .user , title = 'Created from API' ).exists ())
511541
512542 def test_mark_all_messages_as_read (self ):
513543 response = self .client .put (reverse ('user_messages-mark-all-read' ))
0 commit comments