Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix integration tests #4657

Merged
merged 1 commit into from
May 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Put opening brace after property definition on new line, if property has getter and setter [#4625](https://github.com/microsoft/kiota/issues/4625)
- Put spaces correctly around dictionary entries [#4625](https://github.com/microsoft/kiota/issues/4625)
- Remove trailing space after class definition [#4625](https://github.com/microsoft/kiota/issues/4625)
- Fixes constructor generation for nullable properties that are initialized as null in C#,Java and PHP

## [1.14.0] - 2024-05-02

Expand Down
8 changes: 8 additions & 0 deletions src/Kiota.Builder/Writers/CSharp/CodeMethodWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@
writer.CloseBlock("};");
}
private const string ResultVarName = "result";
private void WriteFactoryMethodBodyForUnionModel(CodeMethod codeElement, CodeClass parentClass, CodeParameter parseNodeParameter, LanguageWriter writer)

Check warning on line 124 in src/Kiota.Builder/Writers/CSharp/CodeMethodWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Refactor this method to reduce its Cognitive Complexity from 20 to the 15 allowed. (https://rules.sonarsource.com/csharp/RSPEC-3776)
{
writer.WriteLine($"var {ResultVarName} = new {parentClass.Name.ToFirstCharacterUpperCase()}();");
var includeElse = false;
Expand All @@ -133,7 +133,7 @@
if (propertyType.TypeDefinition is CodeClass && !propertyType.IsCollection)
{
var mappedType = parentClass.DiscriminatorInformation.DiscriminatorMappings.FirstOrDefault(x => x.Value.Name.Equals(propertyType.Name, StringComparison.OrdinalIgnoreCase));
writer.WriteLine($"{(includeElse ? "else " : string.Empty)}if(\"{mappedType.Key}\".Equals({DiscriminatorMappingVarName}, StringComparison.OrdinalIgnoreCase))");

Check warning on line 136 in src/Kiota.Builder/Writers/CSharp/CodeMethodWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Define a constant instead of using this literal 'else ' 6 times. (https://rules.sonarsource.com/csharp/RSPEC-1192)
writer.WriteBlock(lines: $"{ResultVarName}.{property.Name.ToFirstCharacterUpperCase()} = new {conventions.GetTypeString(propertyType, codeElement)}();");
}
else if (propertyType.TypeDefinition is CodeClass && propertyType.IsCollection || propertyType.TypeDefinition is null || propertyType.TypeDefinition is CodeEnum)
Expand Down Expand Up @@ -248,6 +248,12 @@
{
defaultValue = $"{conventions.GetTypeString(propWithDefault.Type, currentMethod).TrimEnd('?')}.{defaultValue.Trim('"').CleanupSymbolName().ToFirstCharacterUpperCase()}";
}
// avoid setting null as a string.
if (propWithDefault.Type.IsNullable &&
defaultValue.TrimQuotes().Equals(NullValueString, StringComparison.OrdinalIgnoreCase))
{
defaultValue = NullValueString;
}
writer.WriteLine($"{propWithDefault.Name.ToFirstCharacterUpperCase()} = {defaultValue};");
}
if (parentClass.IsOfKind(CodeClassKind.RequestBuilder) &&
Expand All @@ -267,6 +273,8 @@
.ToArray());
}
}

private const string NullValueString = "null";
private string DefaultDeserializerValue => $"new Dictionary<string, Action<{conventions.ParseNodeInterfaceName}>>";
private void WriteDeserializerBody(bool shouldHide, CodeMethod codeElement, CodeClass parentClass, LanguageWriter writer)
{
Expand Down Expand Up @@ -605,7 +613,7 @@
var voidCorrectedTaskReturnType = code.IsAsync && isVoid ? string.Empty : returnType;
if (code.ReturnType.IsArray && code.IsOfKind(CodeMethodKind.RequestExecutor))
voidCorrectedTaskReturnType = $"IEnumerable<{voidCorrectedTaskReturnType.StripArraySuffix()}>";
// TODO: Task type should be moved into the refiner

Check warning on line 616 in src/Kiota.Builder/Writers/CSharp/CodeMethodWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Complete the task associated to this 'TODO' comment. (https://rules.sonarsource.com/csharp/RSPEC-1135)
var completeReturnType = isConstructor ?
string.Empty :
$"{asyncPrefix}{voidCorrectedTaskReturnType}{genericTypeSuffix} ";
Expand Down
7 changes: 7 additions & 0 deletions src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@
writer.WriteLine($"return new {parentClass.Name}({rawUrlParameter.Name}, {requestAdapterProperty.Name});");
}
private const string ResultVarName = "result";
private void WriteFactoryMethodBody(CodeMethod codeElement, CodeClass parentClass, LanguageWriter writer)

Check warning on line 118 in src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Refactor this method to reduce its Cognitive Complexity from 17 to the 15 allowed. (https://rules.sonarsource.com/csharp/RSPEC-3776)
{
var parseNodeParameter = codeElement.Parameters.OfKind(CodeParameterKind.ParseNode) ?? throw new InvalidOperationException("Factory method should have a ParseNode parameter");
if (parentClass.DiscriminatorInformation.ShouldWriteDiscriminatorForUnionType || parentClass.DiscriminatorInformation.ShouldWriteDiscriminatorForIntersectionType)
Expand Down Expand Up @@ -202,7 +202,7 @@
if (property.Type is CodeType propertyType)
{
var deserializationMethodName = $"{parseNodeParameter.Name}.{GetDeserializationMethodName(propertyType, codeElement)}";
writer.StartBlock($"{(includeElse ? "} else " : string.Empty)}if ({deserializationMethodName} != null) {{");

Check warning on line 205 in src/Kiota.Builder/Writers/Java/CodeMethodWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Define a constant instead of using this literal '} else ' 6 times. (https://rules.sonarsource.com/csharp/RSPEC-1192)
writer.WriteLine($"{ResultVarName}.{property.Setter!.Name}({deserializationMethodName});");
writer.DecreaseIndent();
}
Expand Down Expand Up @@ -358,6 +358,12 @@
{
defaultValue = $"{enumDefinition.Name}.forValue({defaultValue})";
}
// avoid setting null as a string.
if (propWithDefault.Type.IsNullable &&
defaultValue.TrimQuotes().Equals(NullValueString, StringComparison.OrdinalIgnoreCase))
{
defaultValue = NullValueString;
}
writer.WriteLine($"this.{setterName}({defaultValue});");
}
if (parentClass.IsOfKind(CodeClassKind.RequestBuilder) &&
Expand All @@ -376,6 +382,7 @@
.ToArray());
}
}
private const string NullValueString = "null";
private static void WriteSetterBody(CodeMethod codeElement, LanguageWriter writer, CodeClass parentClass)
{
if (parentClass.GetBackingStoreProperty() is not CodeProperty backingStore || (codeElement.AccessedProperty?.IsOfKind(CodePropertyKind.BackingStore) ?? false))
Expand Down
7 changes: 7 additions & 0 deletions src/Kiota.Builder/Writers/Php/CodeMethodWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -150,10 +150,17 @@
{
defaultValue = $"new {enumDefinition.Name.ToFirstCharacterUpperCase()}({defaultValue})";
}
// avoid setting null as a string.
if (propWithDefault.Type.IsNullable &&
defaultValue.TrimQuotes().Equals(NullValueString, StringComparison.OrdinalIgnoreCase))
{
defaultValue = NullValueString;
}
writer.WriteLine($"$this->{setterName}({defaultValue});");
}
}

private const string NullValueString = "null";
private void WriteRequestBuilderConstructorBody(CodeClass parentClass, CodeMethod currentMethod, LanguageWriter writer)
{
foreach (var propWithDefault in parentClass.GetPropertiesOfKind(
Expand Down Expand Up @@ -359,7 +366,7 @@
.ToArray();
foreach (var otherProp in otherProps)
{
writer.StartBlock($"{(includeElse ? "} else " : string.Empty)}if ($this->{otherProp.Getter!.Name.ToFirstCharacterLowerCase()}() !== null) {{");

Check warning on line 369 in src/Kiota.Builder/Writers/Php/CodeMethodWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Define a constant instead of using this literal '} else ' 6 times. (https://rules.sonarsource.com/csharp/RSPEC-1192)
WriteSerializationMethodCall(otherProp, writer, "null");
writer.DecreaseIndent();
if (!includeElse)
Expand All @@ -379,7 +386,7 @@
.Select(static x => $"$this->{x.Getter!.Name.ToFirstCharacterLowerCase()}()")
.Order(StringComparer.OrdinalIgnoreCase)
.Aggregate(static (x, y) => $"{x}, {y}");
WriteSerializationMethodCall(complexProperties.First(), writer, "null", propertiesNames);

Check warning on line 389 in src/Kiota.Builder/Writers/Php/CodeMethodWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Indexing at 0 should be used instead of the "Enumerable" extension method "First" (https://rules.sonarsource.com/csharp/RSPEC-6608)
if (includeElse)
{
writer.CloseBlock();
Expand Down Expand Up @@ -427,7 +434,7 @@
WriteSerializationMethodCall(otherProp, writer, $"'{otherProp.WireName}'");
}

private string GetSerializationMethodName(CodeTypeBase propType)

Check warning on line 437 in src/Kiota.Builder/Writers/Php/CodeMethodWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Refactor this method to reduce its Cognitive Complexity from 19 to the 15 allowed. (https://rules.sonarsource.com/csharp/RSPEC-3776)
{
var isCollection = propType.CollectionKind != CodeTypeBase.CodeTypeCollectionKind.None;
var propertyType = conventions.TranslateType(propType);
Expand Down Expand Up @@ -551,7 +558,7 @@
}

private static string GetPropertyCall(CodeProperty property, string defaultValue) => property == null ? defaultValue : $"$this->{property.Name}";
private void WriteRequestGeneratorBody(CodeMethod codeElement, RequestParams requestParams, CodeClass currentClass, LanguageWriter writer)

Check warning on line 561 in src/Kiota.Builder/Writers/Php/CodeMethodWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Refactor this method to reduce its Cognitive Complexity from 21 to the 15 allowed. (https://rules.sonarsource.com/csharp/RSPEC-3776)
{
if (codeElement.HttpMethod == null) throw new InvalidOperationException("http method cannot be null");
var requestInformationClass = "RequestInformation";
Expand Down Expand Up @@ -724,7 +731,7 @@
conventions.AddRequestBuilderBody(parentClass, returnType, writer, conventions.TempDictionaryVarName, pathParameters);
}

private void WriteRequestExecutorBody(CodeMethod codeElement, CodeClass parentClass, RequestParams requestParams, LanguageWriter writer)

Check warning on line 734 in src/Kiota.Builder/Writers/Php/CodeMethodWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Refactor this method to reduce its Cognitive Complexity from 16 to the 15 allowed. (https://rules.sonarsource.com/csharp/RSPEC-3776)
{
var generatorMethod = parentClass
.Methods
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1442,12 +1442,26 @@ public void WritesConstructor()
Name = "string"
},
});
var defaultValueNull = "\"null\"";
var nullPropName = "propWithDefaultNullValue";
parentClass.AddProperty(new CodeProperty
{
Name = nullPropName,
DefaultValue = defaultValueNull,
Kind = CodePropertyKind.Custom,
Type = new CodeType
{
Name = "int",
IsNullable = true
}
});
writer.Write(method);
var result = tw.ToString();
Assert.Contains("<summary>", result);
Assert.Contains("<see cref=", result);
Assert.Contains(parentClass.Name.ToFirstCharacterUpperCase(), result);
Assert.Contains($"{propName.ToFirstCharacterUpperCase()} = {defaultValue}", result);
Assert.Contains($"{nullPropName.ToFirstCharacterUpperCase()} = {defaultValueNull.TrimQuotes()}", result);
}
[Fact]
public void WritesWithUrl()
Expand Down
14 changes: 14 additions & 0 deletions tests/Kiota.Builder.Tests/Writers/Java/CodeMethodWriterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1787,6 +1787,19 @@ public void WritesConstructor()
Name = "String"
}
});
var defaultValueNull = "\"null\"";
var nullPropName = "propWithDefaultNullValue";
parentClass.AddProperty(new CodeProperty
{
Name = nullPropName,
DefaultValue = defaultValueNull,
Kind = CodePropertyKind.Custom,
Type = new CodeType
{
Name = "int",
IsNullable = true
}
});
AddRequestProperties();
method.AddParameter(new CodeParameter
{
Expand All @@ -1801,6 +1814,7 @@ public void WritesConstructor()
var result = tw.ToString();
Assert.Contains(parentClass.Name, result);
Assert.Contains($"this.set{propName.ToFirstCharacterUpperCase()}({defaultValue})", result);
Assert.Contains($"this.set{nullPropName.ToFirstCharacterUpperCase()}({defaultValueNull.TrimQuotes()})", result);
Assert.Contains("super", result);
}
[Fact]
Expand Down
15 changes: 14 additions & 1 deletion tests/Kiota.Builder.Tests/Writers/Php/CodeMethodWriterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1125,14 +1125,27 @@ public async Task WriteConstructorBody()
Type = new CodeType { Name = "countryCode", TypeDefinition = countryCode }
};
parentClass.AddProperty(propWithDefaultValue, enumProp);

var defaultValueNull = "\"null\"";
var nullPropName = "propWithDefaultNullValue";
parentClass.AddProperty(new CodeProperty
{
Name = nullPropName,
DefaultValue = defaultValueNull,
Kind = CodePropertyKind.Custom,
Type = new CodeType
{
Name = "int",
IsNullable = true
}
});
await ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.PHP }, root);
_codeMethodWriter.WriteCodeElement(constructor, languageWriter);
var result = stringWriter.ToString();

Assert.Contains("public function __construct", result);
Assert.Contains("$this->setType('#microsoft.graph.entity')", result);
Assert.Contains("$this->setCountryCode(new CountryCode('+254'));", result);
Assert.Contains("$this->setPropWithDefaultNullValue(null)", result);
}
[Fact]
public void DoesNotWriteConstructorWithDefaultFromComposedType()
Expand Down
Loading