github.com/myhau/pulumi/pkg/v3@v3.70.2-0.20221116134521-f2775972e587/codegen/testing/test/testdata/output-funcs-tfbridge20/dotnet-extras/Tests/TestHelpers.cs (about) 1 // Copyright 2016-2021, Pulumi Corporation 2 3 using System; 4 using System.Collections.Concurrent; 5 using System.Linq; 6 using System.Threading.Tasks; 7 8 using Pulumi; 9 using Pulumi.Testing; 10 11 namespace Pulumi.Mypkg 12 { 13 public static class TestHelpers 14 { 15 public static async Task<T> Run<T>(IMocks mocks, Func<Output<T>> outputGenerator, TestOptions? options = null) 16 { 17 options = options ?? new TestOptions(); 18 options.ProjectName = HelperStack.RegisterBuilderAsProjectName(outputGenerator); 19 var resources = await Deployment.TestAsync<HelperStack>(mocks, options); 20 var stack = resources.Where(x => x is HelperStack).First() as HelperStack; 21 if (stack != null) 22 { 23 var result = await AwaitOutput(stack.Result); 24 if (result is T) 25 { 26 return (T)result; 27 } 28 else 29 { 30 throw new Exception($"The output did not resolve to the correct type: {result}"); 31 } 32 } 33 else 34 { 35 throw new Exception("Did not find stack"); 36 } 37 } 38 39 public static Output<T> Out<T>(T x) 40 { 41 return Output.Create<T>(x); 42 } 43 44 public static Task<T> AwaitOutput<T>(Output<T> output) 45 { 46 var tcs = new TaskCompletionSource<T>(); 47 Task.Delay(1000).ContinueWith(_ => 48 { 49 tcs.TrySetException(new Exception("Output resolution has timed out")); 50 }); 51 output.Apply(v => 52 { 53 tcs.TrySetResult(v); 54 return v; 55 }); 56 return tcs.Task; 57 } 58 59 public class HelperStack : Stack 60 { 61 private static ConcurrentDictionary<string,Func<Output<object?>>> registry = 62 new ConcurrentDictionary<string,Func<Output<object?>>>(); 63 64 [Output] 65 public Output<object?> Result { get; private set; } 66 67 public HelperStack() 68 { 69 Console.WriteLine(Deployment.Instance.ProjectName); 70 Func<Output<object?>>? outputBuilder; 71 if (!registry.TryGetValue(Deployment.Instance.ProjectName, out outputBuilder)) 72 { 73 throw new Exception("Incorrect use of HelperStack"); 74 } 75 this.Result = outputBuilder.Invoke(); 76 } 77 78 public static string RegisterBuilderAsProjectName<T>(Func<Output<T>> builder) 79 { 80 var projectName = Guid.NewGuid().ToString(); 81 if (!registry.TryAdd(projectName, () => builder().Apply(x => (object?)x))) 82 { 83 throw new Exception("Impossible"); 84 } 85 return projectName; 86 } 87 } 88 } 89 }