-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy pathEnvironmentRestorerAttribute.cs
More file actions
46 lines (38 loc) · 1.5 KB
/
EnvironmentRestorerAttribute.cs
File metadata and controls
46 lines (38 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// <copyright file="EnvironmentRestorerAttribute.cs" company="Datadog">
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License.
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc.
// </copyright>
using System;
using System.Collections.Generic;
using System.Reflection;
using Xunit.Sdk;
namespace Datadog.Trace.TestHelpers;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class EnvironmentRestorerAttribute : BeforeAfterTestAttribute
{
private readonly string[] _variables;
private readonly Dictionary<string, string> _originalVariables;
public EnvironmentRestorerAttribute(params string[] args)
{
_variables = args;
_originalVariables = new(args.Length);
}
public virtual EnvironmentVariableTarget Target => EnvironmentVariableTarget.Process;
public override void Before(MethodInfo methodUnderTest)
{
foreach (var variable in _variables)
{
_originalVariables[variable] = Environment.GetEnvironmentVariable(variable, Target);
// clear variable
Environment.SetEnvironmentVariable(variable, null, Target);
}
base.Before(methodUnderTest);
}
public override void After(MethodInfo methodUnderTest)
{
foreach (var variable in _originalVariables)
{
Environment.SetEnvironmentVariable(variable.Key, variable.Value, Target);
}
}
}