1+ using Moq ;
2+ using Moq . Protected ;
3+ using System ;
4+ using System . Collections . Generic ;
5+ using System . Net ;
6+ using System . Net . Http ;
7+ using System . Text ;
8+ using System . Threading ;
9+ using System . Threading . Tasks ;
10+ using Xunit ;
11+
12+ namespace Checkout
13+ {
14+ public class OAuthSdkCredentialsTests
15+ {
16+ private OAuthSdkCredentials CreateSdkCredentials ( HttpResponseMessage mockResponse )
17+ {
18+ var mockHttpMessageHandler = new Mock < HttpMessageHandler > ( ) ;
19+
20+ mockHttpMessageHandler
21+ . Protected ( )
22+ . Setup < Task < HttpResponseMessage > > (
23+ "SendAsync" ,
24+ ItExpr . IsAny < HttpRequestMessage > ( ) ,
25+ ItExpr . IsAny < CancellationToken > ( ) )
26+ . ReturnsAsync ( mockResponse ) ;
27+
28+ var httpClient = new HttpClient ( mockHttpMessageHandler . Object )
29+ {
30+ BaseAddress = new Uri ( "https://fake-auth.com" )
31+ } ;
32+
33+ var httpClientFactoryMock = new Mock < IHttpClientFactory > ( ) ;
34+ httpClientFactoryMock
35+ . Setup ( _ => _ . CreateClient ( ) )
36+ . Returns ( httpClient ) ;
37+
38+ return new OAuthSdkCredentials (
39+ httpClientFactoryMock . Object ,
40+ new Uri ( "https://fake-auth.com" ) ,
41+ "test_client_id" ,
42+ "test_client_secret" ,
43+ new HashSet < OAuthScope > ( )
44+ ) ;
45+ }
46+
47+ [ Fact ]
48+ public void ShouldReturnAuthorizationHeaderWhenTokenIsValid ( )
49+ {
50+ var mockResponse = new HttpResponseMessage
51+ {
52+ StatusCode = HttpStatusCode . OK ,
53+ Content = new StringContent (
54+ "{\" access_token\" : \" valid_token\" , \" token_type\" : \" Bearer\" , \" expires_in\" : 3600}" ,
55+ Encoding . UTF8 ,
56+ "application/json" )
57+ } ;
58+
59+ var sdk = CreateSdkCredentials ( mockResponse ) ;
60+ sdk . InitAccess ( ) ;
61+
62+ var authorization = sdk . GetSdkAuthorization ( SdkAuthorizationType . OAuth ) ;
63+ Assert . NotNull ( authorization ) ;
64+
65+ string expectedHeader = $ "Bearer valid_token";
66+ string actualHeader = authorization . GetAuthorizationHeader ( ) ;
67+
68+ Assert . Equal ( expectedHeader , actualHeader ) ;
69+ }
70+
71+ [ Fact ]
72+ public void ShouldThrowExceptionWhenApiReturnsError ( )
73+ {
74+ var mockResponse = new HttpResponseMessage
75+ {
76+ StatusCode = HttpStatusCode . BadRequest ,
77+ Content = new StringContent (
78+ "{\" error\" : \" invalid_client\" }" ,
79+ Encoding . UTF8 ,
80+ "application/json" )
81+ } ;
82+
83+ var sdk = CreateSdkCredentials ( mockResponse ) ;
84+
85+ Assert . Throws < CheckoutAuthorizationException > ( ( ) => sdk . InitAccess ( ) ) ;
86+ }
87+
88+ [ Fact ]
89+ public void ShouldThrowExceptionWhenResponseHasInvalidToken ( )
90+ {
91+ var response = new OAuthServiceResponse
92+ {
93+ AccessToken = null ,
94+ TokenType = "Bearer" ,
95+ ExpiresIn = 3600
96+ } ;
97+
98+ Assert . Throws < ArgumentException > ( ( ) => OAuthAccessToken . FromOAuthServiceResponse ( response ) ) ;
99+ }
100+ }
101+ }
0 commit comments