Skip to content

Commit 5f5738b

Browse files
authored
Add cadl-ranch tests (#3077)
1 parent 8bb3405 commit 5f5738b

File tree

14 files changed

+736
-92
lines changed

14 files changed

+736
-92
lines changed

eng/Generate.ps1

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,7 @@ $cadlRanchProjectDirectory = Join-Path $repoRoot 'test' 'CadlRanchProjects'
255255
$cadlRanchProjectPaths =
256256
'authentication/api-key',
257257
'authentication/oauth2',
258+
'authentication/union',
258259
'models/property-optional',
259260
'models/property-types',
260261
'models/usage'

src/AutoRest.CSharp/Properties/launchSettings.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,10 @@
172172
"commandName": "Project",
173173
"commandLineArgs": "--standalone $(SolutionDir)\\test\\CadlRanchProjects\\authentication\\oauth2\\Generated"
174174
},
175+
"cadl-authentication/union": {
176+
"commandName": "Project",
177+
"commandLineArgs": "--standalone $(SolutionDir)\\test\\CadlRanchProjects\\authentication\\union\\Generated"
178+
},
175179
"cadl-models/property-optional": {
176180
"commandName": "Project",
177181
"commandLineArgs": "--standalone $(SolutionDir)\\test\\CadlRanchProjects\\models\\property-optional\\Generated"
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT License.
3+
4+
using Azure.Core.Pipeline;
5+
using Azure.Core;
6+
using System.Collections.Generic;
7+
using System.Net;
8+
using System.Reflection;
9+
using System.Threading.Tasks;
10+
using System.Threading;
11+
using System;
12+
13+
namespace CadlRanchProjects.Tests
14+
{
15+
public class OAuth2TestHelper
16+
{
17+
public class MockCredential : TokenCredential
18+
{
19+
public override ValueTask<AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
20+
{
21+
return new(GetToken(requestContext, cancellationToken));
22+
}
23+
24+
public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
25+
{
26+
return new AccessToken(string.Join(" ", requestContext.Scopes), DateTimeOffset.MaxValue);
27+
}
28+
}
29+
30+
// Only for bypassing HTTPS check purpose
31+
public class MockBearerTokenAuthenticationPolicy : BearerTokenAuthenticationPolicy
32+
{
33+
private readonly HttpPipelineTransport _transport;
34+
35+
public MockBearerTokenAuthenticationPolicy(TokenCredential credential, IEnumerable<string> scopes, HttpPipelineTransport transport) : base(credential, scopes)
36+
{
37+
_transport = transport;
38+
}
39+
40+
public override ValueTask ProcessAsync(HttpMessage message, ReadOnlyMemory<HttpPipelinePolicy> pipeline)
41+
{
42+
return ProcessAsync(message, pipeline, true);
43+
}
44+
45+
public override void Process(HttpMessage message, ReadOnlyMemory<HttpPipelinePolicy> pipeline)
46+
{
47+
ProcessAsync(message, pipeline, false).EnsureCompleted();
48+
}
49+
50+
protected new async ValueTask ProcessNextAsync(HttpMessage message, ReadOnlyMemory<HttpPipelinePolicy> pipeline)
51+
{
52+
await _transport.ProcessAsync(message).ConfigureAwait(false);
53+
54+
var response = message.Response;
55+
Type responseType = response.GetType();
56+
PropertyInfo propInfo = responseType.GetProperty("IsError", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
57+
propInfo.SetValue(response, message.ResponseClassifier.IsErrorResponse(message));
58+
}
59+
60+
protected new void ProcessNext(HttpMessage message, ReadOnlyMemory<HttpPipelinePolicy> pipeline)
61+
{
62+
_transport.Process(message);
63+
}
64+
65+
private async ValueTask ProcessAsync(HttpMessage message, ReadOnlyMemory<HttpPipelinePolicy> pipeline, bool async)
66+
{
67+
if (async)
68+
{
69+
await AuthorizeRequestAsync(message).ConfigureAwait(false);
70+
await ProcessNextAsync(message, pipeline).ConfigureAwait(false);
71+
}
72+
else
73+
{
74+
AuthorizeRequest(message);
75+
ProcessNext(message, pipeline);
76+
}
77+
78+
// Check if we have received a challenge or we have not yet issued the first request.
79+
if (message.Response.Status == (int)HttpStatusCode.Unauthorized && message.Response.Headers.Contains(HttpHeader.Names.WwwAuthenticate))
80+
{
81+
// Attempt to get the TokenRequestContext based on the challenge.
82+
// If we fail to get the context, the challenge was not present or invalid.
83+
// If we succeed in getting the context, authenticate the request and pass it up the policy chain.
84+
if (async)
85+
{
86+
if (await AuthorizeRequestOnChallengeAsync(message).ConfigureAwait(false))
87+
{
88+
await ProcessNextAsync(message, pipeline).ConfigureAwait(false);
89+
}
90+
}
91+
else
92+
{
93+
if (AuthorizeRequestOnChallenge(message))
94+
{
95+
ProcessNext(message, pipeline);
96+
}
97+
}
98+
}
99+
}
100+
}
101+
}
102+
}

test/CadlRanchProjects.Tests/authentication-oauth2.cs

Lines changed: 1 addition & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,9 @@
66
using Azure;
77
using NUnit.Framework;
88
using Authentication.OAuth2;
9-
using Azure.Core.Pipeline;
109
using Azure.Core;
11-
using System.Collections.Generic;
12-
using System.Net;
13-
using System.Threading;
14-
using System;
15-
using System.Reflection;
1610
using NUnit.Framework.Internal;
11+
using static CadlRanchProjects.Tests.OAuth2TestHelper;
1712

1813
namespace CadlRanchProjects.Tests
1914
{
@@ -38,90 +33,5 @@ public Task Authentication_OAuth2_invalid() => Test((host) =>
3833
Assert.AreEqual(403, exception.Status);
3934
return Task.CompletedTask;
4035
});
41-
42-
public class MockCredential : TokenCredential
43-
{
44-
public override ValueTask<AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
45-
{
46-
return new(GetToken(requestContext, cancellationToken));
47-
}
48-
49-
public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
50-
{
51-
return new AccessToken(string.Join(" ", requestContext.Scopes), DateTimeOffset.MaxValue);
52-
}
53-
}
54-
55-
// Only for bypassing HTTPS check purpose
56-
public class MockBearerTokenAuthenticationPolicy : BearerTokenAuthenticationPolicy
57-
{
58-
private readonly HttpPipelineTransport _transport;
59-
60-
public MockBearerTokenAuthenticationPolicy(TokenCredential credential, IEnumerable<string> scopes, HttpPipelineTransport transport) : base(credential, scopes)
61-
{
62-
_transport = transport;
63-
}
64-
65-
public override ValueTask ProcessAsync(HttpMessage message, ReadOnlyMemory<HttpPipelinePolicy> pipeline)
66-
{
67-
return ProcessAsync(message, pipeline, true);
68-
}
69-
70-
public override void Process(HttpMessage message, ReadOnlyMemory<HttpPipelinePolicy> pipeline)
71-
{
72-
ProcessAsync(message, pipeline, false).EnsureCompleted();
73-
}
74-
75-
protected new async ValueTask ProcessNextAsync(HttpMessage message, ReadOnlyMemory<HttpPipelinePolicy> pipeline)
76-
{
77-
await _transport.ProcessAsync(message).ConfigureAwait(false);
78-
79-
var response = message.Response;
80-
Type responseType = response.GetType();
81-
PropertyInfo propInfo = responseType.GetProperty("IsError", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
82-
propInfo.SetValue(response, message.ResponseClassifier.IsErrorResponse(message));
83-
}
84-
85-
protected new void ProcessNext(HttpMessage message, ReadOnlyMemory<HttpPipelinePolicy> pipeline)
86-
{
87-
_transport.Process(message);
88-
}
89-
90-
private async ValueTask ProcessAsync(HttpMessage message, ReadOnlyMemory<HttpPipelinePolicy> pipeline, bool async)
91-
{
92-
if (async)
93-
{
94-
await AuthorizeRequestAsync(message).ConfigureAwait(false);
95-
await ProcessNextAsync(message, pipeline).ConfigureAwait(false);
96-
}
97-
else
98-
{
99-
AuthorizeRequest(message);
100-
ProcessNext(message, pipeline);
101-
}
102-
103-
// Check if we have received a challenge or we have not yet issued the first request.
104-
if (message.Response.Status == (int)HttpStatusCode.Unauthorized && message.Response.Headers.Contains(HttpHeader.Names.WwwAuthenticate))
105-
{
106-
// Attempt to get the TokenRequestContext based on the challenge.
107-
// If we fail to get the context, the challenge was not present or invalid.
108-
// If we succeed in getting the context, authenticate the request and pass it up the policy chain.
109-
if (async)
110-
{
111-
if (await AuthorizeRequestOnChallengeAsync(message).ConfigureAwait(false))
112-
{
113-
await ProcessNextAsync(message, pipeline).ConfigureAwait(false);
114-
}
115-
}
116-
else
117-
{
118-
if (AuthorizeRequestOnChallenge(message))
119-
{
120-
ProcessNext(message, pipeline);
121-
}
122-
}
123-
}
124-
}
125-
}
12636
}
12737
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT License.
3+
4+
using System.Threading.Tasks;
5+
using Authentication.Union;
6+
using AutoRest.TestServer.Tests.Infrastructure;
7+
using Azure;
8+
using Azure.Core;
9+
using NUnit.Framework;
10+
using static CadlRanchProjects.Tests.OAuth2TestHelper;
11+
12+
namespace CadlRanchProjects.Tests
13+
{
14+
public class AuthenticationUnionTests : CadlRanchTestBase
15+
{
16+
[Test]
17+
public Task Authentication_Union_validKey() => Test(async (host) =>
18+
{
19+
Response response = await new UnionClient(new AzureKeyCredential("valid-key"), host, null).ValidKeyAsync();
20+
Assert.AreEqual(204, response.Status);
21+
});
22+
23+
[Test]
24+
public Task Authentication_Union_validToken() => Test(async (host) =>
25+
{
26+
var options = new UnionClientOptions();
27+
options.AddPolicy(new MockBearerTokenAuthenticationPolicy(new MockCredential(), UnionClient.TokenScopes, options.Transport), HttpPipelinePosition.PerCall);
28+
Response response = await new UnionClient(new MockCredential(), host, options).ValidTokenAsync();
29+
Assert.AreEqual(204, response.Status);
30+
});
31+
}
32+
}

test/CadlRanchProjects.Tests/models-property-optional.cs

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,6 @@ public Task Models_Property_Optional_Datetime_getDefault() => Test(async (host)
9393
});
9494

9595
[Test]
96-
[Ignore("Need cadl ranch fix")]
9796
public Task Models_Property_Optional_Datetime_putAll() => Test(async (host) =>
9897
{
9998
DatetimeProperty data = new()
@@ -210,5 +209,42 @@ public Task Models_Property_Optional_CollectionsModel_putDefault() => Test(async
210209
Response response = await new OptionalClient(host, null).GetCollectionsModelClient().PutDefaultAsync(new CollectionsModelProperty().ToRequestContent());
211210
Assert.AreEqual(204, response.Status);
212211
});
212+
213+
[Test]
214+
public Task Models_Property_Optional_RequiredAndOptional_getAll() => Test(async (host) =>
215+
{
216+
Response response = await new OptionalClient(host, null).GetRequiredAndOptionalClient().GetAllAsync();
217+
var result = RequiredAndOptionalProperty.FromResponse(response);
218+
Assert.AreEqual("hello", result.OptionalProperty);
219+
Assert.AreEqual(42, result.RequiredProperty);
220+
});
221+
222+
[Test]
223+
public Task Models_Property_Optional_RequiredAndOptional_getRequiredOnly() => Test(async (host) =>
224+
{
225+
Response response = await new OptionalClient(host, null).GetRequiredAndOptionalClient().GetRequiredOnlyAsync();
226+
var result = RequiredAndOptionalProperty.FromResponse(response);
227+
Assert.AreEqual(null, result.OptionalProperty);
228+
Assert.AreEqual(42, result.RequiredProperty);
229+
});
230+
231+
[Test]
232+
public Task Models_Property_Optional_RequiredAndOptional_putAll() => Test(async (host) =>
233+
{
234+
var content = new RequiredAndOptionalProperty(42)
235+
{
236+
OptionalProperty = "hello"
237+
};
238+
239+
Response response = await new OptionalClient(host, null).GetRequiredAndOptionalClient().PutAllAsync(content.ToRequestContent());
240+
Assert.AreEqual(204, response.Status);
241+
});
242+
243+
[Test]
244+
public Task Models_Property_Optional_RequiredAndOptional_putRequiredOnly() => Test(async (host) =>
245+
{
246+
Response response = await new OptionalClient(host, null).GetRequiredAndOptionalClient().PutRequiredOnlyAsync(new RequiredAndOptionalProperty(42));
247+
Assert.AreEqual(204, response.Status);
248+
});
213249
}
214250
}

test/CadlRanchProjects.Tests/models-property-types.cs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,5 +214,20 @@ public Task Models_Property_Types_DictionaryString_put() => Test(async (host) =>
214214
Response response = await new TypesClient(host, null).GetDictionaryStringClient().PutAsync(new DictionaryStringProperty(new Dictionary<string, string> { ["k1"] = "hello", ["k2"] = "world" }).ToRequestContent());
215215
Assert.AreEqual(204, response.Status);
216216
});
217+
218+
[Test]
219+
public Task Models_Property_Types_Never_get() => Test(async (host) =>
220+
{
221+
Response response = await new TypesClient(host, null).GetNeverClient().GetNeverAsync();
222+
var result = NeverProperty.FromResponse(response);
223+
Assert.NotNull(result);
224+
});
225+
226+
[Test]
227+
public Task Models_Property_Types_Never_put() => Test(async (host) =>
228+
{
229+
Response response = await new TypesClient(host, null).GetNeverClient().PutAsync(new NeverProperty().ToRequestContent());
230+
Assert.AreEqual(204, response.Status);
231+
});
217232
}
218233
}

test/CadlRanchProjects/authentication/union/Generated/Configuration.json

Lines changed: 10 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<doc>
3+
<members>
4+
<member name="ValidKeyAsync(RequestContext)">
5+
<example>
6+
This sample shows how to call ValidKeyAsync.
7+
<code><![CDATA[
8+
var credential = new AzureKeyCredential("<key>");
9+
var client = new UnionClient(credential);
10+
11+
Response response = await client.ValidKeyAsync();
12+
Console.WriteLine(response.Status);
13+
]]></code>
14+
</example>
15+
</member>
16+
<member name="ValidKey(RequestContext)">
17+
<example>
18+
This sample shows how to call ValidKey.
19+
<code><![CDATA[
20+
var credential = new AzureKeyCredential("<key>");
21+
var client = new UnionClient(credential);
22+
23+
Response response = client.ValidKey();
24+
Console.WriteLine(response.Status);
25+
]]></code>
26+
</example>
27+
</member>
28+
<member name="ValidTokenAsync(RequestContext)">
29+
<example>
30+
This sample shows how to call ValidTokenAsync.
31+
<code><![CDATA[
32+
var credential = new AzureKeyCredential("<key>");
33+
var client = new UnionClient(credential);
34+
35+
Response response = await client.ValidTokenAsync();
36+
Console.WriteLine(response.Status);
37+
]]></code>
38+
</example>
39+
</member>
40+
<member name="ValidToken(RequestContext)">
41+
<example>
42+
This sample shows how to call ValidToken.
43+
<code><![CDATA[
44+
var credential = new AzureKeyCredential("<key>");
45+
var client = new UnionClient(credential);
46+
47+
Response response = client.ValidToken();
48+
Console.WriteLine(response.Status);
49+
]]></code>
50+
</example>
51+
</member>
52+
</members>
53+
</doc>

0 commit comments

Comments
 (0)