Skip to content

Commit 0f5e411

Browse files
committed
Resolve conflicts and clean up code
1 parent 7ed25ed commit 0f5e411

File tree

11 files changed

+142
-153
lines changed

11 files changed

+142
-153
lines changed

src/Microsoft.OpenApi/Reader/OpenApiModelFactory.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ public static async Task<ReadResult> LoadAsync(Stream input, string format, Open
112112
bufferedStream.Position = 0;
113113
}
114114

115-
using var reader = new StreamReader(bufferedStream);
115+
using var reader = new StreamReader(bufferedStream, default, true, -1, settings.LeaveStreamOpen);
116116
return await LoadAsync(reader, format, settings, cancellationToken);
117117
}
118118

src/Microsoft.OpenApi/Reader/V2/OpenApiResponseDeserializer.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright (c) Microsoft Corporation. All rights reserved.
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
22
// Licensed under the MIT license.
33

44
using System;
@@ -133,7 +133,7 @@ private static Dictionary<string, OpenApiExample> LoadExamplesExtension(ParseNod
133133
example.Description = valueNode.Value.GetScalarValue();
134134
break;
135135
case "value":
136-
example.Value = OpenApiAnyConverter.GetSpecificOpenApiAny(valueNode.Value.CreateAny());
136+
example.Value = valueNode.Value.CreateAny();
137137
break;
138138
case "externalValue":
139139
example.ExternalValue = valueNode.Value.GetScalarValue();

src/Microsoft.OpenApi/Validations/OpenApiValidator.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+

12
// Copyright (c) Microsoft Corporation. All rights reserved.
23
// Licensed under the MIT license.
34

@@ -293,15 +294,15 @@ private void Validate(object item, Type type)
293294
}
294295

295296
// Validate unresolved references as references
296-
if (item is IOpenApiReferenceable {UnresolvedReference: true})
297+
if (item is IOpenApiReferenceable { UnresolvedReference: true })
297298
{
298299
type = typeof(IOpenApiReferenceable);
299300
}
300301

301-
var rules = _ruleSet.FindRules(type.Name);
302+
var rules = _ruleSet.FindRules(type);
302303
foreach (var rule in rules)
303304
{
304-
rule.Evaluate(this as IValidationContext, item);
305+
rule.Evaluate(this, item);
305306
}
306307
}
307308
}

src/Microsoft.OpenApi/Validations/Rules/JsonSchemaRules.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright (c) Microsoft Corporation. All rights reserved.
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
22
// Licensed under the MIT license.
33

44
using System.Collections.Generic;
@@ -21,7 +21,7 @@ public static class JsonSchemaRules
2121
/// Validate the data matches with the given data type.
2222
/// </summary>
2323
public static ValidationRule<JsonSchema> SchemaMismatchedDataType =>
24-
new ValidationRule<JsonSchema>(
24+
new ValidationRule<JsonSchema>(nameof(SchemaMismatchedDataType),
2525
(context, jsonSchema) =>
2626
{
2727
// default
@@ -79,7 +79,7 @@ public static class JsonSchemaRules
7979
/// Validates Schema Discriminator
8080
/// </summary>
8181
public static ValidationRule<JsonSchema> ValidateSchemaDiscriminator =>
82-
new ValidationRule<JsonSchema>(
82+
new ValidationRule<JsonSchema>(nameof(ValidateSchemaDiscriminator),
8383
(context, jsonSchema) =>
8484
{
8585
// discriminator

src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs

Lines changed: 36 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
// Copyright (c) Microsoft Corporation. All rights reserved.
1+

2+
// Copyright (c) Microsoft Corporation. All rights reserved.
23
// Licensed under the MIT license.
34

45
using System;
@@ -8,6 +9,7 @@
89
using Microsoft.OpenApi.Exceptions;
910
using Microsoft.OpenApi.Properties;
1011
using Microsoft.OpenApi.Validations.Rules;
12+
using System.Data;
1113

1214
namespace Microsoft.OpenApi.Validations
1315
{
@@ -16,16 +18,12 @@ namespace Microsoft.OpenApi.Validations
1618
/// </summary>
1719
public sealed class ValidationRuleSet
1820
{
19-
private Dictionary<string, IList<ValidationRule>> _rulesDictionary = new();
21+
private Dictionary<Type, IList<ValidationRule>> _rulesDictionary = new();
2022

2123
private static ValidationRuleSet _defaultRuleSet;
2224

2325
private List<ValidationRule> _emptyRules = new();
2426

25-
/// <summary>
26-
/// Gets the keys in this rule set.
27-
/// </summary>
28-
public ICollection<string> Keys => _rulesDictionary.Keys;
2927

3028
/// <summary>
3129
/// Gets the rules in this rule set.
@@ -45,13 +43,13 @@ public ValidationRuleSet()
4543
}
4644

4745
/// <summary>
48-
/// Retrieve the rules that are related to a specific key.
46+
/// Retrieve the rules that are related to a specific type
4947
/// </summary>
50-
/// <param name="key">The key of the rules to search for.</param>
51-
/// <returns>Either the rules related to the given key, or an empty list.</returns>
52-
public IList<ValidationRule> FindRules(string key)
48+
/// <param name="type">The type that is to be validated</param>
49+
/// <returns>Either the rules related to the type, or an empty list.</returns>
50+
public IList<ValidationRule> FindRules(Type type)
5351
{
54-
_rulesDictionary.TryGetValue(key, out var results);
52+
_rulesDictionary.TryGetValue(type, out var results);
5553
return results ?? _emptyRules;
5654
}
5755

@@ -92,7 +90,7 @@ public static ValidationRuleSet GetEmptyRuleSet()
9290
/// <param name="ruleSet">The rule set to add validation rules to.</param>
9391
/// <param name="rules">The validation rules to be added to the rules set.</param>
9492
/// <exception cref="OpenApiException">Throws a null argument exception if the arguments are null.</exception>
95-
public static void AddValidationRules(ValidationRuleSet ruleSet, IDictionary<string, IList<ValidationRule>> rules)
93+
public static void AddValidationRules(ValidationRuleSet ruleSet, IDictionary<Type, IList<ValidationRule>> rules)
9694
{
9795
if (ruleSet == null || rules == null)
9896
{
@@ -118,15 +116,15 @@ public ValidationRuleSet(ValidationRuleSet ruleSet)
118116

119117
foreach (var rule in ruleSet)
120118
{
121-
Add(rule.ElementType.Name, rule);
119+
Add(rule.ElementType, rule);
122120
}
123121
}
124122

125123
/// <summary>
126124
/// Initializes a new instance of the <see cref="ValidationRuleSet"/> class.
127125
/// </summary>
128126
/// <param name="rules">Rules to be contained in this ruleset.</param>
129-
public ValidationRuleSet(IDictionary<string, IList<ValidationRule>> rules)
127+
public ValidationRuleSet(IDictionary<Type, IList<ValidationRule>> rules)
130128
{
131129
if (rules == null)
132130
{
@@ -144,7 +142,7 @@ public ValidationRuleSet(IDictionary<string, IList<ValidationRule>> rules)
144142
/// </summary>
145143
/// <param name="key">The key for the rule.</param>
146144
/// <param name="rules">The list of rules.</param>
147-
public void Add(string key, IList<ValidationRule> rules)
145+
public void Add(Type key, IList<ValidationRule> rules)
148146
{
149147
foreach (var rule in rules)
150148
{
@@ -158,7 +156,7 @@ public void Add(string key, IList<ValidationRule> rules)
158156
/// <param name="key">The key for the rule.</param>
159157
/// <param name="rule">The rule.</param>
160158
/// <exception cref="OpenApiException">Exception thrown when rule already exists.</exception>
161-
public void Add(string key, ValidationRule rule)
159+
public void Add(Type key, ValidationRule rule)
162160
{
163161
if (!_rulesDictionary.ContainsKey(key))
164162
{
@@ -180,7 +178,7 @@ public void Add(string key, ValidationRule rule)
180178
/// <param name="newRule">The new rule.</param>
181179
/// <param name="oldRule">The old rule.</param>
182180
/// <returns>true, if the update was successful; otherwise false.</returns>
183-
public bool Update(string key, ValidationRule newRule, ValidationRule oldRule)
181+
public bool Update(Type key, ValidationRule newRule, ValidationRule oldRule)
184182
{
185183
if (_rulesDictionary.TryGetValue(key, out var currentRules))
186184
{
@@ -195,18 +193,33 @@ public bool Update(string key, ValidationRule newRule, ValidationRule oldRule)
195193
/// </summary>
196194
/// <param name="key">The key of the collection of rules to be removed.</param>
197195
/// <returns>true if the collection of rules with the provided key is removed; otherwise, false.</returns>
198-
public bool Remove(string key)
196+
public bool Remove(Type key)
199197
{
200198
return _rulesDictionary.Remove(key);
201199
}
202200

201+
/// <summary>
202+
/// Remove a rule by its name from all types it is used by.
203+
/// </summary>
204+
/// <param name="ruleName">Name of the rule.</param>
205+
public void Remove(string ruleName)
206+
{
207+
foreach (KeyValuePair<Type, IList<ValidationRule>> rule in _rulesDictionary)
208+
{
209+
_rulesDictionary[rule.Key] = rule.Value.Where(vr => !vr.Name.Equals(ruleName, StringComparison.Ordinal)).ToList();
210+
}
211+
212+
// Remove types with no rule
213+
_rulesDictionary = _rulesDictionary.Where(r => r.Value.Any()).ToDictionary(r => r.Key, r => r.Value);
214+
}
215+
203216
/// <summary>
204217
/// Removes a rule by key.
205218
/// </summary>
206219
/// <param name="key">The key of the rule to be removed.</param>
207220
/// <param name="rule">The rule to be removed.</param>
208221
/// <returns>true if the rule is successfully removed; otherwise, false.</returns>
209-
public bool Remove(string key, ValidationRule rule)
222+
public bool Remove(Type key, ValidationRule rule)
210223
{
211224
if (_rulesDictionary.TryGetValue(key, out IList<ValidationRule> validationRules))
212225
{
@@ -239,7 +252,7 @@ public void Clear()
239252
/// </summary>
240253
/// <param name="key">The key to locate in the rule set.</param>
241254
/// <returns>true if the rule set contains an element with the key; otherwise, false.</returns>
242-
public bool ContainsKey(string key)
255+
public bool ContainsKey(Type key)
243256
{
244257
return _rulesDictionary.ContainsKey(key);
245258
}
@@ -250,7 +263,7 @@ public bool ContainsKey(string key)
250263
/// <param name="key">The key to locate.</param>
251264
/// <param name="rule">The rule to locate.</param>
252265
/// <returns></returns>
253-
public bool Contains(string key, ValidationRule rule)
266+
public bool Contains(Type key, ValidationRule rule)
254267
{
255268
return _rulesDictionary.TryGetValue(key, out IList<ValidationRule> validationRules) && validationRules.Contains(rule);
256269
}
@@ -263,35 +276,11 @@ public bool Contains(string key, ValidationRule rule)
263276
/// key is found; otherwise, an empty <see cref="IList{ValidationRule}"/> object.
264277
/// This parameter is passed uninitialized.</param>
265278
/// <returns>true if the specified key has rules.</returns>
266-
public bool TryGetValue(string key, out IList<ValidationRule> rules)
279+
public bool TryGetValue(Type key, out IList<ValidationRule> rules)
267280
{
268281
return _rulesDictionary.TryGetValue(key, out rules);
269282
}
270283

271-
/// <summary>
272-
/// Remove a rule by its name from all types it is used by.
273-
/// </summary>
274-
/// <param name="ruleName">Name of the rule.</param>
275-
public void Remove(string ruleName)
276-
{
277-
foreach (KeyValuePair<Type, IList<ValidationRule>> rule in _rules)
278-
{
279-
_rules[rule.Key] = rule.Value.Where(vr => !vr.Name.Equals(ruleName, StringComparison.Ordinal)).ToList();
280-
}
281-
282-
// Remove types with no rule
283-
_rules = _rules.Where(r => r.Value.Any()).ToDictionary(r => r.Key, r => r.Value);
284-
}
285-
286-
/// <summary>
287-
/// Remove a rule by element type.
288-
/// </summary>
289-
/// <param name="type">Type of the rule.</param>
290-
public void Remove(Type type)
291-
{
292-
_rules.Remove(type);
293-
}
294-
295284
/// <summary>
296285
/// Get the enumerator.
297286
/// </summary>
@@ -324,7 +313,7 @@ private static ValidationRuleSet BuildDefaultRuleSet()
324313
var propertyValue = property.GetValue(null); // static property
325314
if (propertyValue is ValidationRule rule)
326315
{
327-
ruleSet.Add(rule.ElementType.Name, rule);
316+
ruleSet.Add(rule.ElementType, rule);
328317
}
329318
}
330319

test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiStreamReaderTests.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,7 @@ public async void StreamShouldNotBeDisposedIfLeaveStreamOpenSettingIsTrue()
4545
memoryStream.Position = 0;
4646
var stream = memoryStream;
4747

48-
var reader = new OpenApiStreamReader(new() { LeaveStreamOpen = true });
49-
_ = await reader.ReadAsync(stream);
48+
var result = OpenApiDocument.Load(stream, "yaml", new OpenApiReaderSettings { LeaveStreamOpen = true });
5049
stream.Seek(0, SeekOrigin.Begin); // does not throw an object disposed exception
5150
Assert.True(stream.CanRead);
5251
}

test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiOperationTests.cs

Lines changed: 27 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright (c) Microsoft Corporation. All rights reserved.
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
22
// Licensed under the MIT license.
33

44
using System.Collections.Generic;
@@ -9,10 +9,13 @@
99
using Json.Schema;
1010
using Microsoft.OpenApi.Any;
1111
using Microsoft.OpenApi.Extensions;
12+
using Microsoft.OpenApi.Interfaces;
1213
using Microsoft.OpenApi.Models;
1314
using Microsoft.OpenApi.Reader.ParseNodes;
1415
using Microsoft.OpenApi.Reader.V2;
16+
using Microsoft.OpenApi.Reader.V3;
1517
using Microsoft.OpenApi.Tests;
18+
using Microsoft.OpenApi.Writers;
1619
using Xunit;
1720

1821
namespace Microsoft.OpenApi.Readers.Tests.V2Tests
@@ -305,36 +308,30 @@ public void ParseOperationWithEmptyProducesArraySetsResponseSchemaIfExists()
305308

306309
// Act
307310
var operation = OpenApiV2Deserializer.LoadOperation(node);
311+
var expected = @"{
312+
""produces"": [
313+
""application/octet-stream""
314+
],
315+
""responses"": {
316+
""200"": {
317+
""description"": ""OK"",
318+
""schema"": {
319+
""type"": ""string"",
320+
""description"": ""The content of the file."",
321+
""format"": ""binary"",
322+
""x-ms-summary"": ""File Content""
323+
}
324+
}
325+
}
326+
}";
327+
328+
var stringBuilder = new StringBuilder();
329+
var jsonWriter = new OpenApiJsonWriter(new StringWriter(stringBuilder));
330+
operation.SerializeAsV2(jsonWriter);
308331

309332
// Assert
310-
operation.Should().BeEquivalentTo(
311-
new OpenApiOperation
312-
{
313-
Responses = new()
314-
{
315-
{ "200", new()
316-
{
317-
Description = "OK",
318-
Content =
319-
{
320-
["application/octet-stream"] = new()
321-
{
322-
Schema = new()
323-
{
324-
Format = "binary",
325-
Description = "The content of the file.",
326-
Type = "string",
327-
Extensions =
328-
{
329-
["x-ms-summary"] = new OpenApiString("File Content")
330-
}
331-
}
332-
}
333-
}
334-
}}
335-
}
336-
}
337-
);
333+
var actual = stringBuilder.ToString();
334+
actual.MakeLineBreaksEnvironmentNeutral().Should().BeEquivalentTo(expected.MakeLineBreaksEnvironmentNeutral());
338335
}
339336

340337
[Fact]
@@ -349,7 +346,7 @@ public void ParseOperationWithBodyAndEmptyConsumesSetsRequestBodySchemaIfExists(
349346
var operation = OpenApiV2Deserializer.LoadOperation(node);
350347

351348
// Assert
352-
operation.Should().BeEquivalentTo(_operationWithBody);
349+
operation.Should().BeEquivalentTo(_operationWithBody, options => options.IgnoringCyclicReferences());
353350
}
354351

355352
[Fact]

0 commit comments

Comments
 (0)