Skip to content

Commit 1204455

Browse files
committed
adds unit tests
1 parent 7af3419 commit 1204455

File tree

5 files changed

+29
-151
lines changed

5 files changed

+29
-151
lines changed

src/Kiota.Builder/CodeDOM/CodeComposedTypeBase.cs

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -81,11 +81,4 @@ public DeprecationInformation? Deprecation
8181
set;
8282
}
8383

84-
public bool IsComposedOfPrimitives(Func<CodeType, CodeComposedTypeBase, bool> checkIfPrimitive) => Types.All(x => checkIfPrimitive(x, this));
85-
public bool IsComposedOfObjectsAndPrimitives(Func<CodeType, CodeComposedTypeBase, bool> checkIfPrimitive)
86-
{
87-
// Count the number of primitives in Types
88-
return Types.Any(x => checkIfPrimitive(x, this)) && Types.Any(x => !checkIfPrimitive(x, this));
89-
}
90-
9184
}

src/Kiota.Builder/Refiners/TypeScriptRefiner.cs

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
using Kiota.Builder.CodeDOM;
77
using Kiota.Builder.Configuration;
88
using Kiota.Builder.Extensions;
9-
using static Kiota.Builder.Writers.TypeScript.TypeScriptConventionService;
109

1110
namespace Kiota.Builder.Refiners;
1211
public class TypeScriptRefiner : CommonLanguageRefiner, ILanguageRefiner
@@ -21,10 +20,6 @@ public override Task RefineAsync(CodeNamespace generatedCode, CancellationToken
2120
cancellationToken.ThrowIfCancellationRequested();
2221
DeduplicateErrorMappings(generatedCode);
2322
RemoveMethodByKind(generatedCode, CodeMethodKind.RawUrlConstructor, CodeMethodKind.RawUrlBuilder);
24-
// Invoke the ConvertUnionTypesToWrapper method to maintain a consistent CodeDOM structure.
25-
// Note that in the later stages, specifically within the GenerateModelCodeFile() function, the introduced wrapper interface is disregarded.
26-
// Instead, a ComposedType is created, which has its own writer, along with the associated Factory, Serializer, and Deserializer functions
27-
// that are incorporated into the CodeFile.
2823
ConvertUnionTypesToWrapper(
2924
generatedCode,
3025
_configuration.UsesBackingStore,

src/Kiota.Builder/Writers/TypeScript/CodeFunctionWriter.cs

Lines changed: 5 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,8 @@ public override void WriteCodeElement(CodeFunction codeElement, LanguageWriter w
2222
if (codeElement.Parent is not CodeFile parentFile) throw new InvalidOperationException("the parent of a function should be a file");
2323

2424
var codeMethod = codeElement.OriginalLocalMethod;
25-
var composedType = GetOriginalComposedType(codeMethod.ReturnType);
26-
var isComposedOfPrimitives = composedType is not null && composedType.IsComposedOfPrimitives(conventions.IsPrimitiveType);
2725

28-
var returnType = codeMethod.Kind is CodeMethodKind.Factory && !isComposedOfPrimitives ?
26+
var returnType = codeMethod.Kind is CodeMethodKind.Factory ?
2927
FactoryMethodReturnType :
3028
conventions.GetTypeString(codeMethod.ReturnType, codeElement);
3129
var isVoid = "void".EqualsIgnoreCase(returnType);
@@ -53,12 +51,6 @@ public override void WriteCodeElement(CodeFunction codeElement, LanguageWriter w
5351
}
5452
}
5553

56-
private string GetSerializationMethodsForPrimitiveUnionTypes(CodeComposedTypeBase composedType, string parseNodeParameterName, CodeFunction codeElement, bool nodeParameterCanBeNull = true)
57-
{
58-
var optionalChainingSymbol = nodeParameterCanBeNull ? "?" : string.Empty;
59-
return string.Join(" ?? ", composedType.Types.Where(x => conventions.IsPrimitiveType(x, composedType)).Select(x => $"{parseNodeParameterName}{optionalChainingSymbol}." + conventions.GetDeserializationMethodName(x, codeElement.OriginalLocalMethod)));
60-
}
61-
6254
private static CodeParameter? GetComposedTypeParameter(CodeFunction codeElement)
6355
{
6456
return codeElement.OriginalLocalMethod.Parameters.FirstOrDefault(x => GetOriginalComposedType(x) is not null);
@@ -67,9 +59,9 @@ private string GetSerializationMethodsForPrimitiveUnionTypes(CodeComposedTypeBas
6759
private void WriteComposedTypeSerializer(CodeFunction codeElement, LanguageWriter writer, CodeParameter composedParam)
6860
{
6961
if (GetOriginalComposedType(composedParam) is not { } composedType) return;
70-
71-
if(composedParam.Type is CodeType codeType && codeType.TypeDefinition is CodeInterface codeInterface)
72-
{
62+
63+
if (composedParam.Type is CodeType { TypeDefinition: CodeInterface codeInterface })
64+
{
7365
var paramName = composedParam.Name.ToFirstCharacterLowerCase();
7466
writer.WriteLine($"if ({paramName} === undefined || {paramName} === null) return;");
7567
codeInterface.Properties
@@ -86,7 +78,6 @@ private void WriteComposedTypeSerializer(CodeFunction codeElement, LanguageWrite
8678

8779
if (composedType is CodeIntersectionType)
8880
{
89-
// fix me
9081
WriteSerializationFunctionForCodeIntersectionType(composedType, composedParam, codeElement, writer);
9182
return;
9283
}
@@ -205,10 +196,6 @@ private void WriteFactoryMethodBody(CodeFunction codeElement, string returnType,
205196

206197
switch (composedType)
207198
{
208-
case CodeComposedTypeBase type when type.IsComposedOfPrimitives(conventions.IsPrimitiveType):
209-
string primitiveValuesUnionString = GetSerializationMethodsForPrimitiveUnionTypes(composedType, parseNodeParameter!.Name.ToFirstCharacterLowerCase(), codeElement);
210-
writer.WriteLine($"return {primitiveValuesUnionString};");
211-
break;
212199
case CodeUnionType _ when parseNodeParameter != null:
213200
WriteDiscriminatorInformation(codeElement, parseNodeParameter, writer);
214201
// The default discriminator is useful when the discriminator information is not provided.
@@ -358,7 +345,6 @@ private void WritePropertySerializer(string modelParamName, CodeProperty codePro
358345
{
359346
var serializeName = GetSerializerAlias(propType, codeFunction, $"serialize{propType.TypeDefinition.Name}");
360347
if (propType.TypeDefinition is CodeComposedTypeBase ct)
361-
//if (GetOriginalComposedType(propType.TypeDefinition) is { } ct && (ct.IsComposedOfPrimitives(conventions.IsPrimitiveType) || ct.IsComposedOfObjectsAndPrimitives(conventions.IsPrimitiveType)))
362348
WriteSerializationStatementForComposedTypeProperty(ct, modelParamName, codeFunction, writer, codeProperty, serializeName);
363349
else
364350
writer.WriteLine($"writer.{serializationName}<{propTypeName}>(\"{codeProperty.WireName}\", {modelParamName}.{codePropertyName}{defaultValueSuffix}, {serializeName});");
@@ -374,11 +360,10 @@ private void WritePropertySerializationStatement(CodeProperty codeProperty, stri
374360
var isCollectionOfEnum = IsCollectionOfEnum(codeProperty);
375361
var spreadOperator = isCollectionOfEnum ? "..." : string.Empty;
376362
var codePropertyName = codeProperty.Name.ToFirstCharacterLowerCase();
377-
//var composedType = GetOriginalComposedType(codeProperty.Type);
378363

379364
if (!string.IsNullOrWhiteSpace(spreadOperator))
380365
writer.WriteLine($"if({modelParamName}.{codePropertyName})");
381-
if (codeProperty.Type is CodeComposedTypeBase composedType && (composedType.IsComposedOfPrimitives(conventions.IsPrimitiveType) || composedType.IsComposedOfObjectsAndPrimitives(conventions.IsPrimitiveType)))
366+
if (codeProperty.Type is CodeComposedTypeBase composedType && (composedType.Types.Any(x => conventions.IsPrimitiveType(x, composedType))))
382367
WriteSerializationStatementForComposedTypeProperty(composedType, modelParamName, codeFunction, writer, codeProperty, string.Empty);
383368
else
384369
writer.WriteLine($"writer.{serializationName}(\"{codeProperty.WireName}\", {spreadOperator}{modelParamName}.{codePropertyName}{defaultValueSuffix});");
@@ -444,8 +429,6 @@ private string GetSerializationMethodName(CodeTypeBase propertyType, CodeMethod
444429
ArgumentNullException.ThrowIfNull(method);
445430

446431
var composedType = GetOriginalComposedType(propertyType);
447-
if (composedType is not null && composedType.IsComposedOfPrimitives(conventions.IsPrimitiveType))
448-
return $"serialize{composedType.Name.ToFirstCharacterUpperCase()}";
449432

450433
var propertyTypeName = TranslateTypescriptType(propertyType);
451434
CodeType? currentType = composedType is not null ? GetCodeTypeForComposedType(composedType) : propertyType as CodeType;

tests/Kiota.Builder.Tests/Writers/TypeScript/CodeFunctionWriterTests.cs

Lines changed: 24 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1158,22 +1158,12 @@ public async Task Writes_UnionOfPrimitiveValues_FactoryFunctionAsync()
11581158
var modelCodeFile = modelsNS.FindChildByName<CodeFile>("primitivesRequestBuilder", false);
11591159
Assert.NotNull(modelCodeFile);
11601160

1161-
/*
1162-
\/**
1163-
* Creates a new instance of the appropriate class based on discriminator value
1164-
* @returns {ValidationError_errors_value}
1165-
*\/
1166-
export function createPrimitivesFromDiscriminatorValue(parseNode: ParseNode | undefined) : Primitives | undefined {
1167-
return parseNode?.getNumberValue() ?? parseNode?.getStringValue();
1168-
}
1169-
*/
1170-
11711161
// Test Factory function
11721162
var factoryFunction = modelCodeFile.GetChildElements().FirstOrDefault(x => x is CodeFunction function && GetOriginalComposedType(function.OriginalLocalMethod.ReturnType) is not null);
11731163
Assert.True(factoryFunction is not null);
11741164
writer.Write(factoryFunction);
11751165
var result = tw.ToString();
1176-
Assert.Contains("return parseNode?.getNumberValue() ?? parseNode?.getStringValue();", result);
1166+
Assert.Contains("return deserializeIntoPrimitives;", result);
11771167
AssertExtensions.CurlyBracesAreClosed(result, 1);
11781168
}
11791169

@@ -1251,11 +1241,10 @@ public async Task Writes_UnionOfPrimitiveValues_SerializerFunctionAsync()
12511241
Assert.True(serializerFunction is not null);
12521242
writer.Write(serializerFunction);
12531243
var serializerFunctionStr = tw.ToString();
1254-
Assert.Contains("return", serializerFunctionStr);
1255-
Assert.Contains("switch", serializerFunctionStr);
1256-
Assert.Contains("case \"number\":", serializerFunctionStr);
1257-
Assert.Contains("case \"string\":", serializerFunctionStr);
1258-
Assert.Contains("break", serializerFunctionStr);
1244+
Assert.Contains("if (!primitives) return {};", serializerFunctionStr);
1245+
Assert.Contains("return {", serializerFunctionStr);
1246+
Assert.Contains("\"double\": n => { primitives.double = n.getNumberValue(); },", serializerFunctionStr);
1247+
Assert.Contains("\"string\": n => { primitives.string = n.getStringValue(); },", serializerFunctionStr);
12591248
AssertExtensions.CurlyBracesAreClosed(serializerFunctionStr, 1);
12601249
}
12611250

@@ -1292,11 +1281,12 @@ public async Task Writes_UnionOfObjects_SerializerFunctionsAsync()
12921281
Assert.True(serializerFunction is not null);
12931282
writer.Write(serializerFunction);
12941283
var serializerFunctionStr = tw.ToString();
1295-
Assert.Contains("return", serializerFunctionStr);
1296-
Assert.Contains("switch", serializerFunctionStr);
1297-
Assert.Contains("case \"Cat\":", serializerFunctionStr);
1298-
Assert.Contains("case \"Dog\":", serializerFunctionStr);
1299-
Assert.Contains("break", serializerFunctionStr);
1284+
Assert.Contains("if (petsPatchRequestBody === undefined || petsPatchRequestBody === null) return;", serializerFunctionStr);
1285+
Assert.Contains("writer.writeObjectValue<Dog>(\"Dog\", petsPatchRequestBody.dog, serializeDog);", serializerFunctionStr);
1286+
Assert.Contains("writer.writeObjectValue<Cat>(\"Cat\", petsPatchRequestBody.cat, serializeCat);", serializerFunctionStr);
1287+
Assert.Contains("writer.writeObjectValue<Cat>(\"Cat\", petsPatchRequestBody.petsPatchRequestBodyCat, serializeCat);", serializerFunctionStr);
1288+
Assert.Contains("writer.writeObjectValue<Dog>(\"Dog\", petsPatchRequestBody.petsPatchRequestBodyDog, serializeDog);", serializerFunctionStr);
1289+
Assert.Contains("if (petsPatchRequestBody.petsPatchRequestBodyCat) {", serializerFunctionStr);
13001290
AssertExtensions.CurlyBracesAreClosed(serializerFunctionStr, 1);
13011291
}
13021292

@@ -1371,8 +1361,8 @@ public async Task Writes_CodeIntersectionType_DeserializerFunctionsAsync()
13711361
Assert.True(deserializerFunction is not null);
13721362
writer.Write(deserializerFunction);
13731363
var serializerFunctionStr = tw.ToString();
1374-
Assert.Contains("...deserializeIntoBar(fooBar as Bar),", serializerFunctionStr);
1375-
Assert.Contains("...deserializeIntoFoo(fooBar as Foo),", serializerFunctionStr);
1364+
Assert.Contains("\"bar\": n => { fooBar.bar = n.getObjectValue<Bar>(createBarFromDiscriminatorValue);", serializerFunctionStr);
1365+
Assert.Contains("\"foo\": n => { fooBar.foo = n.getObjectValue<Foo>(createFooFromDiscriminatorValue);", serializerFunctionStr);
13761366
AssertExtensions.CurlyBracesAreClosed(serializerFunctionStr, 1);
13771367
}
13781368

@@ -1409,8 +1399,8 @@ public async Task Writes_CodeIntersectionType_SerializerFunctionsAsync()
14091399
Assert.True(serializerFunction is not null);
14101400
writer.Write(serializerFunction);
14111401
var serializerFunctionStr = tw.ToString();
1412-
Assert.Contains("serializeBar(writer, fooBar as Bar);", serializerFunctionStr);
1413-
Assert.Contains("serializeFoo(writer, fooBar as Foo);", serializerFunctionStr);
1402+
Assert.Contains("writer.writeObjectValue<Bar>(\"Bar\", fooBar.bar, serializeBar);", serializerFunctionStr);
1403+
Assert.Contains("writer.writeObjectValue<Foo>(\"Foo\", fooBar.foo, serializeFoo);", serializerFunctionStr);
14141404
AssertExtensions.CurlyBracesAreClosed(serializerFunctionStr, 1);
14151405
}
14161406

@@ -1454,23 +1444,18 @@ public async Task Writes_CodeUnionBetweenObjectsAndPrimitiveTypes_SerializerAsyn
14541444
writer.Write(serializeFunction);
14551445
var result = tw.ToString();
14561446

1457-
Assert.Contains("case typeof parentClass.property === \"string\"", result);
1458-
Assert.Contains("writer.writeStringValue(\"property\", parentClass.property as string);", result);
1459-
Assert.Contains("case typeof parentClass.property === \"number\"", result);
1460-
Assert.Contains("writer.writeNumberValue(\"property\", parentClass.property as number);", result);
1447+
Assert.Contains("if (parentClass) {", result);
1448+
Assert.Contains("writer.writeStringValue(\"definedInParent\", parentClass.definedInParent);", result);
1449+
Assert.Contains("writer.writeCollectionOfPrimitiveValues<string>(\"dummyColl\", parentClass.dummyColl);", result);
14611450
Assert.Contains(
1462-
"writer.writeCollectionOfObjectValues<ArrayOfObjects>(\"property\", parentClass.property as ArrayOfObjects[] | undefined | null",
1451+
"writer.writeCollectionOfObjectValues<SomeComplexType>(\"dummyComplexColl\", parentClass.dummyComplexColl, serializeSomeComplexType);",
14631452
result);
14641453
Assert.Contains(
1465-
"writer.writeObjectValue<SingleObject>(\"property\", parentClass.property as SingleObject | undefined | null",
1454+
"writer.writeEnumValue<EnumType>(\"dummyEnumCollection\", parentClass.dummyEnumCollection);",
14661455
result);
1467-
Assert.Contains("writeStringValue", result);
1468-
Assert.Contains("writeCollectionOfPrimitiveValues", result);
1469-
Assert.Contains("writeCollectionOfObjectValues", result);
1470-
Assert.Contains("serializeSomeComplexType", result);
1471-
Assert.Contains("writeEnumValue", result);
1472-
Assert.Contains("writer.writeAdditionalData", result);
1473-
Assert.Contains("definedInParent", result, StringComparison.OrdinalIgnoreCase);
1456+
Assert.Contains("writer.writeStringValue(\"dummyProp\", parentClass.dummyProp);", result);
1457+
Assert.Contains("writer.writeObjectValue<Union>(\"property\", parentClass.property, );", result);
1458+
Assert.Contains("writer.writeAdditionalData(parentClass.additionalData);", result);
14741459
}
14751460

14761461
[Fact]
@@ -1512,7 +1497,7 @@ public async Task Writes_CodeUnionBetweenObjectsAndPrimitiveTypes_DeserializerAs
15121497
writer.Write(serializeFunction);
15131498
var result = tw.ToString();
15141499

1515-
Assert.Contains("\"property\": n => { parentClass.property = n.getCollectionOfObjectValues<ArrayOfObjects>(createArrayOfObjectsFromDiscriminatorValue) ?? n.getNumberValue() ?? n.getObjectValue<SingleObject>(createSingleObjectFromDiscriminatorValue) ?? n.getStringValue(); }", result);
1500+
Assert.Contains("\"property\": n => { parentClass.property = n.getObjectValue<Union>(createUnionFromDiscriminatorValue); }", result);
15161501
}
15171502
}
15181503

tests/Kiota.Builder.Tests/Writers/TypeScript/TypeScriptConventionServiceTests.cs

Lines changed: 0 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -31,82 +31,4 @@ private static CodeType CurrentType()
3131
currentType.Parent = parentClass;
3232
return currentType;
3333
}
34-
35-
[Fact]
36-
public void IsComposedOfPrimitives_ShouldBeTrue_WhenComposedOfPrimitives()
37-
{
38-
var composedType = new CodeUnionType { Name = "test", Parent = CurrentType() };
39-
composedType.AddType(new CodeType { Name = "string", IsExternal = true });
40-
composedType.AddType(new CodeType { Name = "integer", IsExternal = true });
41-
Assert.True(composedType.IsComposedOfPrimitives(TypeScriptConventionService.IsPrimitiveType));
42-
}
43-
44-
[Fact]
45-
public void IsComposedOfPrimitives_ShouldBeFalse_WhenNotComposedOfPrimitives()
46-
{
47-
var composedType = new CodeUnionType { Name = "test", Parent = CurrentType() };
48-
composedType.AddType(new CodeType { Name = "string", IsExternal = true });
49-
var td = new CodeClass { Name = "SomeClass" };
50-
composedType.AddType(new CodeType { Name = "SomeCustomObject", IsExternal = false, TypeDefinition = td });
51-
Assert.False(composedType.IsComposedOfPrimitives(TypeScriptConventionService.IsPrimitiveType));
52-
}
53-
54-
[Fact]
55-
public void IsComposedOfObjectsAndPrimitives_OnlyPrimitives_ReturnsFalse()
56-
{
57-
// Arrange
58-
var composedType = new CodeUnionType { Name = "test", Parent = CurrentType() };
59-
60-
composedType.AddType(new CodeType { Name = "string", IsExternal = true });
61-
62-
// Act
63-
var result = composedType.IsComposedOfObjectsAndPrimitives(TypeScriptConventionService.IsPrimitiveType);
64-
65-
// Assert
66-
Assert.False(result);
67-
}
68-
69-
[Fact]
70-
public void IsComposedOfObjectsAndPrimitives_OnlyObjects_ReturnsFalse()
71-
{
72-
var composedType = new CodeUnionType { Name = "test", Parent = CurrentType() };
73-
74-
var td = new CodeClass { Name = "SomeClass" };
75-
composedType.AddType(new CodeType { Name = "SomeCustomObject", IsExternal = false, TypeDefinition = td });
76-
77-
// Act
78-
var result = composedType.IsComposedOfObjectsAndPrimitives(TypeScriptConventionService.IsPrimitiveType);
79-
80-
// Assert
81-
Assert.False(result);
82-
}
83-
84-
[Fact]
85-
public void IsComposedOfObjectsAndPrimitives_BothPrimitivesAndObjects_ReturnsTrue()
86-
{
87-
var composedType = new CodeUnionType { Name = "test", Parent = CurrentType() };
88-
// Add primitive
89-
composedType.AddType(new CodeType { Name = "string", IsExternal = true });
90-
var td = new CodeClass { Name = "SomeClass" };
91-
composedType.AddType(new CodeType { Name = "SomeCustomObject", IsExternal = false, TypeDefinition = td });
92-
93-
// Act
94-
var result = composedType.IsComposedOfObjectsAndPrimitives(TypeScriptConventionService.IsPrimitiveType);
95-
96-
// Assert
97-
Assert.True(result);
98-
}
99-
100-
[Fact]
101-
public void IsComposedOfObjectsAndPrimitives_EmptyTypes_ReturnsFalse()
102-
{
103-
// Arrange
104-
var composedType = new CodeUnionType { Name = "test", Parent = CurrentType() };
105-
106-
// Act
107-
var result = composedType.IsComposedOfObjectsAndPrimitives(TypeScriptConventionService.IsPrimitiveType);
108-
109-
// Assert
110-
Assert.False(result);
111-
}
11234
}

0 commit comments

Comments
 (0)