diff --git a/workshops/serverless-testing-workshop/tests/integration/dotnet/.editorconfig b/workshops/serverless-testing-workshop/tests/integration/dotnet/.editorconfig new file mode 100644 index 00000000..1ac5a9a1 --- /dev/null +++ b/workshops/serverless-testing-workshop/tests/integration/dotnet/.editorconfig @@ -0,0 +1,26 @@ +# https://editorconfig.org/ + +# What is EditorConfig? + +# EditorConfig helps maintain consistent coding styles for multiple developers +# working on the same project across various editors and IDEs. The EditorConfig +# project consists of a file format for defining coding styles and a collection +# of text editor plugins that enable editors to read the file format and adhere +# to defined styles. EditorConfig files are easily readable and they work nicely +# with version control systems. + +# top-most EditorConfig file +root = true + +[*] +charset = utf-8 +end_of_line = crlf + +indent_style = tab +indent_size = 2 + +insert_final_newline = true +trim_trailing_whitespace = true + +[*.cs] +indent_size = 4 diff --git a/workshops/serverless-testing-workshop/tests/integration/dotnet/.gitignore b/workshops/serverless-testing-workshop/tests/integration/dotnet/.gitignore new file mode 100644 index 00000000..f5df85a2 --- /dev/null +++ b/workshops/serverless-testing-workshop/tests/integration/dotnet/.gitignore @@ -0,0 +1,585 @@ +# Created by https://www.toptal.com/developers/gitignore/api/windows,macos,linux,visualstudio,visualstudiocode,rider,vim +# Edit at https://www.toptal.com/developers/gitignore?templates=windows,macos,linux,visualstudio,visualstudiocode,rider,vim + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### macOS ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### macOS Patch ### +# iCloud generated files +*.icloud + +### Rider ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Vim ### +# Swap +[._]*.s[a-v][a-z] +!*.svg # comment out if you don't need vector files +[._]*.sw[a-p] +[._]s[a-rt-v][a-z] +[._]ss[a-gi-z] +[._]sw[a-p] + +# Session +Session.vim +Sessionx.vim + +# Temporary +.netrwhist +# Auto-generated tag files +tags +# Persistent undo +[._]*.un~ + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# Local History for Visual Studio Code +.history/ + +# Built Visual Studio Code Extensions +*.vsix + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history +.ionide + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +### VisualStudio ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +*.code-workspace + +# Local History for Visual Studio Code + +# Windows Installer files from build outputs + +# JetBrains Rider +*.sln.iml + +### VisualStudio Patch ### +# Additional files built by Visual Studio + +# End of https://www.toptal.com/developers/gitignore/api/windows,macos,linux,visualstudio,visualstudiocode,rider,vim diff --git a/workshops/serverless-testing-workshop/tests/integration/dotnet/UnicornReservationSystem.Tests.Integration.sln b/workshops/serverless-testing-workshop/tests/integration/dotnet/UnicornReservationSystem.Tests.Integration.sln new file mode 100644 index 00000000..8b367cf8 --- /dev/null +++ b/workshops/serverless-testing-workshop/tests/integration/dotnet/UnicornReservationSystem.Tests.Integration.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnicornReservationSystem.Tests.Integration", "UnicornReservationSystem.Tests.Integration\UnicornReservationSystem.Tests.Integration.csproj", "{CDF03B50-83B5-40A8-99DE-6226057E32AB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {CDF03B50-83B5-40A8-99DE-6226057E32AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CDF03B50-83B5-40A8-99DE-6226057E32AB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CDF03B50-83B5-40A8-99DE-6226057E32AB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CDF03B50-83B5-40A8-99DE-6226057E32AB}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/workshops/serverless-testing-workshop/tests/integration/dotnet/UnicornReservationSystem.Tests.Integration/FileProcessorTests.cs b/workshops/serverless-testing-workshop/tests/integration/dotnet/UnicornReservationSystem.Tests.Integration/FileProcessorTests.cs new file mode 100644 index 00000000..7c0de124 --- /dev/null +++ b/workshops/serverless-testing-workshop/tests/integration/dotnet/UnicornReservationSystem.Tests.Integration/FileProcessorTests.cs @@ -0,0 +1,165 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved + * + * SPDX-License-Identifier: MIT-0 + */ + +using Amazon.DynamoDBv2; +using Amazon.DynamoDBv2.DocumentModel; +using Amazon.S3; +using Amazon.S3.Model; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +using UnicornReservationSystem.Tests.Integration.Fixtures; + +using Xunit; + +namespace UnicornReservationSystem.Tests.Integration; + +[Collection("Environment")] +public class FileProcessorTests : IAsyncLifetime +{ + private readonly EnvironmentFixture _environmentFixture; + private readonly AmazonDynamoDBClient _dynamoDbClient; + private readonly AmazonS3Client _s3Client; + + private readonly Guid _postFix; + private readonly string _testUnicorn; + private readonly string _testLocation; + + /// + /// We also seed the DynamoDB Table for the test + /// + /// + public FileProcessorTests(EnvironmentFixture environmentFixture) + { + _environmentFixture = environmentFixture; + _dynamoDbClient = new AmazonDynamoDBClient(); + _s3Client = new AmazonS3Client(); + + // Create a random postfix for the id's to prevent data collisions between tests + // Using unique id's per unit test will isolate test data + // Use this id in all test data values or artifacts + _postFix = Guid.NewGuid(); + _testUnicorn = $"TEST_UNI_{_postFix}"; + _testLocation = $"TEST_LOC_{_postFix}"; + } + + public Task InitializeAsync() => Task.CompletedTask; + + /// + /// Test that given an S3 file, the Unicorn is created in DynamoDB + /// In a real-world scenario, we would test variations and failure modes as well + /// + [Fact] + public async Task Workflow_S3Upload_ReturnsNewUnicorn() + { + var table = Table.LoadTable(_dynamoDbClient, _environmentFixture.DynamoDbTable); + Document existingTestUnicorn = await table.GetItemAsync(_testUnicorn); + Assert.True(existingTestUnicorn is null, "Data exists before test, invalid starting state"); + + // Seed the S3 bucket with test data + // Note the uniqueness of the test data and S3 key to prevent collisions with actual data: + // both the postfix and the exact test name are part of the filename. + var testData = $""" + "Unicorn Name","Unicorn Location" + "{_testUnicorn}","{_testLocation}" + + """; + var testDataKey = $"INTEGRATION_TEST/TEST{_postFix}.test_file_processor_happy_path.csv"; + var s3Request = new PutObjectRequest + { + BucketName = _environmentFixture.UnicornInventoryBucket, + Key = testDataKey, + ContentBody = testData + }; + _ = await _s3Client.PutObjectAsync(s3Request); + + // Create a search object to contain the search parameters + List searchResults = []; + + // Poll for processing completion + var pollMaxTime = TimeSpan.FromSeconds(30); + var pollCompleteSeconds = TimeSpan.Zero; + while (pollCompleteSeconds < pollMaxTime) + { + // Perform the search to see if the file processor has finished + Search tableSearch = table.Query(new QueryFilter("PK", QueryOperator.Equal, _testUnicorn)); + searchResults = await tableSearch.GetNextSetAsync(); + if (searchResults.Count == 0) + { + /* There are better ways to wait for an async event to finish than "Sleep" + * https://ardalis.com/thread-sleep-in-tests-is-evil/ + * https://www.meziantou.net/automated-ui-tests-an-asp-net-core-application-with-playwright-and-xunit.htm + */ + Thread.Sleep(TimeSpan.FromSeconds(1)); + pollCompleteSeconds = pollCompleteSeconds.Add(TimeSpan.FromSeconds(1)); + } + else + { + break; + } + } + + // Happy Path Checks: 1 item found within a good timeframe, data is as expected. + // Using Assert.True for most of these checks as they allow for user messages to be added to test output + + Assert.True(searchResults.Count > 0, "Item not found after time allowed for processing."); + Assert.True(pollCompleteSeconds < TimeSpan.FromSeconds(2), $"Unicorns should be fast! Took too long: {pollCompleteSeconds}"); + Assert.True(searchResults.Count == 1, "More than one item found after insert of data"); + Assert.True(searchResults[0]["PK"].AsString() == _testUnicorn, $"Table PK is not set to the Unicorn Name: {searchResults[0]["PK"].AsString()} expected {_testUnicorn}"); + Assert.True(searchResults[0]["LOCATION"].AsString() == _testLocation, $"Table LOCATION is not set to the Unicorn Location: {searchResults[0]["LOCATION"].AsString()} expected {_testLocation}"); + Assert.Contains(["IN_TRAINING", "AVAILABLE"], status => status.Contains(searchResults[0]["STATUS"].AsString())); + } + + public async Task DisposeAsync() + { + // Remove the test unicorn + var table = Table.LoadTable(_dynamoDbClient, _environmentFixture.DynamoDbTable); + Document testUnicorn = await table.GetItemAsync(_testUnicorn); + if (testUnicorn is not null) + { + await table.DeleteItemAsync(testUnicorn); + } + + // And the test location from the locations list + DynamoDBEntry testLocationEntry = DynamoDBEntryConversion.V2.ConvertToEntry(_testLocation); + DynamoDBList locations = null; + var pollMaxTime = TimeSpan.FromSeconds(30); + var pollCompleteSeconds = TimeSpan.Zero; + + // The LOCATIONS#LIST value was being subjected to eventual consistently delays + // This loop repeatedly retrieves the LOCATIONS#LIST key until our _testLocation is present + // or the timeout has elapsed + while (pollCompleteSeconds < pollMaxTime) + { + Document locationsList = await table.GetItemAsync("LOCATION#LIST"); + locations = locationsList["LOCATIONS"].AsDynamoDBList(); + var indexUpdated = locations?.AsArrayOfString().Contains(_testLocation) ?? false; + if (indexUpdated) + { + break; + } + else + { + Thread.Sleep(TimeSpan.FromSeconds(1)); + pollCompleteSeconds = pollCompleteSeconds.Add(TimeSpan.FromSeconds(1)); + } + } + + locations?.Entries.Remove(testLocationEntry); + await table.PutItemAsync(new Document + { + ["PK"] = "LOCATION#LIST", + ["LOCATIONS"] = locations + }); + + _dynamoDbClient?.Dispose(); + _s3Client?.Dispose(); + } +} diff --git a/workshops/serverless-testing-workshop/tests/integration/dotnet/UnicornReservationSystem.Tests.Integration/Fixtures/EnvironmentCollection.cs b/workshops/serverless-testing-workshop/tests/integration/dotnet/UnicornReservationSystem.Tests.Integration/Fixtures/EnvironmentCollection.cs new file mode 100644 index 00000000..e5703f0e --- /dev/null +++ b/workshops/serverless-testing-workshop/tests/integration/dotnet/UnicornReservationSystem.Tests.Integration/Fixtures/EnvironmentCollection.cs @@ -0,0 +1,17 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved + * + * SPDX-License-Identifier: MIT-0 + */ + +using Xunit; + +namespace UnicornReservationSystem.Tests.Integration.Fixtures; + +/// +/// This class has no code, and is never created. Its purpose is simply +/// to be the place to apply [CollectionDefinition] and all the +/// ICollectionFixture<T> interfaces. +/// +[CollectionDefinition("Environment")] +public class EnvironmentCollection : ICollectionFixture; diff --git a/workshops/serverless-testing-workshop/tests/integration/dotnet/UnicornReservationSystem.Tests.Integration/Fixtures/EnvironmentFixture.cs b/workshops/serverless-testing-workshop/tests/integration/dotnet/UnicornReservationSystem.Tests.Integration/Fixtures/EnvironmentFixture.cs new file mode 100644 index 00000000..8fa3f47a --- /dev/null +++ b/workshops/serverless-testing-workshop/tests/integration/dotnet/UnicornReservationSystem.Tests.Integration/Fixtures/EnvironmentFixture.cs @@ -0,0 +1,28 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved + * + * SPDX-License-Identifier: MIT-0 + */ + +// More information about xUnit Collection Fixtures +// https://xunit.net/docs/shared-context#collection-fixture + +using Amazon.CloudFormation; +using Amazon.CloudFormation.Model; + +using System; +using System.Linq; + +namespace UnicornReservationSystem.Tests.Integration.Fixtures; + +public sealed class EnvironmentFixture +{ + public EnvironmentFixture() + { + + } + + public string ApiEndpoint { get; private set; } + public string DynamoDbTable { get; private set; } + public string UnicornInventoryBucket { get; private set; } +} diff --git a/workshops/serverless-testing-workshop/tests/integration/dotnet/UnicornReservationSystem.Tests.Integration/Fixtures/LocationFixture.cs b/workshops/serverless-testing-workshop/tests/integration/dotnet/UnicornReservationSystem.Tests.Integration/Fixtures/LocationFixture.cs new file mode 100644 index 00000000..f4d5d1c6 --- /dev/null +++ b/workshops/serverless-testing-workshop/tests/integration/dotnet/UnicornReservationSystem.Tests.Integration/Fixtures/LocationFixture.cs @@ -0,0 +1,139 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved + * + * SPDX-License-Identifier: MIT-0 + */ + +// More information about xUnit Class Fixtures +// https://xunit.net/docs/shared-context#class-fixture + +using Amazon.DynamoDBv2; +using Amazon.DynamoDBv2.DocumentModel; + +using System; +using System.Linq; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; + +using Xunit; + +namespace UnicornReservationSystem.Tests.Integration.Fixtures; + +public class LocationFixture : IAsyncLifetime +{ + private readonly EnvironmentFixture _environmentFixture; + private readonly AmazonDynamoDBClient _dynamoDbClient; + + public LocationFixture(EnvironmentFixture environmentFixture) + { + // ** Place UniqueTestLocation Code Here ** + + _environmentFixture = environmentFixture; + _dynamoDbClient = new AmazonDynamoDBClient(); + + // HttpClient lifecycle management best practices: + // https://learn.microsoft.com/dotnet/fundamentals/networking/http/httpclient-guidelines#recommended-use + UnicornApi = new HttpClient + { + BaseAddress = new Uri(_environmentFixture.ApiEndpoint) + }; + } + + public string UniqueTestLocation { get; } + public HttpClient UnicornApi { get; } + + /// + /// Perform initialization steps + /// + /// + /// This method is implemented as part of the interface. + /// It is here that we use the DynamoDB module of the .NET SDK to directly upload a test location to the LOCATION#LIST + /// entry so we can use it in our tests. + /// + public async Task InitializeAsync() + { + // Get the LOCATION#LIST item from DynamoDB + var table = Table.LoadTable(_dynamoDbClient, _environmentFixture.DynamoDbTable); + Document locationList = await table.GetItemAsync("LOCATION#LIST"); + + // The LOCATION#LIST is a List data type + // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes.Document.List + // Create a new DynamoDBList object to add the test location + var updatedLocationList = new DynamoDBList(); + + // Convert the test location into a DynamoDB entry from a string + var testLocationEntry = DynamoDBEntryConversion.V2.ConvertToEntry(UniqueTestLocation); + if (locationList is null) + { + updatedLocationList.Add(testLocationEntry); + } + else + { + // If the location list already has entries, add them to the updatedLocationList + // before we add our test location. Otherwise, the LOCATIONS attribute would be wholly + // replaced with just the new test location, erasing the existing locations. + updatedLocationList = locationList["LOCATIONS"].AsDynamoDBList(); + updatedLocationList.Add(testLocationEntry); + } + + // Store the new list of locations + await table.PutItemAsync(new Document + { + ["PK"] = "LOCATION#LIST", + ["LOCATIONS"] = updatedLocationList + }); + } + + /// + /// Runs at the completion of all tests in a given class + /// + /// + /// This method is implemented as part of the interface. + /// It is here that we use the DynamoDB module of the .NET SDK to remove the test location from the LOCATION#LIST + /// entry so we can clean up after the tests finish. + /// + public async Task DisposeAsync() + { + // Convert the test location into a DynamoDB entry from a string + DynamoDBEntry testLocationEntry = DynamoDBEntryConversion.V2.ConvertToEntry(UniqueTestLocation); + var table = Table.LoadTable(_dynamoDbClient, _environmentFixture.DynamoDbTable); + + // Setup variables to keep track of polling + DynamoDBList locations = null; + var pollMaxTime = TimeSpan.FromSeconds(30); + var pollCompleteSeconds = TimeSpan.Zero; + + // When reading from DynamoDB values are sometimes eventually consistent + // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html + // This loop repeatedly retrieves the LOCATIONS#LIST key until our UniqueTestLocation is present + // or the timeout has elapsed + while (pollCompleteSeconds < pollMaxTime) + { + Document locationsList = await table.GetItemAsync("LOCATION#LIST"); + locations = locationsList["LOCATIONS"].AsDynamoDBList(); + var indexUpdated = locations?.AsArrayOfString().Contains(UniqueTestLocation) ?? false; + if (indexUpdated) + { + break; + } + else + { + Thread.Sleep(TimeSpan.FromSeconds(1)); + pollCompleteSeconds = pollCompleteSeconds.Add(TimeSpan.FromSeconds(1)); + } + } + + // Remove the UniqueTestLocation from the list retrieved from DynamoDB + locations?.Entries.Remove(testLocationEntry); + + // Store the new list of locations + await table.PutItemAsync(new Document + { + ["PK"] = "LOCATION#LIST", + ["LOCATIONS"] = locations + }); + + _dynamoDbClient?.Dispose(); + } +} diff --git a/workshops/serverless-testing-workshop/tests/integration/dotnet/UnicornReservationSystem.Tests.Integration/LocationTests.cs b/workshops/serverless-testing-workshop/tests/integration/dotnet/UnicornReservationSystem.Tests.Integration/LocationTests.cs new file mode 100644 index 00000000..50ae7808 --- /dev/null +++ b/workshops/serverless-testing-workshop/tests/integration/dotnet/UnicornReservationSystem.Tests.Integration/LocationTests.cs @@ -0,0 +1,6 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved + * + * SPDX-License-Identifier: MIT-0 + */ + diff --git a/workshops/serverless-testing-workshop/tests/integration/dotnet/UnicornReservationSystem.Tests.Integration/UnicornReservationSystem.Tests.Integration.csproj b/workshops/serverless-testing-workshop/tests/integration/dotnet/UnicornReservationSystem.Tests.Integration/UnicornReservationSystem.Tests.Integration.csproj new file mode 100644 index 00000000..ec7ecb69 --- /dev/null +++ b/workshops/serverless-testing-workshop/tests/integration/dotnet/UnicornReservationSystem.Tests.Integration/UnicornReservationSystem.Tests.Integration.csproj @@ -0,0 +1,28 @@ + + + + net8.0 + disable + disable + + false + true + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + diff --git a/workshops/serverless-testing-workshop/tests/integration/dotnet/completed-solution/.gitignore b/workshops/serverless-testing-workshop/tests/integration/dotnet/completed-solution/.gitignore new file mode 100644 index 00000000..f5df85a2 --- /dev/null +++ b/workshops/serverless-testing-workshop/tests/integration/dotnet/completed-solution/.gitignore @@ -0,0 +1,585 @@ +# Created by https://www.toptal.com/developers/gitignore/api/windows,macos,linux,visualstudio,visualstudiocode,rider,vim +# Edit at https://www.toptal.com/developers/gitignore?templates=windows,macos,linux,visualstudio,visualstudiocode,rider,vim + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### macOS ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### macOS Patch ### +# iCloud generated files +*.icloud + +### Rider ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Vim ### +# Swap +[._]*.s[a-v][a-z] +!*.svg # comment out if you don't need vector files +[._]*.sw[a-p] +[._]s[a-rt-v][a-z] +[._]ss[a-gi-z] +[._]sw[a-p] + +# Session +Session.vim +Sessionx.vim + +# Temporary +.netrwhist +# Auto-generated tag files +tags +# Persistent undo +[._]*.un~ + +### VisualStudioCode ### +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +!.vscode/*.code-snippets + +# Local History for Visual Studio Code +.history/ + +# Built Visual Studio Code Extensions +*.vsix + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history +.ionide + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +### VisualStudio ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +*.code-workspace + +# Local History for Visual Studio Code + +# Windows Installer files from build outputs + +# JetBrains Rider +*.sln.iml + +### VisualStudio Patch ### +# Additional files built by Visual Studio + +# End of https://www.toptal.com/developers/gitignore/api/windows,macos,linux,visualstudio,visualstudiocode,rider,vim diff --git a/workshops/serverless-testing-workshop/tests/integration/dotnet/completed-solution/UnicornReservationSystem.Tests.Integration.sln b/workshops/serverless-testing-workshop/tests/integration/dotnet/completed-solution/UnicornReservationSystem.Tests.Integration.sln new file mode 100644 index 00000000..8b367cf8 --- /dev/null +++ b/workshops/serverless-testing-workshop/tests/integration/dotnet/completed-solution/UnicornReservationSystem.Tests.Integration.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnicornReservationSystem.Tests.Integration", "UnicornReservationSystem.Tests.Integration\UnicornReservationSystem.Tests.Integration.csproj", "{CDF03B50-83B5-40A8-99DE-6226057E32AB}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {CDF03B50-83B5-40A8-99DE-6226057E32AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CDF03B50-83B5-40A8-99DE-6226057E32AB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CDF03B50-83B5-40A8-99DE-6226057E32AB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CDF03B50-83B5-40A8-99DE-6226057E32AB}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/workshops/serverless-testing-workshop/tests/integration/dotnet/completed-solution/UnicornReservationSystem.Tests.Integration/FileProcessorTests.cs b/workshops/serverless-testing-workshop/tests/integration/dotnet/completed-solution/UnicornReservationSystem.Tests.Integration/FileProcessorTests.cs new file mode 100644 index 00000000..7c0de124 --- /dev/null +++ b/workshops/serverless-testing-workshop/tests/integration/dotnet/completed-solution/UnicornReservationSystem.Tests.Integration/FileProcessorTests.cs @@ -0,0 +1,165 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved + * + * SPDX-License-Identifier: MIT-0 + */ + +using Amazon.DynamoDBv2; +using Amazon.DynamoDBv2.DocumentModel; +using Amazon.S3; +using Amazon.S3.Model; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +using UnicornReservationSystem.Tests.Integration.Fixtures; + +using Xunit; + +namespace UnicornReservationSystem.Tests.Integration; + +[Collection("Environment")] +public class FileProcessorTests : IAsyncLifetime +{ + private readonly EnvironmentFixture _environmentFixture; + private readonly AmazonDynamoDBClient _dynamoDbClient; + private readonly AmazonS3Client _s3Client; + + private readonly Guid _postFix; + private readonly string _testUnicorn; + private readonly string _testLocation; + + /// + /// We also seed the DynamoDB Table for the test + /// + /// + public FileProcessorTests(EnvironmentFixture environmentFixture) + { + _environmentFixture = environmentFixture; + _dynamoDbClient = new AmazonDynamoDBClient(); + _s3Client = new AmazonS3Client(); + + // Create a random postfix for the id's to prevent data collisions between tests + // Using unique id's per unit test will isolate test data + // Use this id in all test data values or artifacts + _postFix = Guid.NewGuid(); + _testUnicorn = $"TEST_UNI_{_postFix}"; + _testLocation = $"TEST_LOC_{_postFix}"; + } + + public Task InitializeAsync() => Task.CompletedTask; + + /// + /// Test that given an S3 file, the Unicorn is created in DynamoDB + /// In a real-world scenario, we would test variations and failure modes as well + /// + [Fact] + public async Task Workflow_S3Upload_ReturnsNewUnicorn() + { + var table = Table.LoadTable(_dynamoDbClient, _environmentFixture.DynamoDbTable); + Document existingTestUnicorn = await table.GetItemAsync(_testUnicorn); + Assert.True(existingTestUnicorn is null, "Data exists before test, invalid starting state"); + + // Seed the S3 bucket with test data + // Note the uniqueness of the test data and S3 key to prevent collisions with actual data: + // both the postfix and the exact test name are part of the filename. + var testData = $""" + "Unicorn Name","Unicorn Location" + "{_testUnicorn}","{_testLocation}" + + """; + var testDataKey = $"INTEGRATION_TEST/TEST{_postFix}.test_file_processor_happy_path.csv"; + var s3Request = new PutObjectRequest + { + BucketName = _environmentFixture.UnicornInventoryBucket, + Key = testDataKey, + ContentBody = testData + }; + _ = await _s3Client.PutObjectAsync(s3Request); + + // Create a search object to contain the search parameters + List searchResults = []; + + // Poll for processing completion + var pollMaxTime = TimeSpan.FromSeconds(30); + var pollCompleteSeconds = TimeSpan.Zero; + while (pollCompleteSeconds < pollMaxTime) + { + // Perform the search to see if the file processor has finished + Search tableSearch = table.Query(new QueryFilter("PK", QueryOperator.Equal, _testUnicorn)); + searchResults = await tableSearch.GetNextSetAsync(); + if (searchResults.Count == 0) + { + /* There are better ways to wait for an async event to finish than "Sleep" + * https://ardalis.com/thread-sleep-in-tests-is-evil/ + * https://www.meziantou.net/automated-ui-tests-an-asp-net-core-application-with-playwright-and-xunit.htm + */ + Thread.Sleep(TimeSpan.FromSeconds(1)); + pollCompleteSeconds = pollCompleteSeconds.Add(TimeSpan.FromSeconds(1)); + } + else + { + break; + } + } + + // Happy Path Checks: 1 item found within a good timeframe, data is as expected. + // Using Assert.True for most of these checks as they allow for user messages to be added to test output + + Assert.True(searchResults.Count > 0, "Item not found after time allowed for processing."); + Assert.True(pollCompleteSeconds < TimeSpan.FromSeconds(2), $"Unicorns should be fast! Took too long: {pollCompleteSeconds}"); + Assert.True(searchResults.Count == 1, "More than one item found after insert of data"); + Assert.True(searchResults[0]["PK"].AsString() == _testUnicorn, $"Table PK is not set to the Unicorn Name: {searchResults[0]["PK"].AsString()} expected {_testUnicorn}"); + Assert.True(searchResults[0]["LOCATION"].AsString() == _testLocation, $"Table LOCATION is not set to the Unicorn Location: {searchResults[0]["LOCATION"].AsString()} expected {_testLocation}"); + Assert.Contains(["IN_TRAINING", "AVAILABLE"], status => status.Contains(searchResults[0]["STATUS"].AsString())); + } + + public async Task DisposeAsync() + { + // Remove the test unicorn + var table = Table.LoadTable(_dynamoDbClient, _environmentFixture.DynamoDbTable); + Document testUnicorn = await table.GetItemAsync(_testUnicorn); + if (testUnicorn is not null) + { + await table.DeleteItemAsync(testUnicorn); + } + + // And the test location from the locations list + DynamoDBEntry testLocationEntry = DynamoDBEntryConversion.V2.ConvertToEntry(_testLocation); + DynamoDBList locations = null; + var pollMaxTime = TimeSpan.FromSeconds(30); + var pollCompleteSeconds = TimeSpan.Zero; + + // The LOCATIONS#LIST value was being subjected to eventual consistently delays + // This loop repeatedly retrieves the LOCATIONS#LIST key until our _testLocation is present + // or the timeout has elapsed + while (pollCompleteSeconds < pollMaxTime) + { + Document locationsList = await table.GetItemAsync("LOCATION#LIST"); + locations = locationsList["LOCATIONS"].AsDynamoDBList(); + var indexUpdated = locations?.AsArrayOfString().Contains(_testLocation) ?? false; + if (indexUpdated) + { + break; + } + else + { + Thread.Sleep(TimeSpan.FromSeconds(1)); + pollCompleteSeconds = pollCompleteSeconds.Add(TimeSpan.FromSeconds(1)); + } + } + + locations?.Entries.Remove(testLocationEntry); + await table.PutItemAsync(new Document + { + ["PK"] = "LOCATION#LIST", + ["LOCATIONS"] = locations + }); + + _dynamoDbClient?.Dispose(); + _s3Client?.Dispose(); + } +} diff --git a/workshops/serverless-testing-workshop/tests/integration/dotnet/completed-solution/UnicornReservationSystem.Tests.Integration/Fixtures/EnvironmentCollection.cs b/workshops/serverless-testing-workshop/tests/integration/dotnet/completed-solution/UnicornReservationSystem.Tests.Integration/Fixtures/EnvironmentCollection.cs new file mode 100644 index 00000000..e5703f0e --- /dev/null +++ b/workshops/serverless-testing-workshop/tests/integration/dotnet/completed-solution/UnicornReservationSystem.Tests.Integration/Fixtures/EnvironmentCollection.cs @@ -0,0 +1,17 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved + * + * SPDX-License-Identifier: MIT-0 + */ + +using Xunit; + +namespace UnicornReservationSystem.Tests.Integration.Fixtures; + +/// +/// This class has no code, and is never created. Its purpose is simply +/// to be the place to apply [CollectionDefinition] and all the +/// ICollectionFixture<T> interfaces. +/// +[CollectionDefinition("Environment")] +public class EnvironmentCollection : ICollectionFixture; diff --git a/workshops/serverless-testing-workshop/tests/integration/dotnet/completed-solution/UnicornReservationSystem.Tests.Integration/Fixtures/EnvironmentFixture.cs b/workshops/serverless-testing-workshop/tests/integration/dotnet/completed-solution/UnicornReservationSystem.Tests.Integration/Fixtures/EnvironmentFixture.cs new file mode 100644 index 00000000..3b17738d --- /dev/null +++ b/workshops/serverless-testing-workshop/tests/integration/dotnet/completed-solution/UnicornReservationSystem.Tests.Integration/Fixtures/EnvironmentFixture.cs @@ -0,0 +1,51 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved + * + * SPDX-License-Identifier: MIT-0 + */ + +// More information about xUnit Collection Fixtures +// https://xunit.net/docs/shared-context#collection-fixture + +using Amazon.CloudFormation; +using Amazon.CloudFormation.Model; + +using System; +using System.Linq; + +namespace UnicornReservationSystem.Tests.Integration.Fixtures; + +public sealed class EnvironmentFixture +{ + public EnvironmentFixture() + { + var stackName = Environment.GetEnvironmentVariable("AWS_SAM_STACK_NAME"); + if (String.IsNullOrWhiteSpace(stackName)) + { + throw new ApplicationException("Cannot find environment variable AWS_SAM_STACK_NAME. \n" + + "Please setup this environment variable with the stack name for integration tests"); + } + + try + { + var client = new AmazonCloudFormationClient(); + var request = new DescribeStacksRequest + { + StackName = stackName + }; + var response = client.DescribeStacksAsync(request).GetAwaiter().GetResult(); + ApiEndpoint = response.Stacks[0].Outputs.First(x => x.OutputKey == "ApiEndpoint").OutputValue; + DynamoDbTable = response.Stacks[0].Outputs.First(x => x.OutputKey == "DynamoDBTableName").OutputValue; + UnicornInventoryBucket = response.Stacks[0].Outputs.First(x => x.OutputKey == "UnicornInventoryBucket").OutputValue; + } + catch + { + throw new ApplicationException($"Cannot find stack {stackName}.\n" + + "Please make sure stack with the name \"{stackName}\" exists."); + } + } + + public string ApiEndpoint { get; private set; } + public string DynamoDbTable { get; private set; } + public string UnicornInventoryBucket { get; private set; } +} diff --git a/workshops/serverless-testing-workshop/tests/integration/dotnet/completed-solution/UnicornReservationSystem.Tests.Integration/Fixtures/LocationFixture.cs b/workshops/serverless-testing-workshop/tests/integration/dotnet/completed-solution/UnicornReservationSystem.Tests.Integration/Fixtures/LocationFixture.cs new file mode 100644 index 00000000..b72745ab --- /dev/null +++ b/workshops/serverless-testing-workshop/tests/integration/dotnet/completed-solution/UnicornReservationSystem.Tests.Integration/Fixtures/LocationFixture.cs @@ -0,0 +1,140 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved + * + * SPDX-License-Identifier: MIT-0 + */ + +// More information about xUnit Class Fixtures +// https://xunit.net/docs/shared-context#class-fixture + +using Amazon.DynamoDBv2; +using Amazon.DynamoDBv2.DocumentModel; + +using System; +using System.Linq; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; + +using Xunit; + +namespace UnicornReservationSystem.Tests.Integration.Fixtures; + +public class LocationFixture : IAsyncLifetime +{ + private readonly EnvironmentFixture _environmentFixture; + private readonly AmazonDynamoDBClient _dynamoDbClient; + + public LocationFixture(EnvironmentFixture environmentFixture) + { + // ** Place UniqueTestLocation Code Here ** + UniqueTestLocation = $"TEST_LOC_{Guid.NewGuid()}"; + + _environmentFixture = environmentFixture; + _dynamoDbClient = new AmazonDynamoDBClient(); + + // HttpClient lifecycle management best practices: + // https://learn.microsoft.com/dotnet/fundamentals/networking/http/httpclient-guidelines#recommended-use + UnicornApi = new HttpClient + { + BaseAddress = new Uri(_environmentFixture.ApiEndpoint) + }; + } + + public string UniqueTestLocation { get; } + public HttpClient UnicornApi { get; } + + /// + /// Perform initialization steps + /// + /// + /// This method is implemented as part of the interface. + /// It is here that we use the DynamoDB module of the .NET SDK to directly upload a test location to the LOCATION#LIST + /// entry so we can use it in our tests. + /// + public async Task InitializeAsync() + { + // Get the LOCATION#LIST item from DynamoDB + var table = Table.LoadTable(_dynamoDbClient, _environmentFixture.DynamoDbTable); + Document locationList = await table.GetItemAsync("LOCATION#LIST"); + + // The LOCATION#LIST is a List data type + // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes.Document.List + // Create a new DynamoDBList object to add the test location + var updatedLocationList = new DynamoDBList(); + + // Convert the test location into a DynamoDB entry from a string + var testLocationEntry = DynamoDBEntryConversion.V2.ConvertToEntry(UniqueTestLocation); + if (locationList is null) + { + updatedLocationList.Add(testLocationEntry); + } + else + { + // If the location list already has entries, add them to the updatedLocationList + // before we add our test location. Otherwise, the LOCATIONS attribute would be wholly + // replaced with just the new test location, erasing the existing locations. + updatedLocationList = locationList["LOCATIONS"].AsDynamoDBList(); + updatedLocationList.Add(testLocationEntry); + } + + // Store the new list of locations + await table.PutItemAsync(new Document + { + ["PK"] = "LOCATION#LIST", + ["LOCATIONS"] = updatedLocationList + }); + } + + /// + /// Runs at the completion of all tests in a given class + /// + /// + /// This method is implemented as part of the interface. + /// It is here that we use the DynamoDB module of the .NET SDK to remove the test location from the LOCATION#LIST + /// entry so we can clean up after the tests finish. + /// + public async Task DisposeAsync() + { + // Convert the test location into a DynamoDB entry from a string + DynamoDBEntry testLocationEntry = DynamoDBEntryConversion.V2.ConvertToEntry(UniqueTestLocation); + var table = Table.LoadTable(_dynamoDbClient, _environmentFixture.DynamoDbTable); + + // Setup variables to keep track of polling + DynamoDBList locations = null; + var pollMaxTime = TimeSpan.FromSeconds(30); + var pollCompleteSeconds = TimeSpan.Zero; + + // When reading from DynamoDB values are sometimes eventually consistent + // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html + // This loop repeatedly retrieves the LOCATIONS#LIST key until our UniqueTestLocation is present + // or the timeout has elapsed + while (pollCompleteSeconds < pollMaxTime) + { + Document locationsList = await table.GetItemAsync("LOCATION#LIST"); + locations = locationsList["LOCATIONS"].AsDynamoDBList(); + var indexUpdated = locations?.AsArrayOfString().Contains(UniqueTestLocation) ?? false; + if (indexUpdated) + { + break; + } + else + { + Thread.Sleep(TimeSpan.FromSeconds(1)); + pollCompleteSeconds = pollCompleteSeconds.Add(TimeSpan.FromSeconds(1)); + } + } + + // Remove the UniqueTestLocation from the list retrieved from DynamoDB + locations?.Entries.Remove(testLocationEntry); + + // Store the new list of locations + await table.PutItemAsync(new Document + { + ["PK"] = "LOCATION#LIST", + ["LOCATIONS"] = locations + }); + + _dynamoDbClient?.Dispose(); + } +} diff --git a/workshops/serverless-testing-workshop/tests/integration/dotnet/completed-solution/UnicornReservationSystem.Tests.Integration/LocationTests.cs b/workshops/serverless-testing-workshop/tests/integration/dotnet/completed-solution/UnicornReservationSystem.Tests.Integration/LocationTests.cs new file mode 100644 index 00000000..b0d524ff --- /dev/null +++ b/workshops/serverless-testing-workshop/tests/integration/dotnet/completed-solution/UnicornReservationSystem.Tests.Integration/LocationTests.cs @@ -0,0 +1,61 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved + * + * SPDX-License-Identifier: MIT-0 + */ + +using System.Collections.Generic; +using System.Net; +using System.Text.Json; +using System.Threading.Tasks; + +using UnicornReservationSystem.Tests.Integration.Fixtures; + +using Xunit; + +namespace UnicornReservationSystem.Tests.Integration; + +[Collection("Environment")] +public class LocationTests : IClassFixture +{ + private readonly EnvironmentFixture _environmentFixture; + private readonly LocationFixture _locationFixture; + + public LocationTests(EnvironmentFixture environmentFixture, LocationFixture locationFixture) + { + _environmentFixture = environmentFixture; + _locationFixture = locationFixture; + } + + [Fact] + public async Task Api_ConnectivityCheck_Returns200() + { + var response = await _locationFixture.UnicornApi.GetAsync("locations/"); + + Assert.True(response.IsSuccessStatusCode); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact] + public async Task Api_GetCorrectLocations_ReturnsLocations() + { + var response = await _locationFixture.UnicornApi.GetAsync("locations/"); + var content = await response.Content.ReadAsStringAsync(); + var result = JsonSerializer.Deserialize>(content); + + Assert.True(response.IsSuccessStatusCode); + Assert.Contains(_locationFixture.UniqueTestLocation, result["locations"]); + } + + [Fact] + public async Task Api_IncorrectLocationsUrl_ReturnsError() + { + var response = await _locationFixture.UnicornApi.GetAsync("incorrect-locations/"); + var content = await response.Content.ReadAsStringAsync(); + var result = JsonSerializer.Deserialize>(content); + + Assert.False(response.IsSuccessStatusCode); + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.Equal("Missing Authentication Token", result["message"].ToString()); + } +} diff --git a/workshops/serverless-testing-workshop/tests/integration/dotnet/completed-solution/UnicornReservationSystem.Tests.Integration/UnicornReservationSystem.Tests.Integration.csproj b/workshops/serverless-testing-workshop/tests/integration/dotnet/completed-solution/UnicornReservationSystem.Tests.Integration/UnicornReservationSystem.Tests.Integration.csproj new file mode 100644 index 00000000..ec7ecb69 --- /dev/null +++ b/workshops/serverless-testing-workshop/tests/integration/dotnet/completed-solution/UnicornReservationSystem.Tests.Integration/UnicornReservationSystem.Tests.Integration.csproj @@ -0,0 +1,28 @@ + + + + net8.0 + disable + disable + + false + true + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + +