public async Task WhenEtagStale_ItShouldThrowException()
            {
                // Arrange
                var documentStore = await FixtureHelper.CreateDocumentStore();

                var session1  = documentStore.CreateSession();
                var document1 = new TestDocument {
                    Id = Guid.NewGuid().ToString(), PartitionKey = "Tests"
                };

                session1.Add(document1);
                await session1.SaveChanges();

                // Cause the etag to become stale
                var session2 = documentStore.CreateSession();
                await session2.LoadMany <TestDocument>(new[] { document1.Id });

                await session2.SaveChanges();

                // Act
                var exception = await Assert.ThrowsAsync <DocumentSessionException>(() => session1.SaveChanges());

                // Assert
                Assert.StartsWith("Received response status PreconditionFailed from Cosmos Db", exception.Message);
            }
            public async Task WhenDocumentIdsProvided_ItShouldLoadTheDocuments()
            {
                // Arrange
                var documentStore = await FixtureHelper.CreateDocumentStore();

                var session   = documentStore.CreateSession();
                var document1 = new TestDocument {
                    Id = Guid.NewGuid().ToString(), PartitionKey = "Tests"
                };

                session.Add(document1);
                var document2 = new TestDocument {
                    Id = Guid.NewGuid().ToString(), PartitionKey = "Tests"
                };

                session.Add(document2);
                await session.SaveChanges();

                session = documentStore.CreateSession();

                // Act
                var documents = await session.LoadMany <TestDocument>(new[] { document1.Id, document2.Id });

                // Assert
                Assert.Contains(documents.Keys, id => document1.Id == id);
                Assert.NotNull(documents[document1.Id]);
                Assert.Contains(documents.Keys, id => document2.Id == id);
                Assert.NotNull(documents[document2.Id]);
            }
示例#3
0
        public void TestVictoryPoint(byte level, decimal occupiedDays, decimal bonusDays, decimal serverDays, decimal expectedValue)
        {
            var serverDate = SystemClock.Now.Subtract(TimeSpan.FromDays((double)serverDays));

            var systemVariableManager = Substitute.For <ISystemVariableManager>();

            systemVariableManager["Server.date"].Returns(new SystemVariable("Server.date", serverDate));

            var fixture = FixtureHelper.Create();

            fixture.Register(() => systemVariableManager);
            fixture.Customize <Formula>(c => c.FromFactory(new MethodInvoker(new GreedyConstructorQuery())));

            var stronghold = Substitute.For <IStronghold>();

            stronghold.StrongholdState.Returns(StrongholdState.Occupied);
            stronghold.Lvl.Returns(level);
            stronghold.BonusDays.Returns(bonusDays);
            var occupiedDate = SystemClock.Now.Subtract(TimeSpan.FromDays((double)occupiedDays));

            stronghold.DateOccupied.Returns(occupiedDate);

            var formula = fixture.Create <Formula>();

            formula.StrongholdVictoryPoint(stronghold).Should().Be(expectedValue);
        }
示例#4
0
        public BootstrapFixture()
        {
            // We define the connection string to be used withing this fixture.
            SetConnectionString(SqlInstanceName, Catalog);

            //
            CreateSqlInstance();
            FixtureHelper.DeployDatabase(CurrentConnectionString);
        }
示例#5
0
        public void TestLaborMoveWithOvertime(int labor, IEnumerable <Effect> effects, int expected)
        {
            var formula   = FixtureHelper.Create().Create <Formula>();
            var structure = Substitute.For <IStructure>();

            structure.City.GetTotalLaborers().Returns(160);
            structure.City.Technologies.GetEffects(EffectCode.LaborMoveTimeMod).Returns(effects);

            formula.LaborMoveTime(structure, (ushort)labor, true).Should().Be(expected);
        }
        private void ImportData()
        {
            var helper = new FixtureHelper();

            using (var cleaner = new FileCleaner()) {
                var sampleData = helper.Run <SampleData>();
                cleaner.Watch(sampleData.Files.Select(x => x.LocalFileName).Where(x => x != null));
                helper.Run(new LoadSampleData(sampleData.Files));
            }
        }
            public async Task WhenContainerInfoHasBeenSupplied_ItShouldReturnDocumentSession()
            {
                // Arrange
                var documentStore = await FixtureHelper.CreateDocumentStore();

                // Act
                var session = documentStore.CreateSession();

                // Assert
                Assert.NotNull(session);
            }
示例#8
0
        public void LoadFromString_WithValidManifest_Deserializes()
        {
            var json   = File.ReadAllText(FixtureHelper.FixturePath("Manifests", "livery.json"));
            var result = Sideloader.FlightSim.Manifest.LoadFromString(json);

            Assert.Equal("Open Livery Studios", result.Creator);
            Assert.Equal("AIRCRAFT", result.ContentType);
            Assert.Equal("A320 Neo - Lufthansa", result.Title);
            Assert.Equal(Version.Parse("2.0.1"), result.PackageVersion);
            Assert.Equal(Version.Parse("1.7.12"), result.MinimumGameVersion);
            Assert.Equal("Airbus", result.Manufacturer);
        }
示例#9
0
        public void TestNonOccupiedVictoryPoint()
        {
            var formula = FixtureHelper.Create().Create <Formula>();

            var stronghold = Substitute.For <IStronghold>();

            stronghold.StrongholdState.Returns(StrongholdState.Neutral);
            stronghold.Lvl.Returns((byte)5);
            stronghold.BonusDays.Returns(10);
            stronghold.DateOccupied.Returns(SystemClock.Now.Subtract(TimeSpan.FromDays(10)));

            formula.StrongholdVictoryPoint(stronghold).Should().Be(0);
        }
示例#10
0
        public void GetNumberOfHits_WhenObjectIsNotSplashEvery200(ICombatObject attacker, ICombatList defenderCombatList)
        {
            var objectTypeFactory = Substitute.For <IObjectTypeFactory>();
            var fixture           = FixtureHelper.Create();

            fixture.Register(() => objectTypeFactory);
            var battleFormulas = fixture.Create <BattleFormulas>();

            objectTypeFactory.IsObjectType(string.Empty, 0).ReturnsForAnyArgs(false);
            attacker.Stats.Splash.Returns((byte)2);
            defenderCombatList.UpkeepExcludingWaitingToJoinBattle.Returns(800);
            battleFormulas.GetNumberOfHits(attacker, defenderCombatList).Should().Be(2);
        }
示例#11
0
        public void StrongholdGateLimit_WhenMoreThan30Days1000Hours(ISystemVariableManager systemVariableManager)
        {
            systemVariableManager["Server.date"].Returns(new SystemVariable("Server.date", DateTime.MinValue));

            var fixture = FixtureHelper.Create();

            fixture.Register(() => systemVariableManager);
            fixture.Customize <Formula>(c => c.FromFactory(new MethodInvoker(new GreedyConstructorQuery())));

            var formula = fixture.Create <Formula>();

            SystemClock.SetClock(DateTime.MinValue.Add(new TimeSpan(30, 2000, 0, 0)));
            formula.StrongholdGateLimit(1).Should().Be(20000);
        }
示例#12
0
    public void SingleMethod()
    {
        var assemblyPath = FixtureHelper.IsolateAssembly <StandardAssemblyToProcessReference>();
        var type         = typeof(MethodRefTestCases);
        var methodName   = nameof(MethodRefTestCases.ReturnMethodHandle);

        using var module = ModuleDefinition.ReadModule(assemblyPath);
        var weavingContext = new ModuleWeavingContext(module, new WeaverConfig(null, module));

        var typeDef   = module.GetTypes().Single(i => i.FullName == type.FullName);
        var methodDef = typeDef.Methods.Single(i => i.Name == methodName);

        new MethodWeaver(weavingContext, methodDef, NoOpLogger.Instance).Process();
    }
示例#13
0
        public void StrongholdMainBattleMeter_WhenLessThanOrEqualTo30Days999Hours(ISystemVariableManager systemVariableManager)
        {
            systemVariableManager["Server.date"].Returns(new SystemVariable("Server.date", DateTime.MinValue));

            var fixture = FixtureHelper.Create();

            fixture.Register(() => systemVariableManager);
            fixture.Customize <Formula>(c => c.FromFactory(new MethodInvoker(new GreedyConstructorQuery())));

            var formula = fixture.Create <Formula>();

            SystemClock.SetClock(DateTime.MinValue.Add(new TimeSpan(30, 999, 0, 0)));
            formula.StrongholdMainBattleMeter(1).Should().Be(1996);
        }
示例#14
0
        public void StrongholdMainBattleMeter_WhenNegativeTime(ISystemVariableManager systemVariableManager)
        {
            systemVariableManager["Server.date"].Returns(new SystemVariable("Server.date", DateTime.MaxValue));

            var fixture = FixtureHelper.Create();

            fixture.Register(() => systemVariableManager);
            fixture.Customize <Formula>(c => c.FromFactory(new MethodInvoker(new GreedyConstructorQuery())));

            var formula = fixture.Create <Formula>();

            SystemClock.SetClock(DateTime.MaxValue.Subtract(new TimeSpan(30, 0, 0, 0)));
            formula.StrongholdMainBattleMeter(1).Should().Be(250);
        }
示例#15
0
        protected void DeployDatabase()
        {
            var dacPacPath = Path.Combine(AppContext.BaseDirectory, @"..\..\..\..\..", FixtureHelper.ComplianceDacPac);
            var fileInfo   = new FileInfo(dacPacPath);

            if (!fileInfo.Exists)
            {
                throw new FileNotFoundException("Couldn't find dacpac file. Please make sure the database project has been built.");
            }

            var args = $"/Action:Publish /SourceFile:\"{fileInfo.FullName}\" /TargetConnectionString:\"{connString}";

            FixtureHelper.RunExternalProcess(FindSqlPackage(), args);
        }
示例#16
0
        public IActionResult GenerateFixtures(Guid competitionId)
        {
            var competition = GetById(competitionId);

            if (competition == null)
            {
                return(BadRequest());
            }

            var teams    = Context.CompetitionsTeams.Where(o => o.Competition == competition).Select(c => c.Team).ToList();
            var fixtures = FixtureHelper.CreateRandomFixtures(teams, competition.IsTwoLeggedTie);

            return(Ok(fixtures));
        }
示例#17
0
        public IActionResult GetLadder(Guid competitionId)
        {
            var competition = GetById(competitionId);

            if (competition == null)
            {
                return(BadRequest());
            }

            var teams      = Context.CompetitionsTeams.Where(o => o.Competition == competition).Select(c => c.Team).ToList();
            var resultRows = FixtureHelper.BuildLadder(competition, teams);

            return(Ok(resultRows));
        }
            public async Task WhenDocumentNotFound_ItShouldReturnNull()
            {
                // Arrange
                var documentStore = await FixtureHelper.CreateDocumentStore();

                var session    = documentStore.CreateSession();
                var documentId = Guid.NewGuid().ToString();

                // Act
                var documents = await session.LoadMany <TestDocument>(new[] { documentId });

                // Assert
                Assert.Contains(documents.Keys, id => documentId == id);
                Assert.Null(documents[documentId]);
            }
示例#19
0
        public void TestGateBaseValue(int level, int expectedValue)
        {
            var systemVariableManager = Substitute.For <ISystemVariableManager>();

            systemVariableManager["Server.date"].Returns(new SystemVariable("Server.date", DateTime.MinValue));

            var fixture = FixtureHelper.Create();

            fixture.Register(() => systemVariableManager);

            var formula = fixture.Create <Formula>();

            SystemClock.SetClock(DateTime.MinValue);
            formula.StrongholdGateLimit((byte)level).Should().Be(expectedValue);
        }
示例#20
0
    static InvalidAssemblyToProcessFixture()
    {
        var weavingTask = new ModuleWeaver();

        TestResult = weavingTask.ExecuteTestRun(
            FixtureHelper.IsolateAssembly <InvalidAssemblyToProcessReference>(),
            false,
            beforeExecuteCallback: AssemblyToProcessFixture.BeforeExecuteCallback
            );

        using var assemblyResolver = new TestAssemblyResolver();

        ResultModule = ModuleDefinition.ReadModule(TestResult.AssemblyPath, new ReaderParameters(ReadingMode.Immediate)
        {
            AssemblyResolver = assemblyResolver
        });
    }
示例#21
0
        public void TestMoveFromBattleToNormal(TroopStub stub)
        {
            Global.Current = Substitute.For <IGlobal>();
            Global.Current.FireEvents.Returns(false);
            stub.AddFormation(FormationType.Normal);
            stub.AddFormation(FormationType.Garrison);
            stub.AddFormation(FormationType.InBattle);
            stub.AddUnit(FormationType.Normal, 101, 10);

            var fixture   = FixtureHelper.Create();
            var procedure = fixture.Create <CityBattleProcedure>();

            procedure.MoveUnitFormation(stub, FormationType.Normal, FormationType.InBattle);
            procedure.MoveUnitFormation(stub, FormationType.InBattle, FormationType.Normal);

            Assert.True(stub[FormationType.Normal].Type == FormationType.Normal);
            Assert.True(stub[FormationType.InBattle].Type == FormationType.InBattle);
        }
            public async Task WhenDocumentHasAlreadyBeenAdded_ItShouldThrowInvalidOperationException()
            {
                // Arrange
                var documentStore = await FixtureHelper.CreateDocumentStore();

                var session  = documentStore.CreateSession();
                var document = new TestDocument {
                    Id = Guid.NewGuid().ToString(), PartitionKey = "Tests"
                };

                session.Add(document);

                // Act
                var exception = Assert.Throws <InvalidOperationException>(() => session.Add(document));

                // Assert
                Assert.StartsWith("A document with id", exception.Message);
            }
示例#23
0
        public void CityValueShouldReturnProperValue(IEnumerable <IStructure> structures, int expected)
        {
            var fixture = FixtureHelper.Create();

            var objectTypeFactory = fixture.Freeze <IObjectTypeFactory>();

            // Structures with id less than 100 count towards Influence, others dont
            objectTypeFactory.IsStructureType("NoInfluencePoint", Arg.Any <IStructure>())
            .Returns(args => ((IStructure)args[1]).Type >= 100);

            var formula = fixture.Create <Formula>();

            var city = Substitute.For <ICity>();

            city.GetEnumerator().Returns(structures.GetEnumerator());

            formula.CalculateCityValue(city).Should().Be((ushort)expected);
        }
        public static void Log(Fixture fixture)
        {
            var path = GetPath(fixture);

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            var sequence     = fixture.Sequence;
            var filename     = sequence + ".json";
            var fullFilename = Path.Combine(path, filename);

            if (!File.Exists(fullFilename))
            {
                var json = FixtureHelper.ToJson(fixture);
                System.IO.File.WriteAllText(fullFilename, json);
            }
        }
示例#25
0
        public void GetDmgModifier_WhenOver5Rounds(WeaponType weaponType, ArmorType armorType, double dmg)
        {
            var unitModFactory = Substitute.For <UnitModFactory>();

            var fixture = FixtureHelper.Create();

            fixture.Register(() => unitModFactory);
            var battleFormulas = fixture.Create <BattleFormulas>();

            unitModFactory.GetModifier(0, 0).ReturnsForAnyArgs(1);

            var attacker = Substitute.For <ICombatObject>();
            var defender = Substitute.For <ICombatObject>();

            attacker.Stats.Base.Weapon.Returns(WeaponType.Sword);
            defender.Stats.Base.Armor.Returns(ArmorType.Building1);

            battleFormulas.GetDmgModifier(attacker, defender, 5).Should().Be(1);
        }
            public async Task WhenDocumentHasNotBeenSavedToStorage_ItShouldBeRetrievable()
            {
                // Arrange
                var documentStore = await FixtureHelper.CreateDocumentStore();

                var session  = documentStore.CreateSession();
                var document = new TestDocument {
                    Id = Guid.NewGuid().ToString(), PartitionKey = "Tests"
                };

                session.Add(document);

                // Act
                var results = await session.LoadMany <TestDocument>(new [] { document.Id });

                // Assert
                Assert.Contains(results, pair => pair.Key == document.Id);
                Assert.Same(document, results[document.Id]);
            }
示例#27
0
        public void Execute(string name, int count = 1)
        {
            var type   = GetTypes().FirstOrDefault(t => t.Name.Match(name));
            var method = GetMethods().FirstOrDefault(m => m.Name.Match(name));

            if (type == null && method == null)
            {
                Console.WriteLine("Не удалось найти набор тестовых данных '{0}'," +
                                  " используй list что просмотреть доступные наборы", name);
                return;
            }

            for (var i = 0; i < count; i++)
            {
                if (type != null)
                {
                    new FixtureHelper(verbose: true).Run(type);
                }
                else
                {
                    var factory = FixtureHelper.GetFactory();
                    if (method.GetCustomAttributes(typeof(ServiceAttribute)).Any())
                    {
                        factory = DbHelper.ServerNHConfig("local");
                    }

                    using (var session = factory.OpenSession())
                        using (session.BeginTransaction()) {
                            var infos = method.GetParameters();
                            if (infos.Length > 1 && infos[1].ParameterType == typeof(bool))
                            {
                                method.Invoke(null, new object[] { session, true });
                            }
                            else
                            {
                                method.Invoke(null, new object[] { session });
                            }
                            session.Transaction.Commit();
                        }
                }
            }
        }
示例#28
0
        public void HiddenResourceWithBasementsShouldProtectResources(byte[] basementLevels,
                                                                      decimal ap,
                                                                      bool checkApBonus,
                                                                      Resource cityResourceLimit,
                                                                      Resource expectedOutput)
        {
            var fixture = FixtureHelper.Create();

            var city = Substitute.For <ICity>();

            var basements = new List <IStructure>();

            foreach (byte basementLevel in basementLevels)
            {
                var basement = Substitute.For <IStructure>();
                basement.Lvl.Returns(basementLevel);
                basements.Add(basement);
            }

            city.GetEnumerator().Returns(args => basements.GetEnumerator());
            city.Resource.Crop.Limit.Returns(cityResourceLimit.Crop);
            city.Resource.Gold.Limit.Returns(cityResourceLimit.Gold);
            city.Resource.Wood.Limit.Returns(cityResourceLimit.Wood);
            city.Resource.Iron.Limit.Returns(cityResourceLimit.Iron);
            city.Resource.Labor.Limit.Returns(cityResourceLimit.Labor);
            city.AlignmentPoint.Returns(ap);

            var objectTypeFactory = fixture.Freeze <IObjectTypeFactory>();

            objectTypeFactory.IsStructureType("Basement", Arg.Any <IStructure>()).Returns(true);

            var formula = fixture.Create <Formula>();

            var hiddenResources = formula.HiddenResource(city, checkApBonus);

            hiddenResources.CompareTo(expectedOutput)
            .Should()
            .Be(0,
                "Expected {0} but found {1}",
                expectedOutput.ToNiceString(),
                hiddenResources.ToNiceString());
        }
            public async Task WhenDocumentMarkedForRemoval_ItShouldNotBeAbleToBeLoaded()
            {
                // Arrange
                var documentStore = await FixtureHelper.CreateDocumentStore();

                var session  = documentStore.CreateSession();
                var document = new TestDocument {
                    Id = Guid.NewGuid().ToString(), PartitionKey = "Tests"
                };

                session.Add(document);
                session.Remove(document);

                // Act
                var results = await session.LoadMany <TestDocument>(new [] { document.Id });

                // Assert
                Assert.Contains(results, pair => pair.Key == document.Id);
                Assert.Null(results[document.Id]);
            }
        private Fixture RetrieveSnapshot()
        {
            _logger.Debug($"Getting snapshot for {_resource}");

            string snapshotJson = null;

            try
            {
                snapshotJson = _resource.GetSnapshot();
            }
            catch (Exception ex)
            {
                var apiError = new ApiException($"GetSnapshot for {_resource} failed", ex);
                UpdateStatsError(apiError);
                throw apiError;
            }

            if (string.IsNullOrEmpty(snapshotJson))
            {
                throw new Exception($"Received empty snapshot for {_resource}");
            }

            var snapshot = FixtureHelper.GetFromJson(snapshotJson);

            if (snapshot == null || snapshot != null && snapshot.Id.IsNullOrWhiteSpace())
            {
                throw new Exception($"Received a snapshot that resulted in an empty snapshot object {_resource}"
                                    + Environment.NewLine +
                                    $"Platform raw data=\"{snapshotJson}\"");
            }

            if (snapshot.Sequence < _currentSequence)
            {
                throw new Exception(
                          $"Received snapshot {snapshot} with sequence lower than currentSequence={_currentSequence}");
            }

            _fixtureStartTime = snapshot.StartTime;

            return(snapshot);
        }