A game about forced loneliness, made by TACStudios
1using System;
2using System.Collections.Generic;
3using NUnit.Framework;
4using NUnit.Framework.Interfaces;
5using NUnit.Framework.Internal;
6
7namespace UnityEngine.TestTools
8{
9 /// <summary>
10 /// This attribute is an alternative to the standard `Ignore` attribute in [NUnit](https://nunit.org/). It allows for ignoring tests only under a specified condition. The condition evaluates during `OnLoad`, referenced by ID.
11 /// </summary>
12 public class ConditionalIgnoreAttribute : NUnitAttribute, IApplyToTest
13 {
14 private string m_ConditionKey;
15 private string m_IgnoreReason;
16
17 /// <summary>
18 /// Initializes a new instance of the <see cref="ConditionalIgnoreAttribute"/> class with a condition key.
19 /// </summary>
20 /// <param name="conditionKey">The key to check for enabling the conditional ignore. The condition is set with the static <see cref="AddConditionalIgnoreMapping"/> method.</param>
21 /// <param name="ignoreReason">The reason for the ignore.</param>
22 public ConditionalIgnoreAttribute(string conditionKey, string ignoreReason)
23 {
24 m_ConditionKey = conditionKey;
25 m_IgnoreReason = ignoreReason;
26 }
27
28 /// <summary>
29 /// Modifies a test as defined for the specific attribute.
30 /// </summary>
31 /// <param name="test">The test to modify</param>
32 public void ApplyToTest(Test test)
33 {
34 var key = m_ConditionKey.ToLowerInvariant();
35 if (m_ConditionMap.ContainsKey(key) && m_ConditionMap[key])
36 {
37 test.RunState = RunState.Ignored;
38 string skipReason = string.Format(m_IgnoreReason);
39 test.Properties.Add(PropertyNames.SkipReason, skipReason);
40 }
41 }
42
43 private static Dictionary<string, bool> m_ConditionMap = new Dictionary<string, bool>();
44
45 /// <summary>
46 /// Adds a flag indicating whether tests with the same key should be ignored.
47 /// </summary>
48 /// <param name="key">The key to ignore tests for.</param>
49 /// <param name="value">A boolean value indicating whether the tests should be ignored.</param>
50 /// <example>
51 /// An example in which tests are ignored in the Mac editor only.
52 /// <code>
53 /// using UnityEditor;
54 /// using NUnit.Framework;
55 /// using UnityEngine.TestTools;
56 ///
57 /// [InitializeOnLoad]
58 /// public class OnLoad
59 /// {
60 /// static OnLoad()
61 /// {
62 /// var editorIsOSX = false;
63 /// #if UNITY_EDITOR_OSX
64 /// editorIsOSX = true;
65 /// #endif
66 ///
67 /// ConditionalIgnoreAttribute.AddConditionalIgnoreMapping("IgnoreInMacEditor", editorIsOSX);
68 /// }
69 /// }
70 ///
71 /// public class MyTestClass
72 /// {
73 /// [Test, ConditionalIgnore("IgnoreInMacEditor", "Ignored on Mac editor.")]
74 /// public void TestNeverRunningInMacEditor()
75 /// {
76 /// Assert.Pass();
77 /// }
78 /// }
79 /// </code>
80 /// </example>
81 public static void AddConditionalIgnoreMapping(string key, bool value)
82 {
83 m_ConditionMap.Add(key.ToLowerInvariant(), value);
84 }
85 }
86}