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

Add unit tests to common package for allowedValues change #641

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 13 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
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ private CodeTypeDeclaration GenerateEnumStruct(MetricType type)
allowedValue.Replace(" ", "_").ToPascalCase().Replace(".", "").Replace("-", ""))
{
InitExpression = new CodeObjectCreateExpression(type.GetGeneratedTypeName(),
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For C# we converted the "key" but not the "value" to get rid of spaces. This was an oversight and testing of course caught this.

Thanks for pushing for testing.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Were any Toolkits released with spaces in the values? This change would create a discrepancy in emitted values across Toolkit versions.

Why not change the definition data to remove the spaces? I don't understand why the values cannot contain spaces.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There were spaces deployed this week. But we can revert this quickly as our slack discussion aligns with this being better for backend ingestion now and in the future.

new CodeExpression[] {new CodePrimitiveExpression(allowedValue)}),
new CodeExpression[] {new CodePrimitiveExpression(allowedValue.Replace(" ", "_"))}),
Attributes = MemberAttributes.Static | MemberAttributes.Public
};
field.Comments.Add(new CodeCommentStatement(allowedValue, true));
Expand Down
4,809 changes: 4,033 additions & 776 deletions telemetry/csharp/AwsToolkit.Telemetry.Events.Tests/Generated/GeneratedCode.cs

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,40 @@ public void RecordMetricWithNewTransform()
Assert.Single(datum.Metadata);
}

damntrecky marked this conversation as resolved.
Show resolved Hide resolved
/// <summary>
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test to make sure allowedValues with spaces converts the key properly and make sure the allowedValue -> value has spaces for now.

Although its recommended to NOT have spaces in the values, the build should not fail and have consistent behavior across environments

/// RecordCodeTransformIsDoubleClickedToTriggerInvalidProject was chosen as a sample call that has a
/// CodeTransformPreValidationError for allowedValues which have spaces in the values that
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CodeTransformPreValidationError values no longer have spaces, does the comment need to be updated?

/// should be converted to underscores.
/// </summary>
[Fact]
public void RecordWithAllowedValues()
{
var doubleClickRecord = new CodeTransformIsDoubleClickedToTriggerInvalidProject()
{
CodeTransformPreValidationError = CodeTransformPreValidationError.NoJavaProjectFound,
CodeTransformSessionId = "test-session-id",
Result = Result.Succeeded
};

_telemetryLogger.Object.RecordCodeTransformIsDoubleClickedToTriggerInvalidProject(doubleClickRecord);

Assert.NotNull(_recordedMetrics);
_telemetryLogger.Verify(
mock => mock.Record(_recordedMetrics),
Times.Once
);

var datum = Assert.Single(_recordedMetrics.Data);
Assert.NotNull(datum);
Assert.Equal("codeTransform_isDoubleClickedToTriggerInvalidProject", datum.MetricName);
Assert.Equal(Unit.None, datum.Unit);
Assert.False(datum.Passive);
Assert.True(datum.Metadata.ContainsKey("codeTransformSessionId"));
Assert.Equal("test-session-id", datum.Metadata["codeTransformSessionId"]);
Assert.True(datum.Metadata.ContainsKey("codeTransformPreValidationError"));
Assert.Equal("No_Java_project_found", datum.Metadata["codeTransformPreValidationError"]);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Strictly assert the new change/value here.

}

private MetricDatum TransformDuplicateReason(MetricDatum datum)
{
datum.Metadata["reason1"] = datum.Metadata["reason"];
Expand Down
9 changes: 9 additions & 0 deletions telemetry/csharp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,15 @@ Supplemental telemetry definitions can be integrated as follows:
1. Run the generator, using the Toolkit's supplemental telemetry definition file(s) as command line arguments (`toolkitcore\AWSToolkit.Util\Telemetry\vs-telemetry-definitions.json`)
1. Take the generated file(s) (GeneratedCode.cs), and place them in the toolkit (`toolkitcore\AWSToolkit.Util\Telemetry\ToolkitTelemetryEvents.generated.cs`)

## Testing

Tests are located under `AwsToolkit.Telmetry.Events.Tests`. These
tests are based off the build from `commonDefinitions.json`.

### Running Tests

To run the tests you can run them from this directory `telemetry/csharp` with the `dotnet build -c Release AwsToolkit.Telemetry.sln` command. This command will build the repo, including `commonDefinitions.json` and the tests will be run against that JSON file output for C#.

## Roadmap

- Standalone NuGet Package containing the Telemetry Event generator
Expand Down
6 changes: 6 additions & 0 deletions telemetry/jetbrains/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,9 @@
compileJava.dependsOn(generateTelemetry)
```
To add additional telemetry files, add `file("/path/to/file)` entries into the inputFiles array.

## Testing

### Running Tests

To run the tests you can run them from this directory `telemetry/jetbrains` with the `./gradlew test` command.
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ private fun FileSpec.Builder.generateTelemetryEnumType(item: TelemetryMetricType
item.allowedValues!!.forEach { enumValue ->
enum.addEnumConstant(
enumValue.toString().replace(Regex("\\s"), "_").toTypeFormat(), TypeSpec.anonymousClassBuilder()
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For Kotlin we converted the "key" but not the "value" to get rid of spaces. This was an oversight and testing of course caught this.

Thanks for pushing for testing.

.addSuperclassConstructorParameter("%S", enumValue.toString())
.addSuperclassConstructorParameter("%S", enumValue.toString().replace(Regex("\\s"), "_"))
.build()
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ class GeneratorTest {
testGenerator(defaultDefinitionsFile = "/testResultInput.json", definitionsOverrides = listOf("/testOverrideInput.json"), expectedOutputFile = "/testOverrideOutput")
}

@Test
fun generateAllowedValuesWithUnderscores() {
testGenerator(defaultDefinitionsFile = "/testGeneratorAllowedValuesInput.json", expectedOutputFile = "/testGeneratorAllowedValuesOutput")
}

@Test
fun longEnum() {
testGenerator(defaultDefinitionsFile = "/testLongEnumInput.json", expectedOutputFile = "/testLongEnumOutput")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@

{
"types": [
{
"name": "testAllowedValues",
"allowedValues": [
"test spaces are replaced",
"in allowed values"
],
"description": "A test object for parsing allowedValues"
}
],
"metrics": [
{
"name": "test_metric",
"description": "A test for defining allowedValues",
"unit": "None",
"metadata": [{ "type": "testAllowedValues" }]
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// THIS FILE IS GENERATED! DO NOT EDIT BY HAND!
@file:Suppress("unused", "MemberVisibilityCanBePrivate")

package software.aws.toolkits.telemetry

import com.intellij.openapi.project.Project
import java.time.Instant
import kotlin.Boolean
import kotlin.Double
import kotlin.String
import kotlin.Suppress
import kotlin.Unit
import software.aws.toolkits.core.ConnectionSettings
import software.aws.toolkits.jetbrains.services.telemetry.MetricEventMetadata
import software.aws.toolkits.jetbrains.services.telemetry.TelemetryService

/**
* A test object for parsing allowedValues
*/
public enum class TestAllowedValues(
private val `value`: String,
) {
damntrecky marked this conversation as resolved.
Show resolved Hide resolved
TestSpacesAreReplaced("test_spaces_are_replaced"),
InAllowedValues("in_allowed_values"),
Unknown("unknown"),
;

public override fun toString(): String = value

public companion object {
public fun from(type: String): TestAllowedValues = values().firstOrNull { it.value == type }
?: Unknown
}
}

public object TestTelemetry {
/**
* A test for defining allowedValues
*/
public fun metric(
project: Project?,
testAllowedValues: TestAllowedValues,
passive: Boolean = false,
`value`: Double = 1.0,
createTime: Instant = Instant.now(),
): Unit {
TelemetryService.getInstance().record(project) {
datum("test_metric") {
createTime(createTime)
unit(software.amazon.awssdk.services.toolkittelemetry.model.Unit.NONE)
value(value)
passive(passive)
metadata("testAllowedValues", testAllowedValues.toString())
}
}
}

/**
* A test for defining allowedValues
*/
public fun metric(
connectionSettings: ConnectionSettings? = null,
testAllowedValues: TestAllowedValues,
passive: Boolean = false,
`value`: Double = 1.0,
createTime: Instant = Instant.now(),
): Unit {
TelemetryService.getInstance().record(connectionSettings) {
datum("test_metric") {
createTime(createTime)
unit(software.amazon.awssdk.services.toolkittelemetry.model.Unit.NONE)
value(value)
passive(passive)
metadata("testAllowedValues", testAllowedValues.toString())
}
}
}

/**
* A test for defining allowedValues
*/
public fun metric(
metadata: MetricEventMetadata,
testAllowedValues: TestAllowedValues,
passive: Boolean = false,
`value`: Double = 1.0,
createTime: Instant = Instant.now(),
): Unit {
TelemetryService.getInstance().record(metadata) {
datum("test_metric") {
createTime(createTime)
unit(software.amazon.awssdk.services.toolkittelemetry.model.Unit.NONE)
value(value)
passive(passive)
metadata("testAllowedValues", testAllowedValues.toString())
}
}
}
}
6 changes: 6 additions & 0 deletions telemetry/vscode/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,9 @@ The script has two arguments:

1. `--extraInput` accepts lists of paths to telemetry JSON files, seperated by commas. For example, "--extraInput=abc.json,/abc/bcd.json"
2. `--output` accepts one path which represents where the final output will go. For example, "--output=abc.ts"

## Testing

### Running Tests

To run the tests you can run them from this directory `telemetry/vscode` with the `npm run test` command.
8 changes: 7 additions & 1 deletion telemetry/vscode/test/generator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ describe('Generator', () => {
beforeAll(() => {
tempDir = tmpdir()
})

test('Generate fails when validation fails', async () => {
await expect(testGenerator(['resources/invalidInput.json'], '/invalid/file/path')).rejects.toBeDefined()
})
Expand All @@ -28,6 +27,13 @@ describe('Generator', () => {
)
})

test('Generate replaces allowedValues spaces with underscores', async () => {
await testGenerator(
['resources/generatorAllowedValuesInput.json'],
'resources/generatorAllowedValuesOutput.ts'
)
})

async function testGenerator(inputFiles: string[], expectedOutputFile: string) {
const output = `${tempDir}/output`
await generate({ inputFiles: inputFiles.map(item => `${__dirname}/${item}`), outputFile: output })
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@

{
"types": [
{
"name": "result",
"allowedValues": ["Succeeded"],
"description": "The result of the operation"
},
{
"name": "reason",
"type": "string",
"description": "The reason for a metric or exception depending on context"
},
{
"name": "duration",
"type": "double",
"description": "The duration of the operation in miliseconds"
},
{
"name": "testAllowedValues",
"allowedValues": [
"test spaces are replaced",
"in allowed values"
],
"description": "A test object for parsing allowedValues"
}
],
"metrics": [
{
"name": "test_metric",
"description": "A test for defining allowedValues",
"unit": "None",
"metadata": [{ "type": "testAllowedValues" }]
}
]
}
62 changes: 62 additions & 0 deletions telemetry/vscode/test/resources/generatorAllowedValuesOutput.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*!
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
export interface MetricBase {
/** The result of the operation */
readonly result?: Result
/** The reason for a metric or exception depending on context */
readonly reason?: string
/** The duration of the operation in miliseconds */
readonly duration?: number
/** A flag indicating that the metric was not caused by the user. */
readonly passive?: boolean
/** @deprecated Arbitrary "value" of the metric. */
readonly value?: number
}

export interface TestMetric extends MetricBase {
/** A test object for parsing allowedValues */
readonly testAllowedValues: TestAllowedValues
}

export type Result = 'Succeeded'
export type LambdaRuntime = 'dotnetcore2.1' | 'nodejs12.x'
export type TestAllowedValues = 'test_spaces_are_replaced' | 'in_allowed_values'

export interface MetricDefinition {
readonly unit: string
readonly passive: boolean
readonly requiredMetadata: readonly string[]
}

export interface MetricShapes {
readonly test_metric: TestMetric
}

export type MetricName = keyof MetricShapes

export const definitions: Record<string, MetricDefinition> = {
test_metric: { unit: 'None', passive: false, requiredMetadata: ['testAllowedValues'] },
}

export type Metadata<T extends MetricBase> = Partial<Omit<T, keyof MetricBase>>

export interface Metric<T extends MetricBase = MetricBase> {
readonly name: string
/** Adds data to the metric which is preserved for the remainder of the execution context */
record(data: Metadata<T>): void
/** Sends the metric to the telemetry service */
emit(data?: T): void
/** Executes a callback, automatically sending the metric after completion */
run<U>(fn: (span: this) => U): U
}

export abstract class TelemetryBase {
/** A test for defining allowedValues */
public get test_metric(): Metric<TestMetric> {
return this.getMetric('test_metric')
}

protected abstract getMetric(name: string): Metric
}