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+ using var httpClient = new HttpClient ( mockHttpMessageHandler . Object ) ;
29+ httpClient . BaseAddress = new Uri ( "https://fake-auth.com" ) ;
30+
31+ var httpClientFactoryMock = new Mock < IHttpClientFactory > ( ) ;
32+ httpClientFactoryMock
33+ . Setup ( _ => _ . CreateClient ( ) )
34+ . Returns ( httpClient ) ;
35+
36+ return new OAuthSdkCredentials (
37+ httpClientFactoryMock . Object ,
38+ new Uri ( "https://fake-auth.com" ) ,
39+ "test_client_id" ,
40+ "test_client_secret" ,
41+ new HashSet < OAuthScope > ( )
42+ ) ;
43+ }
44+
45+ [ Fact ]
46+ public void ShouldReturnAuthorizationHeaderWhenTokenIsValid ( )
47+ {
48+ using var mockResponse = new HttpResponseMessage ( ) ;
49+ mockResponse . StatusCode = HttpStatusCode . OK ;
50+ mockResponse . Content = new StringContent (
51+ "{\" access_token\" : \" valid_token\" , \" token_type\" : \" Bearer\" , \" expires_in\" : 3600}" ,
52+ Encoding . UTF8 ,
53+ "application/json" ) ;
54+ var sdk = CreateSdkCredentials ( mockResponse ) ;
55+ sdk . InitAccess ( ) ;
56+
57+ var authorization = sdk . GetSdkAuthorization ( SdkAuthorizationType . OAuth ) ;
58+ Assert . NotNull ( authorization ) ;
59+
60+ string expectedHeader = $ "Bearer valid_token";
61+ string actualHeader = authorization . GetAuthorizationHeader ( ) ;
62+
63+ Assert . Equal ( expectedHeader , actualHeader ) ;
64+ }
65+
66+ [ Fact ]
67+ public void ShouldThrowExceptionWhenApiReturnsError ( )
68+ {
69+ using var mockResponse = new HttpResponseMessage ( ) ;
70+ mockResponse . StatusCode = HttpStatusCode . BadRequest ;
71+ mockResponse . Content = new StringContent (
72+ "{\" error\" : \" invalid_client\" }" ,
73+ Encoding . UTF8 ,
74+ "application/json" ) ;
75+ var sdk = CreateSdkCredentials ( mockResponse ) ;
76+
77+ Assert . Throws < CheckoutAuthorizationException > ( ( ) => sdk . InitAccess ( ) ) ;
78+ }
79+
80+ [ Fact ]
81+ public void ShouldThrowExceptionWhenResponseHasInvalidToken ( )
82+ {
83+ var response = new OAuthServiceResponse
84+ {
85+ AccessToken = null ,
86+ TokenType = "Bearer" ,
87+ ExpiresIn = 3600
88+ } ;
89+
90+ Assert . Throws < ArgumentException > ( ( ) => OAuthAccessToken . FromOAuthServiceResponse ( response ) ) ;
91+ }
92+ }
93+ }
0 commit comments