Ejemplo n.º 1
0
        public IEnumerator OutOfGameTime_DoesNotUpdateOnSave(
            [ValueSource(nameof(RealSeconds))] double secondsOutOfGame
            )
        {
            FortuneFountainSaveData fortuneFountainSaveData =
                FortuneFountainSaveData.NewSaveFile(nameof(OutOfGameTime_DoesNotUpdateOnSave));

            var outOfGameSpan = TimeSpan.FromSeconds(secondsOutOfGame);

            //Set the OutOfGameTimeSinceLastThrow (using reflection since the setter is private)
            fortuneFountainSaveData.GetType().GetProperty(nameof(FortuneFountainSaveData.OutOfGameTimeSinceLastThrow))
            ?.SetValue(fortuneFountainSaveData, outOfGameSpan);

            Assert.That(fortuneFountainSaveData.OutOfGameTimeSinceLastThrow, Is.EqualTo(outOfGameSpan));

            const int repetitions = 5;

            for (int rep = 0; rep < repetitions; rep++)
            {
                yield return(new WaitForSecondsRealtime(0.01f));

                fortuneFountainSaveData.Save(false);

                Assert.That(fortuneFountainSaveData.OutOfGameTimeSinceLastThrow, Is.EqualTo(outOfGameSpan),
                            $"[{nameof(rep)}: {rep}] The {nameof(FortuneFountainSaveData.OutOfGameTimeSinceLastThrow)} should not have changed when we {nameof(FortuneFountainSaveData.Save)}-ed!");
            }
        }
Ejemplo n.º 2
0
        public void TestSerializeThrowables()
        {
            const string            nickName = nameof(TestSerializeThrowables);
            FortuneFountainSaveData fortuneFountainSaveData = FortuneFountainSaveData.NewSaveFile(nickName);

            for (int i = 0; i < ValuableDatabase.ValuableTypes.Length; i++)
            {
                // copying `i` into `index` inside the loop 'cus otherwise lambdas can get messed up
                var index        = i;
                var karmaValue   = Random.Range(1, 25);
                var valuableType = ValuableDatabase.ValuableTypes[index];
                Log($"Grabbing a {valuableType} with a value of {karmaValue}");
                fortuneFountainSaveData.Hand.AddToHand(new ThrowableValuable(valuableType, karmaValue));
                fortuneFountainSaveData.Save(useReSaveDelay: false);

                Log($"before loading throwables:", fortuneFountainSaveData.Hand.Throwables.JoinLines());

                //load the save data we created
                FortuneFountainSaveData loadedSaveData = FortuneFountainSaveData.Load(nickName);

                Log($"original SaveData:", fortuneFountainSaveData);
                Log($"loaded SaveData:", loadedSaveData);

                AssertAll.Of(
                    () => Assert.That(loadedSaveData.ToJson(), Contains.Substring($"\"{nameof(Hand._throwables)}\":")),
                    () => Assert.That(loadedSaveData.Hand.Throwables.Count, Is.EqualTo(index + 1)),
                    () => Assert.That(loadedSaveData.Hand.Throwables[index] as ThrowableValuable,
                                      Has.Property(nameof(ThrowableValuable.ValuableType)).EqualTo(valuableType)),
                    () => Assert.That(loadedSaveData.Hand.Throwables[index] as ThrowableValuable,
                                      Has.Property(nameof(ThrowableValuable.PresentValue)).EqualTo(karmaValue))
                    );
            }
        }
Ejemplo n.º 3
0
        public void ReductionWorks(int iterations, double maxIncrementsPerIteration)
        {
            var incrementer = new Incrementer();

            for (int i = 0; i < iterations; i++)
            {
                incrementer.AddIncrements(Brandom.Gen.NextDouble() * maxIncrementsPerIteration);
            }

            var exactBeforeReduction   = incrementer.ExactIncrements;
            var fullBeforeReduction    = incrementer.FullIncrements;
            var partialBeforeReduction = incrementer.PartialIncrements;

            Assert.That(exactBeforeReduction - fullBeforeReduction, Is.EqualTo(partialBeforeReduction),
                        $"Before {nameof(incrementer.Reduce)}: {nameof(incrementer.ExactIncrements)} - {nameof(incrementer.FullIncrements)} == {nameof(incrementer.PartialIncrements)}");

            var reductionAmount = incrementer.Reduce();

            AssertAll.Of(
                $"After calling {nameof(incrementer.Reduce)}",
                () => Assert.That(reductionAmount, Is.EqualTo(fullBeforeReduction),
                                  $"{nameof(incrementer.Reduce)} should have returned the previous {nameof(incrementer.FullIncrements)}"),
                () => Assert.That(incrementer.ExactIncrements, Is.EqualTo(partialBeforeReduction),
                                  $"{nameof(incrementer.ExactIncrements)} should equal the previous {nameof(incrementer.PartialIncrements)}"),
                () => Assert.That(incrementer.ExactIncrements, Is.Positive.And.LessThan(1),
                                  $"1 > {nameof(incrementer.ExactIncrements)} >= 0")
                );
        }
Ejemplo n.º 4
0
        public void EmptyFallbackSerializesEmpty()
        {
            var fallback = new Fallback <int>();
            var json     = JsonConvert.SerializeObject(fallback);

            Console.WriteLine(json);
            Assert.That(json, Is.EqualTo(@"{""FallbackValue"":0,""ExplicitValue"":[]}"));
        }
Ejemplo n.º 5
0
        public void DefaultEqualsEmpty()
        {
            Optional <int> a = default;

            Console.WriteLine(a);

            AssertAll.Of(
                a,
                Has.Property(nameof(a.HasValue)).EqualTo(false),
                Is.EqualTo(new Optional <int>())
                );
        }
Ejemplo n.º 6
0
        public void ComputeElapsedIncrements(double periodInSeconds, double elapsedTimeInSeconds,
                                             double expectedIntervalAmount)
        {
            var incrementer = new Incrementer()
            {
                Period = TimeSpan.FromSeconds(periodInSeconds)
            };

            var elapsedTime = TimeSpan.FromSeconds(elapsedTimeInSeconds);

            Assert.That(incrementer.ComputeElapsedIncrements(elapsedTime), Is.EqualTo(expectedIntervalAmount));
        }
Ejemplo n.º 7
0
        public void EmptyEqualsEmpty()
        {
            var a = new Optional <int>();
            var b = new Optional <int>();

            Asserter.Against(a)
            .And(Is.EqualTo(b), "a IsEqualTo b")
            .And(Is.EqualTo(new Optional <int>()))
            .And(Is.EqualTo(default(Optional <int>)))
            .And(it => it == b, Is.True, "a == b")
            .And(it => it.Equals(b), Is.True, "a.Equals(b)")
            .Invoke();
        }
Ejemplo n.º 8
0
        public void TestInGameTimeSinceLastThrowWithoutSaving(
            [ValueSource(nameof(Seconds))] double secondsInGame
            )
        {
            FortuneFountainSaveData fortuneFountainSaveData =
                FortuneFountainSaveData.NewSaveFile(nameof(TestInGameTimeSinceLastThrowWithoutSaving));

            var inGameTime = TimeSpan.FromSeconds(secondsInGame);

            fortuneFountainSaveData.Hand.LastThrowTime = FrameTime.Now - inGameTime;
            Assert.That(fortuneFountainSaveData.InGameTimeSinceLastThrow,
                        Is.InRange(inGameTime.Multiply(0.999), inGameTime.Multiply(1.001)));
        }
Ejemplo n.º 9
0
        public void OptionalEqualsUnboxed_String()
        {
            const string str = "yolo";
            var          a   = new Optional <string>(str);

            AssertAll.Of(
                () => Assert.That(a.Equals(str), "a.Equals(str)"),
                () => Assert.That(a, Is.EqualTo(str)),
                () => Assert.That(a == str, "a == str"),
                () => Assert.That(str == a, "str == a"),
                () => Assert.That(str, Is.EqualTo(a)),
                () => Assert.That(a.Equals(str), "a.Equals(str)")
                );
        }
Ejemplo n.º 10
0
        public void FromList(int numberOfChoices, int numberOfPicks)
        {
            var ls = Enumerable.Range(0, numberOfChoices).ToList();
            var v2 = new FromList <int>(ls);

            var picks = numberOfPicks.Repeat <int>(() => v2).ToList();

            Assert.That(picks, Is.SupersetOf(ls));

            var groups = picks.Group();
            var expectedHitsPerChoice = (double)numberOfPicks / numberOfChoices;

            Assert.That(groups, Has.All.Values().Approximately(expectedHitsPerChoice, expectedHitsPerChoice / 2));
        }
Ejemplo n.º 11
0
        public void TestFirstValuableEnabledOnNewSave()
        {
            const string nickName = nameof(TestFirstValuableEnabledOnNewSave);
            var          fortuneFountainSaveData = FortuneFountainSaveData.NewSaveFile(nickName);

            const ValuableType expectedFirstValuableType = 0;

            Assert.That(fortuneFountainSaveData.PlayerValuables,
                        Has.Some.Property(nameof(PlayerValuable.ValuableType)).EqualTo(expectedFirstValuableType),
                        $"The new save file didn't contain PlayerValuable type 0 ({expectedFirstValuableType})!");

            Assert.That(fortuneFountainSaveData.PlayerValuables.Count, Is.EqualTo(1),
                        "The save file contained extra player valuables!");
        }
Ejemplo n.º 12
0
        public void TestGenerateInterval(
            [ValueSource(nameof(rates))] double rateInItemsPerSecond
            )
        {
            var saveData = new FortuneFountainSaveData(nameof(TestGenerateInterval));
            var pv       = new PlayerValuable(saveData, ValuableType.Coin)
            {
                Rate = rateInItemsPerSecond
            };

            Assert.That(TimeSpan.FromSeconds(1).Divide(pv.GenerateInterval),
                        Is.InRange(Math.Floor(rateInItemsPerSecond), rateInItemsPerSecond * 1.00001));

            Assert.That(pv.GenerateInterval,
                        Is.EqualTo(TimeSpan.FromTicks((long)(TimeSpan.TicksPerSecond / rateInItemsPerSecond))));
        }
Ejemplo n.º 13
0
        public Asserter <AggregateExecutionComparison.TimeComparison> AssertComparison(
            AggregateExecutionComparison.TimeComparison results,
            int expectedComparison
            )
        {
            Constraint ratioConstraint = expectedComparison switch {
                -1 => Is.Positive.And.LessThan(1),
                0 => Is.EqualTo(1),
                1 => Is.Positive.And.GreaterThan(1),
                _ => throw new ArgumentOutOfRangeException(nameof(expectedComparison))
            };

            return(Asserter.Against(results)
                   .And(it => it.First.CompareTo(it.Second), Is.EqualTo(expectedComparison))
                   .And(it => it.Difference.Sign(), Is.EqualTo(expectedComparison))
                   .And(it => it.Ratio, ratioConstraint));
        }
Ejemplo n.º 14
0
        public void TestGenerateIsLimitedByRate()
        {
            const string nickName = nameof(TestGenerateIsLimitedByRate);

            GameManager.SaveData = FortuneFountainSaveData.NewSaveFile(nickName);

            var generateCounter = 0;

            PlayerValuable.GeneratePlayerValuableEvent += (valuable, amount) => generateCounter++;

            LogUtils.Log(GameManager.SaveData.PlayerValuables[0]);
            LogUtils.Log(JsonConvert.SerializeObject(GameManager.SaveData.PlayerValuables[0]));

            for (var i = 0; i < 10; i++)
            {
                GameManager.SaveData.PlayerValuables.CheckGenerate();
                Assert.That(generateCounter, Is.EqualTo(0), $"Error on {i + 1}th generation!");
            }
        }
Ejemplo n.º 15
0
        public void ApproximationConstraint(
            [ValueSource(typeof(PrimitiveUtils), nameof(PrimitiveUtils.NumericTypes))]
            Type actualType,
            [ValueSource(typeof(PrimitiveUtils), nameof(PrimitiveUtils.NumericTypes))]
            Type expectedType,
            [ValueSource(typeof(PrimitiveUtils), nameof(PrimitiveUtils.NumericTypes))]
            Type thresholdType,
            [Values] Clusivity clusivity
            )
        {
            var exp = new ApproximationExpectation(actualType, expectedType, thresholdType);

            Console.WriteLine(exp);

            AssertAll.Of(
                () => Assert.That(exp.Actual, Is.Approximately(exp.Expected_ToPass(clusivity), exp.Threshold, clusivity), $"{nameof(exp.Expected_ToPass)}, {clusivity}"),
                () => Assert.That(exp.Actual, Is.Not.Approximately(exp.Expected_ToFail(clusivity), exp.Threshold, clusivity), $"{nameof(exp.Expected_ToFail)}, {clusivity}")
                );
        }
Ejemplo n.º 16
0
        public void SingleActionTime()
        {
            Action action = Quick;

            //stopwatch version
            var stopwatch = Stopwatch.StartNew();

            action();
            stopwatch.Stop();
            Console.WriteLine($"Stopwatch version: {stopwatch.Elapsed:g}");

            var exTime = new ExecutionTime(action);

            Console.WriteLine($"{nameof(exTime)}: {exTime}");
            Asserter.Against(exTime)
            .And(Has.Property(nameof(exTime.Duration)).CloseTo(SlowSpan, TimeSpan.FromSeconds(0.01)))
            .And(it => it.Execution.Failed, Is.EqualTo(false))
            .And(Has.Property(nameof(exTime.Duration)).CloseTo(stopwatch.Elapsed))
            .Invoke();
        }
Ejemplo n.º 17
0
        public IEnumerator TestPartialUncheckedItemsGeneratedDuringLastSession(
            [Values(0.5)] double previousGenIntervals,
            [Values(3)] double totalItemsToGenerate
            )
        {
            Assume.That(previousGenIntervals, Is.LessThan(1));
            Assume.That(totalItemsToGenerate, Is.GreaterThan(previousGenIntervals));

            GameManager.SaveData =
                FortuneFountainSaveData.NewSaveFile(nameof(TestPartialUncheckedItemsGeneratedDuringLastSession));
            GameManager.SaveData.PlayerValuables = TestData.GetUniformPlayerValuables(GameManager.SaveData);

            yield return(TestUtils.WaitForRealtime(GameManager.SaveData.PlayerValuables[0].GenerateInterval,
                                                   previousGenIntervals));

            GameManager.SaveData.Save(false);

            var genCounters = CreateValuableGenerationCounters(GameManager.SaveData.PlayerValuables);

            yield return(TestUtils.WaitForRealtime(GameManager.SaveData.PlayerValuables[0].GenerateInterval, 2));

            GameManager.SaveData.Reload();

            var sleepIntervals = totalItemsToGenerate - previousGenIntervals + 0.5;

            LogUtils.Log($"{nameof(sleepIntervals)} = {sleepIntervals}");
            yield return(TestUtils.WaitForRealtime(GameManager.SaveData.PlayerValuables[0].GenerateInterval,
                                                   sleepIntervals));

            var itemsGenerated = GameManager.SaveData.PlayerValuables.CheckGenerate();

            Assert.That(itemsGenerated, Has.All.EqualTo(totalItemsToGenerate));
            Assert.That(genCounters,
                        Has.All.Values().EqualTo(new ValuableGenerationCounter()
            {
                Amount = (int)totalItemsToGenerate, Events = 1
            }));
        }
Ejemplo n.º 18
0
 public void ReturnBoxed()
 {
     Assert.That(Boxional(5), Is.TypeOf <Optional <int> >());
 }
Ejemplo n.º 19
0
 public void ReturnUnboxed()
 {
     Assert.That(Unboxional(Optional.Of(5)), Is.TypeOf <int>());
 }
Ejemplo n.º 20
0
        public IEnumerator GenerateAllViaCollectionExtension(
            [Values(true, false)] bool checkThrowables
            )
        {
            const string nickName = nameof(TestGenerateIsLimitedByRate);

            GameManager.SaveData = FortuneFountainSaveData.NewSaveFile(nickName);
            GameManager.SaveData.PlayerValuables = TestData.GetUniformPlayerValuables(GameManager.SaveData);

            Assume.That(GameManager.SaveData.PlayerValuables.Count, Is.GreaterThan(1),
                        "We need to test more than 1 valuable type!");
            Assume.That(GameManager.SaveData.PlayerValuables, Has.All.Property("Rate").EqualTo(1),
                        "All valuables should have a generation rate of 1!");

            //Add counter events for each of the valuables
            var generateCounters = CreateValuableGenerationCounters(GameManager.SaveData.PlayerValuables);

            //Set the LastGenerateTime for each valuable to be their previous interval (that way, they are ready to generate)
            var setTime = FrameTime.Now - GameManager.SaveData.PlayerValuables[0].GenerateInterval;

            GameManager.SaveData.Hand.LastThrowTime = setTime;

            GameManager.SaveData.PlayerValuables.ForEach(it => it.LastGenerateCheckTime = setTime);

            if (checkThrowables)
            {
                Assert.That(GameManager.SaveData.Hand.Throwables.Count, Is.EqualTo(0));
            }

            //Generate stuff
            GameManager.SaveData.PlayerValuables.CheckGenerate();
            Assert.That(generateCounters,
                        Has.All.Values().EqualTo(new ValuableGenerationCounter()
            {
                Events = 1, Amount = 1
            }));

            if (checkThrowables)
            {
                Assert.That(GameManager.SaveData.Hand.Throwables.Count,
                            Is.EqualTo(generateCounters.Sum(it => it.Value.Amount)));
            }

            //sleep so we can expect to generate another item
            yield return(TestUtils.WaitForRealtime(GameManager.SaveData.PlayerValuables[0].GenerateInterval));

            //Generate stuff
            GameManager.SaveData.PlayerValuables.CheckGenerate();
            Assert.That(generateCounters,
                        Has.All.Values().EqualTo(new ValuableGenerationCounter()
            {
                Events = 2, Amount = 2
            }));

            if (checkThrowables)
            {
                Assert.That(GameManager.SaveData.Hand.Throwables.Count,
                            Is.EqualTo(generateCounters.Sum(it => it.Value.Amount)));
            }

            //sleep so that we can expect to generate _2_ more items
            yield return
                (TestUtils.WaitForRealtime(GameManager.SaveData.PlayerValuables[0].GenerateInterval.Multiply(2)));

            //Generate stuff
            GameManager.SaveData.PlayerValuables.CheckGenerate();
            Assert.That(generateCounters,
                        Has.All.Values().EqualTo(new ValuableGenerationCounter()
            {
                Events = 3, Amount = 4
            }));

            if (checkThrowables)
            {
                Assert.That(GameManager.SaveData.Hand.Throwables,
                            Has.Property(nameof(Hand.Throwables.Count)).EqualTo(generateCounters.Sum(it => it.Value.Amount)));
            }
        }
Ejemplo n.º 21
0
        public void GenerateEventsLimitedByMaxGenerateTime(
            double generateTimeLimitInSeconds,
            double itemsPerSecond,
            double extraGenerationSeconds
            )
        {
            //the number of items we expect to generate - which should always be limited by maxGenerationSeconds
            var expectedItemsGenerated = generateTimeLimitInSeconds * itemsPerSecond;

            Ignore.Unless(
                () => Assume.That(generateTimeLimitInSeconds, Is.GreaterThan(0),
                                  $"{nameof(generateTimeLimitInSeconds)} must be greater than 0!"),
                () => Assume.That(itemsPerSecond, Is.GreaterThan(0),
                                  $"{nameof(itemsPerSecond)} must be greater than 0!"),
                () => Assume.That(extraGenerationSeconds, Is.GreaterThanOrEqualTo(0),
                                  $"{nameof(extraGenerationSeconds)} must be positive!"),
                () => Assume.That(expectedItemsGenerated, Is.GreaterThanOrEqualTo(1),
                                  $"{nameof(expectedItemsGenerated)} must be at least 1!")
                );

            //this test is very quick and runs a LOT of times, so we should disable logging to prevent it from being crazy slow
            // LogUtils.locations = LogUtils.Locations.None;

            const string nickName = nameof(GenerateEventsLimitedByMaxGenerateTime);

            GameManager.SaveData = FortuneFountainSaveData.NewSaveFile(nickName);


            //Setting up the player data
            GameManager.SaveData.PlayerValuables =
                TestData.GetUniformPlayerValuables(GameManager.SaveData, itemsPerSecond);
            GameManager.SaveData.Hand.LastThrowTime = FrameTime.Now -
                                                      TimeSpan.FromSeconds(generateTimeLimitInSeconds +
                                                                           extraGenerationSeconds);
            GameManager.SaveData.PlayerValuables.ForEach(it =>
                                                         it.LastGenerateCheckTime = GameManager.SaveData.Hand.LastThrowTime);
            GameManager.SaveData.Hand.GenerateTimeLimit = TimeSpan.FromSeconds(generateTimeLimitInSeconds);

            Assert.That(GameManager.SaveData.PlayerValuables[0].GenerateInterval,
                        Is.LessThanOrEqualTo(GameManager.SaveData.Hand.GenerateTimeLimit),
                        $"We must have enough time to generate at least one item - i.e. {nameof(PlayerValuable.GenerateInterval)} <= {nameof(Hand.GenerateTimeLimit)}!");

            var genCounters = CreateValuableGenerationCounters(GameManager.SaveData.PlayerValuables);

            //Generate the items
            GameManager.SaveData.PlayerValuables.CheckGenerate();

            //Check for the proper number of events & actual items generated
            AssertAll.Of(
                () => Assert.That(
                    GroupThrowables(GameManager.SaveData.Hand.Throwables),
                    Has.All.Values().With.Count.InRange(Math.Floor(expectedItemsGenerated),
                                                        Math.Ceiling(expectedItemsGenerated))
                    ),
                () => Assert.That(genCounters,
                                  Has.All.Values().With.Property(nameof(ValuableGenerationCounter.Events)).EqualTo(1)),
                () => Assert.That(genCounters,
                                  Has.All.Values().With.Property(nameof(ValuableGenerationCounter.Amount))
                                  .InRange(Math.Floor(expectedItemsGenerated), Math.Ceiling(expectedItemsGenerated)))
                );
        }
Ejemplo n.º 22
0
 public void PassUnboxional()
 {
     Assert.That(Unboxional <int>(5), Is.TypeOf <int>());
 }