namespace ZB.MOM.WW.MxGateway.Client.Tests;
///
/// Marks a test that writes to a real Galaxy attribute through a running gateway.
/// The test is skipped unless an endpoint, an API key and a write item are all set,
/// so it never runs (or writes) by accident. See docs/GatewayTesting.md, "Live gateway write".
///
public sealed class LiveGatewayWriteFactAttribute : FactAttribute
{
/// Gateway gRPC endpoint, e.g. http://host:5120.
public const string EndpointVariableName = "MXGATEWAY_LIVE_GATEWAY_ENDPOINT";
/// API key (mxgw_<id>_<secret>). Prefer the file variant so the key stays out of the environment.
public const string ApiKeyVariableName = "MXGATEWAY_LIVE_GATEWAY_API_KEY";
/// Path to a file holding the API key. Takes precedence over .
public const string ApiKeyFileVariableName = "MXGATEWAY_LIVE_GATEWAY_API_KEY_FILE";
/// A writable, test-only Int32 attribute. It is written and then restored. No default on purpose.
public const string WriteItemVariableName = "MXGATEWAY_LIVE_GATEWAY_WRITE_ITEM";
/// Set to 1 to also run the Write2 timestamp-parity test (fails on a non-UTC host until #228 is fixed).
public const string AssertWrite2TimestampVariableName = "MXGATEWAY_LIVE_GATEWAY_ASSERT_WRITE2_TIMESTAMP";
/// Initializes the attribute, skipping unless the live gateway write variables are set.
/// When true, also require =1.
public LiveGatewayWriteFactAttribute(bool requireTimestampOptIn = false)
{
if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(EndpointVariableName))
|| string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(WriteItemVariableName))
|| (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(ApiKeyVariableName))
&& string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(ApiKeyFileVariableName))))
{
Skip = $"Set {EndpointVariableName}, {WriteItemVariableName} and {ApiKeyFileVariableName} (or {ApiKeyVariableName}) to run live gateway write tests.";
}
else if (requireTimestampOptIn
&& Environment.GetEnvironmentVariable(AssertWrite2TimestampVariableName) != "1")
{
Skip = $"Set {AssertWrite2TimestampVariableName}=1 to assert Write2 timestamp parity (mxaccessgw#228).";
}
}
internal static string Endpoint => Environment.GetEnvironmentVariable(EndpointVariableName)!;
internal static string WriteItem => Environment.GetEnvironmentVariable(WriteItemVariableName)!;
internal static string ApiKey
{
get
{
string? path = Environment.GetEnvironmentVariable(ApiKeyFileVariableName);
return !string.IsNullOrWhiteSpace(path)
? File.ReadAllText(path).Trim()
: Environment.GetEnvironmentVariable(ApiKeyVariableName)!.Trim();
}
}
}