public IEnumerable <ITestCollection> OrderTestCollections(IEnumerable <ITestCollection> testCollections)
        {
            var sortedList = new SortedList <int, ITestCollection>();
            var unOrdered  = 100000;

            foreach (var testCollection in testCollections)
            {
                var featureClass = testCollection.TestAssembly
                                   .Assembly.GetType(testCollection.DisplayName.Replace("Test collection for ", string.Empty))
                                   .ToRuntimeType();

                var traits = TraitHelper.GetTraits(featureClass);

                int order;

                if (traits.Any(_ => _.Value.StartsWith("FeatureOrder")))
                {
                    order = Convert.ToInt32(traits.Single(_ => _.Value.StartsWith("FeatureOrder")).Value.Replace("FeatureOrder", string.Empty));
                }
                else
                {
                    unOrdered++;
                    order = unOrdered;
                }

                sortedList.Add(order, testCollection);
            }

            return(sortedList.Values);
        }
Esempio n. 2
0
        public override void Execute()
        {
            if (CompatRegistry.Magic?.IsClassTrait(_thisShop.TraitDef !) == true && TkSettings.ResetClass)
            {
                CompatRegistry.Magic.ResetClass(_pawn);
            }

            TraitHelper.RemoveTraitFromPawn(_pawn, _thisTrait);

            Viewer.Charge(_thisShop.CostToRemove, _thisShop.TraitData?.KarmaTypeForRemoving ?? storeIncident.karmaType);


            TraitHelper.GivePawnTrait(_pawn, _thatTrait);

            Viewer.Charge(_thatShop.CostToAdd, _thatShop.Data?.KarmaType ?? storeIncident.karmaType);

            MessageHelper.SendConfirmation(Viewer.username, "TKUtils.ReplaceTrait.Complete".LocalizeKeyed(_thisTrait.LabelCap, _thatTrait.LabelCap));

            Current.Game.letterStack.ReceiveLetter(
                "TKUtils.TraitLetter.Title".Localize(),
                "TKUtils.TraitLetter.ReplaceDescription".LocalizeKeyed(Viewer.username, _thisTrait.LabelCap, _thatTrait.LabelCap),
                LetterDefOf.NeutralEvent,
                new LookTargets(_pawn)
                );
        }
Esempio n. 3
0
        public void NeverConditionalOuterLoopAttribute()
        {
            var method = System.Reflection.MethodBase.GetCurrentMethod();
            var res    = TraitHelper.GetTraits(method);

            Assert.Empty(res);
        }
Esempio n. 4
0
        public override void Execute([NotNull] Viewer viewer, Pawn pawn)
        {
            if (!viewer.username.Equals("scavenging_mechanic", StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }

            if (!pawn.story.traits.HasTrait(TraitDefOf.Transhumanist))
            {
                if (pawn.story.traits.allTraits.Count >= AddTraitSettings.maxTraits)
                {
                    Trait trait = pawn.story.traits.allTraits.RandomElement();
                    TraitHelper.RemoveTraitFromPawn(pawn, trait);
                }

                TraitHelper.GivePawnTrait(pawn, new Trait(TraitDefOf.Transhumanist));
            }

            if (ResearchProjectDef.Named("Bionics")?.IsFinished == true)
            {
                ApplyBionics(pawn);

                return;
            }

            if (ResearchProjectDef.Named("SimpleProsthetics")?.IsFinished == true)
            {
                ApplyProsthetics(pawn);

                return;
            }

            ApplyMedieval(pawn);
        }
Esempio n. 5
0
        public override bool CanHappen(string msg, [NotNull] Viewer viewer)
        {
            if (!PurchaseHelper.TryGetPawn(viewer.username, out _pawn))
            {
                MessageHelper.ReplyToUser(viewer.username, "TKUtils.NoPawn".Localize());

                return(false);
            }

            var worker = ArgWorker.CreateInstance(CommandFilter.Parse(msg).Skip(2));

            if (!worker.TryGetNextAsTrait(out _thisShop) || !worker.TryGetNextAsTrait(out _thatShop))
            {
                MessageHelper.ReplyToUser(viewer.username, "TKUtils.InvalidTraitQuery".LocalizeKeyed(worker.GetLast()));

                return(false);
            }

            if (!IsUsable(_thisShop, _thatShop))
            {
                MessageHelper.ReplyToUser(
                    viewer.username,
                    $"TKUtils.{(_thisShop.CanRemove ? "" : "Remove")}Trait.Disabled".LocalizeKeyed((_thisShop.CanRemove ? _thatShop : _thisShop).Name.CapitalizeFirst())
                    );

                return(false);
            }

            if (TraitHelper.GetTotalTraits(_pawn) >= AddTraitSettings.maxTraits && WouldExceedLimit())
            {
                MessageHelper.ReplyToUser(viewer.username, "TKUtils.ReplaceTrait.Violation".LocalizeKeyed(_thisShop.Name, _thatShop.Name));

                return(false);
            }

            if (!viewer.CanAfford(TotalPrice))
            {
                MessageHelper.ReplyToUser(viewer.username, "TKUtils.InsufficientBalance".LocalizeKeyed(TotalPrice.ToString("N0"), viewer.GetViewerCoins().ToString("N0")));

                return(false);
            }

            if (!PassesCharacterCheck(viewer))
            {
                return(false);
            }

            if (!PassesModCheck(viewer))
            {
                return(false);
            }

            if (!PassesValidationCheck(viewer))
            {
                return(false);
            }

            return(true);
        }
Esempio n. 6
0
    public void MethodWithNoTraits_ReturnsEmptyList()
    {
        var method = typeof(ClassUnderTest).GetMethod("NoTraits");

        var traits = TraitHelper.GetTraits(method);

        Assert.Empty(traits);
    }
Esempio n. 7
0
        public void AlwaysOuterLoopAttribute()
        {
            var method = System.Reflection.MethodBase.GetCurrentMethod();
            var res    = TraitHelper.GetTraits(method);

            Assert.Single(res);
            Assert.Equal("outerloop", res[0].Value);
        }
Esempio n. 8
0
            private void AddTrait(Pawn pawn)
            {
                if (Item == null)
                {
                    return;
                }

                TraitHelper.GivePawnTrait(pawn, new Trait(Item.TraitDef, Item.Degree));
            }
Esempio n. 9
0
    public void MethodWithTraitAttribute_ReturnsTrait()
    {
        var method = typeof(ClassUnderTest).GetMethod("Trait");

        var traits = TraitHelper.GetTraits(method);

        Assert.Collection(traits.Select(kvp => $"{kvp.Key} = {kvp.Value}").OrderBy(_ => _, StringComparer.OrdinalIgnoreCase),
                          value => Assert.Equal("foo = bar", value)
                          );
    }
Esempio n. 10
0
    public void MethodWithInheritedCustomTraitAttribute_ReturnsTraitValues()
    {
        var method = typeof(ClassUnderTest).GetMethod("InheritedTrait");

        var traits = TraitHelper.GetTraits(method);

        Assert.Collection(traits.Select(kvp => $"{kvp.Key} = {kvp.Value}").OrderBy(_ => _, StringComparer.OrdinalIgnoreCase),
                          value => Assert.Equal("Baz = 2112", value),
                          value => Assert.Equal("Foo = Biff", value)
                          );
    }
Esempio n. 11
0
        public override void Execute()
        {
            TraitHelper.GivePawnTrait(_pawn, _trait);
            Viewer.Charge(_buyableTrait.CostToAdd, _buyableTrait.Data?.KarmaType ?? storeIncident.karmaType);
            MessageHelper.SendConfirmation(Viewer.username, "TKUtils.Trait.Complete".LocalizeKeyed(_trait.Label));

            Current.Game.letterStack.ReceiveLetter(
                "TKUtils.TraitLetter.Title".Localize(),
                "TKUtils.TraitLetter.AddDescription".LocalizeKeyed(Viewer.username, _trait.LabelCap),
                LetterDefOf.NeutralEvent,
                new LookTargets(_pawn)
                );
        }
Esempio n. 12
0
    public void CombinesInheritedMultipleTraitSources()
    {
        var method = typeof(ClassUnderTest).GetMethod("InheritedMultipleTraits");

        var traits = TraitHelper.GetTraits(method);

        Assert.Collection(traits.Select(kvp => $"{kvp.Key} = {kvp.Value}").OrderBy(_ => _, StringComparer.OrdinalIgnoreCase),
                          value => Assert.Equal("Baz = 2112", value),
                          value => Assert.Equal("foo = bar", value),
                          value => Assert.Equal("Foo = Biff", value),
                          value => Assert.Equal("Hello = World", value)
                          );
    }
Esempio n. 13
0
            private void RemoveTrait(Pawn pawn)
            {
                if (Trait == null)
                {
                    return;
                }

                if (CompatRegistry.Magic?.IsClassTrait(Trait.def) == true && TkSettings.ResetClass)
                {
                    CompatRegistry.Magic.ResetClass(pawn);
                }

                TraitHelper.RemoveTraitFromPawn(pawn, Trait);
            }
Esempio n. 14
0
        private static IEnumerable <MethodInfo> RunAllTests(MethodInfo[] tests)
        {
            var failed      = new ConcurrentQueue <MethodInfo>();
            var safeTests   = new ConcurrentQueue <MethodInfo>();
            var unsafeTests = new ConcurrentQueue <MethodInfo>();

            Parallel.ForEach(tests, test =>
            {
                var testCategories = TraitHelper.GetTraits(test)
                                     .Where(trait => trait.Key == "Category")
                                     .Select(trait => trait.Value)
                                     .ToArray();
                bool isUnsafe = testCategories.Any(tc => tc == "CsoftModel" || tc == "ModifiesGlobals" || tc == "DistributedTests" || tc == "Performance");
                if (isUnsafe)
                {
                    unsafeTests.Enqueue(test);
                }
                else
                {
                    safeTests.Enqueue(test);
                }
            });
            // unsafe tests must run sequentially.
            Trace.WriteLine($"Running {unsafeTests.Count} tests sequentially");
            foreach (var test in unsafeTests)
            {
                RunTest(test, failed);
            }
            var safeTestsArray = safeTests.ToArray();

            Array.Sort(safeTestsArray, (a, b) => a.Name.CompareTo(b.Name));
            Trace.WriteLine($"Running {safeTests.Count} tests in parallel");
            try
            {
                Parallel.ForEach(safeTestsArray, test =>
                {
                    RunTest(test, failed);
                });
            }
            catch (AggregateException ex)
            {
                // To make the Visual Studio debugger stop at the inner exception, check "Enable Just My Code" in Debug->Options.
                // throw InnerException while preserving stack trace
                // https://stackoverflow.com/questions/57383/in-c-how-can-i-rethrow-innerexception-without-losing-stack-trace
                System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
                throw;
            }
            return(failed);
        }
Esempio n. 15
0
        public override bool CanHappen(string msg, [NotNull] Viewer viewer)
        {
            if (!PurchaseHelper.TryGetPawn(viewer.username, out _pawn))
            {
                MessageHelper.ReplyToUser(viewer.username, "TKUtils.NoPawn".Localize());

                return(false);
            }

            var worker = ArgWorker.CreateInstance(CommandFilter.Parse(msg).Skip(2));

            if (!worker.TryGetNextAsTrait(out _buyableTrait) || !_buyableTrait.CanAdd || _buyableTrait.TraitDef == null)
            {
                MessageHelper.ReplyToUser(viewer.username, "TKUtils.InvalidTraitQuery".LocalizeKeyed(worker.GetLast()));

                return(false);
            }

            if (!viewer.CanAfford(_buyableTrait !.CostToAdd))
            {
                MessageHelper.ReplyToUser(
                    viewer.username,
                    "TKUtils.InsufficientBalance".LocalizeKeyed(_buyableTrait.CostToAdd.ToString("N0"), viewer.GetViewerCoins().ToString("N0"))
                    );

                return(false);
            }

            if (TraitHelper.GetTotalTraits(_pawn) >= AddTraitSettings.maxTraits && _buyableTrait.TraitData?.CanBypassLimit != true)
            {
                MessageHelper.ReplyToUser(viewer.username, "TKUtils.Trait.LimitReached".LocalizeKeyed(AddTraitSettings.maxTraits));

                return(false);
            }

            if (!PassesCharacterChecks(viewer, worker))
            {
                return(false);
            }

            _trait = new Trait(_buyableTrait.TraitDef, _buyableTrait.Degree);

            return(PassesValidationChecks(viewer) && PassesModChecks(viewer));
        }
Esempio n. 16
0
        internal static MethodInfo[] FindTestMethods(Assembly assembly, string filter = null)
        {
            var methods           = assembly.GetTypes().SelectMany(t => t.GetMethods()).ToArray();
            var excludeCategories = new[] { "BadTest", "OpenBug", "CompilerOptionsTest", "x86" };
            var testMethods       = methods.Where(method =>
            {
                if (!method.GetCustomAttributes().Any(attr => attr is FactAttribute))
                {
                    return(false);
                }
                var categories = TraitHelper.GetTraits(method)
                                 .Where(trait => trait.Key == "Category" || trait.Key == "Platform")
                                 .Select(trait => trait.Value)
                                 .ToArray();
                return(!categories.Any(excludeCategories.Contains) && (filter == null || categories.Contains(filter)));
            }).ToArray();

            return(testMethods);
        }
Esempio n. 17
0
        /// <summary>
        /// Runs xUnit test and appends meta-data to output.
        /// </summary>
        /// <param name="methodName">The test method name.</param>
        /// <param name="testAction">The actual test action.</param>
        private void RunXUnitTest(string methodName, Action testAction)
        {
            MethodInfo testMethodInfo = this.GetType().GetMethod(methodName);

            foreach (KeyValuePair <string, string> trait in
                     TraitHelper.GetTraits(testMethodInfo))
            {
                this.output.WriteLine($"{trait.Key.PadRight(15)}: {trait.Value}");
            }

            Stopwatch testMethodStopwatch = new Stopwatch();

            testMethodStopwatch.Start();

            try
            {
                testAction();
            }
            finally
            {
                testMethodStopwatch.Stop();
                this.output.WriteLine($"Execution Time : {testMethodStopwatch.Elapsed}");
            }
        }
        private static bool MethodMissingCorrectCategoryTrait(MethodInfo method)
        {
            IReadOnlyList <KeyValuePair <string, string> > methodTraits = TraitHelper.GetTraits(method);

            return(!methodTraits.Any(TraitIsValidCategory));
        }