Inheritance: INotifyPropertyChanged
コード例 #1
1
        public void Should_register_converters_when_asked()
        {
            // Given
            var defaultSerializer = new JavaScriptSerializer();
            var configuration = new JsonConfiguration(Encoding.UTF8, new[] { new TestConverter() }, new[] { new TestPrimitiveConverter() }, false, false);

            // When
            var serializer = new JavaScriptSerializer(configuration, true, GlobalizationConfiguration.Default);

            var data =
                new TestData()
                {
                    ConverterData =
                        new TestConverterType()
                        {
                            Data = 42,
                        },

                    PrimitiveConverterData =
                        new TestPrimitiveConverterType()
                        {
                            Data = 1701,
                        },
                };

            const string ExpectedJSON = @"{""converterData"":{""dataValue"":42},""primitiveConverterData"":1701}";

            // Then
            serializer.Serialize(data).ShouldEqual(ExpectedJSON);

            serializer.Deserialize<TestData>(ExpectedJSON).ShouldEqual(data);
        }
コード例 #2
0
        public void VerifyBetInfoInBetslip()
        {
            IWebDriver driver = ((WebDriverBackedSelenium)MyBrowser).UnderlyingWebDriver;
            string EWterms;
            TestData[] testDataLst = new TestData[1];
            testDataLst[0] = new TestData(3, "PreProdEvents");
            Console.WriteLine("***** Executing Test Case --- 'VerifyBetInfoInBetslip', Verify the details on the info frame of the Betslip (user Logged in/Logged out) *****");
            try
            {
                BTcommonObj.WaitForLoadingIcon(MyBrowser, FrameGlobals.IconLoadTimeout);
                BTbetslipObj.OddTypeSwitch(MyBrowser, "decimal");

                // Verify the min/max stake is not displayed in Bet Info if user is logout
                EWterms = BTbetslipObj.AddAndVerifySelectionInBetslip(MyBrowser, "", "Competition", testDataLst[0].ClassName, testDataLst[0].TypeName, testDataLst[0].SubTypeName, testDataLst[0].EventName, testDataLst[0].MarketName, testDataLst[0].SelectionName, testDataLst[0].Odds, true);
                BTbetslipObj.VerifyBetSlip(MyBrowser, testDataLst[0].EventName, testDataLst[0].SelectionName, testDataLst[0].MarketName, testDataLst[0].Odds, EWterms, "Single", 1);

                BTbetslipObj.VerifyBetslipInfo(MyBrowser, testDataLst[0].EventName, testDataLst[0].MarketName, testDataLst[0].SelectionName, testDataLst[0].Odds, EWterms);
                Console.WriteLine("Verification of Bet Info details in Betslip (User Logged Out) was successful");

                // Verify the min/max stake is displayed in the Bet Info on Login
                BTloginLogoutObj.Login(MyBrowser, FrameGlobals.UserName, FrameGlobals.PassWord);
                BTbetslipObj.VerifyBetSlip(MyBrowser, testDataLst[0].EventName, testDataLst[0].SelectionName, testDataLst[0].MarketName, testDataLst[0].Odds, EWterms, "Single", 1);
                BTbetslipObj.VerifyBetslipInfo(MyBrowser, testDataLst[0].EventName, testDataLst[0].MarketName, testDataLst[0].SelectionName, testDataLst[0].Odds, EWterms);
                Console.WriteLine("Verification of Bet Info details in Betslip (User Logged In) was successful");
                Console.WriteLine("TestCase 'VerifyBetInfoInBetslip' - PASS");
            }
            catch (Exception ex)
            {
                CaptureScreenshot(MyBrowser, "VerifyBetInfoInBetslip");
                Console.WriteLine("TestCase 'VerifyBetInfoInBetslip' - FAIL");
                Fail(ex.Message);
            }
        }
コード例 #3
0
 private static TestDataNode AddMetadataNode(TestData testData, string metadataType, 
     TestTreeNode rootNode, Node parentNode)
 {
     var testDataNode = new TestDataNode(testData);
     
     var metadataList = testData.Metadata[metadataType];
     if (metadataList.Count > 0)
     {
         foreach (string metadata in metadataList)
         {
             var metadataNode = FindOrAddMetadataNode(metadataType, rootNode, metadata);
             metadataNode.Nodes.Add(testDataNode);
             testDataNode = new TestDataNode(testData); // can't re-use node
         }
     }
     else if (parentNode != null)
     {
         parentNode.Nodes.Add(testDataNode);
     }
     else
     {
         var metadataNode = FindOrAddMetadataNode(metadataType, rootNode, "None");
         metadataNode.Nodes.Add(testDataNode);
     }
     return testDataNode;
 }
コード例 #4
0
        public void Setup(TrainingData trainData, TestData testData)
        {
            this.trainData = trainData;
            this.testData = testData;

            uod = DataFormatter.GetUserOrderRepositories(trainData);
        }
コード例 #5
0
		public void SetUp()
		{
			this.Data1 = new TestData();
			this.Data2 = new TestData();
			this.Data1.Data = 1;
			this.Data2.Data = 2;
		}
コード例 #6
0
        public TestCase GetTestCase(TestData testData)
        {
            string displayName;

            var fullName = testData.FullName;

            var pos = fullName.LastIndexOf('/');

            if (pos == -1)
            {
                displayName = testData.CodeReference.MemberName;
            }
            else
            {
                displayName = fullName.Substring(pos + 1);
            }

            var testCase = new TestCase(fullName, new Uri(GallioAdapter.ExecutorUri), GetSource(testData))
            {
                CodeFilePath = testData.CodeLocation.Path,
                LineNumber = testData.CodeLocation.Line,
                DisplayName = displayName
            };

            testCase.SetPropertyValue(testIdProperty, testData.Id);

            return testCase;
        }
コード例 #7
0
 private static ExpressionContext GetExpressionContext()
 {
     var expressionOwner = new TestData { Id = "World" };
     var context = new ExpressionContext(expressionOwner);
     context.Imports.AddType(typeof(TestDataExtensions));
     return context;
 }
コード例 #8
0
        public void WithDataContractAndRoundedDouble()
        {
            var data = new TestData
            {
                TestBool = true,
                TestByteArray = new byte[] { 0x00, 0x02, 0x04, 0x05, 0x01 },
                TestDouble = 17.0,
                TestByte = 0xff,
                TestDateTime = new DateTime(2089, 9, 27),
                TestInt = 7,
                TestList = new List<int> { 4, 55, 4, 6, 13 },
                TestLong = 777,
                TestShort = 456,
                TestString = "Hello World!",
                TestChar = 'R',
                TestDecimal = 100,
                TestsByte = 0x05,
                TestuInt = 80,
                DontGo = 42,
                Children = new List<SubTestData> { new SubTestData { Name = "one" }, new SubTestData { Name = "two" } }
            };

            var str = JSON.ToJSON(data);
            var result = JSON.ToObject<TestData>(str);

            VerifyEqual(data, result);
        }
コード例 #9
0
		/// <summary>
		/// Downloads the specified test file and verifies its contents.
		/// </summary>
		private async Task TestFileDownload(TestData.TestFile testFile)
		{
			var target = Path.GetTempFileName();

			try
			{
				Debug.WriteLine("Temporary local file: " + target);

				using (var feedback = new DebugFeedbackChannel("Test"))
				{
					using (var initializing = feedback.BeginSubOperation("InitializeData"))
						await TestData.Current.BringToInitialState(initializing);

					var client = new MegaClient(TestData.Current.Email1, TestData.Current.Password1);
					var filesystem = await client.GetFilesystemSnapshotAsync(feedback);

					var file = testFile.TryFind(filesystem);

					if (file == null)
						Assert.Fail("Could not find expected file to download: " + testFile.Name);

					await file.DownloadContentsAsync(target, feedback);

					using (var expectedContents = testFile.Open())
					using (var contents = File.OpenRead(target))
						TestHelper.AssertStreamsAreEqual(expectedContents, contents);
				}
			}
			finally
			{
				File.Delete(target);
			}
		}
コード例 #10
0
        private static TestTreeNode AddNode(TestData testData, TestTreeNode parent,
            TreeBuilderOptions options)
        {
            var testTreeNode = new TestDataNode(testData);

            if (options.NamespaceHierarchy == NamespaceHierarchy.Flat)
            {
                if (FixtureNode(testData) && parent.TestKind != TestKinds.Namespace)
                {
                    var @namespace = testData.CodeReference.NamespaceName;
                    parent = FindOrAddNamespaceNode(parent, @namespace, @namespace);
                }
                else if (testTreeNode.TestKind == TestKinds.Namespace)
                {
                    return parent;
                }
            }

            if (FixtureNode(testData) && parent.TestKind != TestKinds.Namespace) 
            {
                parent = BuildNamespaceNode(testData, parent, options);
            }
            
            parent.Nodes.Add(testTreeNode);
         
            return testTreeNode;
        }
コード例 #11
0
            public static TestData Create(int stepCount, int machinesPerStep)
            {
                var fixture = new Fixture();
                var returnValue = new TestData
                {
                    DeployBatchRequest = fixture.Build<DeployBatchRequest>()
                                    .With(i=>i.ItemList,
                                            fixture.Build<DeployBatchRequestItem>()
                                                .With(j=>j.MachineList, fixture.CreateMany<DeployMachine>(machinesPerStep).ToList())
                                                .CreateMany(stepCount).ToList())
                                    .Create(),
                    ProjectManager = new Mock<IProjectManager>()
                };
                var deployMachineNameList = fixture.CreateMany("DeployMachineName", machinesPerStep).ToList();
                foreach(var item in returnValue.DeployBatchRequest.ItemList)
                {
                    for(int i = 0; i < machinesPerStep; i++)
                    {
                        item.MachineList[i].MachineName = deployMachineNameList[i];
                    }
                }
                returnValue.Sut = new DeploymentPlanBuilder(returnValue.ProjectManager.Object);

                return returnValue;
            }
コード例 #12
0
        private ObjectModel.TestResult CreateTest(TestData test, TestStepRun stepRun, TestCase testCase)
        {
            ObjectModel.TestResult testResult = new ObjectModel.TestResult(testCase);
            testResult.DisplayName = test.Name;
            testResult.ErrorLineNumber = test.CodeLocation.Line;
            //testResult.ErrorStackTrace
            testResult.StartTime = stepRun.StartTime;
            if (stepRun.TestLog.Streams.Count > 0)
            {
                testResult.ErrorMessage = stepRun.TestLog.Streams[0].ToString();
            }
            testResult.EndTime = stepRun.EndTime;

            testResult.Duration = stepRun.Result.Duration;

            var testStatus = stepRun.Result.Outcome.Status;
            switch (testStatus)
            {
                case TestStatus.Passed:
                    testResult.Outcome = ObjectModel.TestOutcome.Passed;
                    break;
                case TestStatus.Failed:
                    testResult.Outcome = ObjectModel.TestOutcome.Failed;
                    break;
                case TestStatus.Skipped:
                    testResult.Outcome = ObjectModel.TestOutcome.Skipped;
                    break;
                case TestStatus.Inconclusive:
                    testResult.Outcome = ObjectModel.TestOutcome.NotFound;
                    break;
            }

            return testResult;
        }
コード例 #13
0
        public void VerifyBetPlacement()
        {
            string[] aryOdd = new string[1];
            TestData[] testDataLst = new TestData[1];
            testDataLst[0] = new TestData(0, "PreProdEvents");
            aryOdd[0] = testDataLst[0].Odds;
            Console.WriteLine("***** Executing Test Case --- 'VerifyBetPlacement', Verify Single Bet Placement *****");
            try
            {
                BVTcommonObj.WaitForLoadingIcon(MyBrowser, FrameGlobals.IconLoadTimeout);
                BVTloginLogoutObj.Login(MyBrowser, FrameGlobals.UserName, FrameGlobals.PassWord);
                BVTbetslipObj.OddTypeSwitch(MyBrowser, "decimal");

                BVTbetslipObj.AddAndVerifySelectionInBetslip(MyBrowser, "", "Competition", testDataLst[0].ClassName, testDataLst[0].TypeName, testDataLst[0].SubTypeName, testDataLst[0].EventName, testDataLst[0].MarketName, testDataLst[0].SelectionName, testDataLst[0].Odds, false);
                BVTbetslipObj.VerifyBetSlip(MyBrowser, testDataLst[0].EventName, testDataLst[0].SelectionName, testDataLst[0].MarketName, testDataLst[0].Odds, "", "Single", 1);

                BVTbetslipObj.EnterStake(MyBrowser, testDataLst[0].EventName, testDataLst[0].SelectionName, testDataLst[0].MarketName, testDataLst[0].Odds, testDataLst[0].Stake, "", false);
                BVTbetslipObj.VerifyBetDetails(MyBrowser, testDataLst[0].EventName, testDataLst[0].SelectionName, testDataLst[0].MarketName, aryOdd, testDataLst[0].Stake, "", "Single", "", "");
                BVTbetslipObj.ValidateBetReceipt(MyBrowser, "", testDataLst[0].EventName, testDataLst[0].MarketName, testDataLst[0].SelectionName, aryOdd, testDataLst[0].Stake, "", false, "Single", 1);
                Console.WriteLine("TestCase 'VerifyBetPlacement' - PASS");
            }
            catch (Exception ex)
            {
                CaptureScreenshot(MyBrowser, "VerifyBetPlacement");
                Console.WriteLine("TestCase 'VerifyBetPlacement' - FAIL");
                Fail(ex.Message);
            }
        }
コード例 #14
0
        /// <summary>
        /// Method to update and validate event status validations
        /// </summary>
        public void EventStatusValidation(ISelenium browser, ISelenium adminBrowser,TestData testData, string navPanel)
        {
            string eventStatus, updatedStatus;
            string alternateStatus = "Suspended";

            try
            {
                #region Event Status validation

                eventStatus = GetEventStatus(browser, testData.ClassName, navPanel, testData);
                if (eventStatus == "Suspended")
                    alternateStatus = "Active";
                adminCommonObj.UpdateEvents(adminBrowser, testData.CategoryName, testData.ClassName, testData.TypeName, testData.SubTypeName, testData.EventName, alternateStatus);
                Thread.Sleep(FrameGlobals.OpenBetReflectTimeOut);
                Console.WriteLine("Event status is updated in admin");

                updatedStatus = GetEventStatus(browser, testData.ClassName, navPanel, testData);
                Assert.IsFalse(Equals(eventStatus, updatedStatus), "Event status is not updated on the page");

                #endregion

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                CaptureScreenshot(browser, "EventStatusValidation");
            }
        }
コード例 #15
0
ファイル: TabRunStats.cs プロジェクト: lgatto/proteowizard
        public void Process(string logFile)
        {
            var log = File.ReadAllText(logFile);

            var testDictionary = new Dictionary<string, TestData>();
            var startTest = new Regex(@"\r\n\[\d\d:\d\d\] +(\d+).(\d+) +(\S+) +\((\w\w)\) ", RegexOptions.Compiled);
            var endTest = new Regex(@" \d+ failures, ([\.\d]+)/([\.\d]+) MB, (\d+) sec\.\r\n", RegexOptions.Compiled);

            for (var startMatch = startTest.Match(log); startMatch.Success; startMatch = startMatch.NextMatch())
            {
                var name = startMatch.Groups[3].Value;
                var endMatch = endTest.Match(log, startMatch.Index);
                var duration = endMatch.Groups[3].Value;

                TestData testData;
                if (!testDictionary.TryGetValue(name, out testData))
                {
                    testData = new TestData();
                    testDictionary.Add(name, testData);
                }
                testData.Iterations++;
                int durationSeconds;
                if (int.TryParse(duration, out durationSeconds))
                    testData.Duration += durationSeconds;
            }

            MainWindow.DataGridRunStats.Rows.Clear();
            foreach (var pair in testDictionary)
            {
                MainWindow.DataGridRunStats.Rows.Add(pair.Key, pair.Value.Iterations, pair.Value.Duration, pair.Value.Duration / pair.Value.Iterations);
            }
        }
コード例 #16
0
        public unsafe void TestComponentAccess()
        {
            var entity = new Entity();

            entity.AddChild(new Entity("child1")
            {
                new LightComponent()
            });

            var modelComponent = new ModelComponent();

            var compiledUpdate = UpdateEngine.Compile(typeof(Entity), new List<UpdateMemberInfo>
            {
                new UpdateMemberInfo("[ModelComponent.Key]", 0),
                new UpdateMemberInfo("child1[LightComponent.Key].Intensity", 0),
            });

            var testData = new TestData[] { 32.0f };

            fixed (TestData* dataPtr = testData)
            {
                UpdateEngine.Run(entity, compiledUpdate, (IntPtr)dataPtr, new[] { new UpdateObjectData(modelComponent) });
            }

            Assert.That(entity.Get(ModelComponent.Key), Is.EqualTo(modelComponent));
            Assert.That(entity.GetChild(0).Get(LightComponent.Key).Intensity, Is.EqualTo(32.0f));
        }
コード例 #17
0
            public static TestData Create(bool existingUser = false)
            {
                var fixture = new Fixture();
                var testData = new TestData
                {
                    Fixture = fixture,
                    UserManager = new Mock<IUserManager>(),
                    SystemRoleManager = new Mock<ISystemRoleManager>(),
                    SystemSettings = new Mock<ISystemSettings>(),
                    AdministratorUserName = fixture.Create<string>("UserName"),
                    AdministratorPassword = fixture.Create<string>("Password"),
                    AdministratorEmailAddress = fixture.Create<string>("EmailAddress"),
                    AdministratorRole = fixture.Build<SystemRole>()
                                                .With(i => i.RoleType, EnumSystemRoleType.Administrator)
                                                .Create()
                };
                if (existingUser)
                {
                    testData.ExistingUser = fixture.Build<SrirachaUser>()
                                                    .With(i => i.UserName, testData.AdministratorUserName)
                                                    .Create();
                    testData.UserManager.Setup(i => i.GetUser(testData.ExistingUser.Id)).Returns(testData.ExistingUser);
                    testData.UserManager.Setup(i => i.TryGetUserByUserName(testData.ExistingUser.UserName)).Returns(testData.ExistingUser);
                    testData.UserManager.Setup(i => i.GetUserByUserName(testData.ExistingUser.UserName)).Returns(testData.ExistingUser);
                }
                testData.SystemRoleManager.Setup(i => i.GetBuiltInRole(EnumSystemRoleType.Administrator)).Returns(testData.AdministratorRole);

                testData.Sut = new SystemSetterUpper(testData.UserManager.Object, testData.SystemRoleManager.Object, testData.SystemSettings.Object);

                return testData;
            }
コード例 #18
0
			public static TestData Create(int taskCount)
			{
				var fixture = new Fixture();
				var returnValue = new TestData
				{
					TaskFactory = new Mock<IDeployTaskFactory>(),
					StatusManager = new Mock<IDeployTaskStatusManager>(),
					Component = fixture.Create<DeployComponent>(),
					EnvironmentComponent = fixture.Create<DeployEnvironmentConfiguration>(),
					Impersonator = new Mock<IImpersonator>(),
					Build = fixture.Create<DeployBuild>(),
					RuntimeSystemSettings = fixture.Create<RuntimeSystemSettings>(),
					TaskDefinitionExecutorList = new TupleList<Mock<IDeployTaskDefinition>,Mock<IDeployTaskExecutor>,Type>(),
					DeployStateId = fixture.Create<string>()
				};
				returnValue.EnvironmentComponent.DeployCredentialsId = null;
				returnValue.Sut = new DeployComponentRunner(returnValue.TaskFactory.Object, returnValue.Impersonator.Object);

				for (int index = 0; index < taskCount; index++)
				{
					var executorType = CreateType(fixture);
					var taskDefinition = new Mock<IDeployTaskDefinition>();
					var taskExecutor = new Mock<IDeployTaskExecutor>();
					taskDefinition.Setup(i=>i.GetTaskExecutorType()).Returns(executorType);
					returnValue.TaskFactory.Setup(i=>i.CreateTaskExecutor(executorType)).Returns(taskExecutor.Object);
					returnValue.TaskDefinitionExecutorList.Add(taskDefinition, taskExecutor, executorType);
					var successResult = new DeployTaskExecutionResult
					{
						Status = EnumDeployTaskExecutionResultStatus.Success
					};
					taskExecutor.Setup(i => i.Execute(returnValue.DeployStateId, returnValue.StatusManager.Object, taskDefinition.Object, returnValue.Component, returnValue.EnvironmentComponent, It.IsAny<DeployMachine>(), It.IsAny<DeployBuild>(), returnValue.RuntimeSystemSettings)).Returns(successResult);
				}
				return returnValue;
			}
コード例 #19
0
				public static TestData Create(int projectCount=5)
				{
					var fixture = new Fixture();
					var returnValue = new TestData
					{
						Fixture = fixture,
						UserName = fixture.Create<string>("UserName"),
						ProjectList = fixture.CreateMany<DeployProject>(projectCount).ToList(),
						ProjectRoleManager = new Mock<IProjectRoleManager>(),
                        SystemRoleManager = new Mock<ISystemRoleManager>(),
						UserIdentity = new Mock<IUserIdentity>()
					};
					returnValue.DeployProjectRoleList = 
						(from i in returnValue.ProjectList
						 select new DeployProjectRole
							{
								ProjectId = i.Id,
								RoleName = fixture.Create<string>("RoleName")
							}
						).ToList();
                    returnValue.ProjectRoleManager.Setup(i => i.GetProjectRoleListForUser(It.IsAny<string>())).Returns(new List<DeployProjectRole>());
                    returnValue.ProjectRoleManager.Setup(i => i.GetProjectRoleListForUser(returnValue.UserName)).Returns(returnValue.DeployProjectRoleList);

                    returnValue.SystemRoleManager.Setup(i=>i.GetSystemRoleListForUser(It.IsAny<string>())).Returns(new List<SystemRole>());

					returnValue.UserIdentity.Setup(i=>i.UserName).Returns(returnValue.UserName);

					returnValue.Sut = new PermissionValidator(returnValue.ProjectRoleManager.Object, returnValue.SystemRoleManager.Object, returnValue.UserIdentity.Object);

					return returnValue;
				}
コード例 #20
0
        public void Should_not_register_converters_when_not_asked()
        {
            // Given
            var defaultSerializer = new JavaScriptSerializer();

            // When
            var serializer = new JavaScriptSerializer(JsonConfiguration.Default, GlobalizationConfiguration.Default);

            var data =
                new TestData()
                {
                    ConverterData =
                        new TestConverterType()
                        {
                            Data = 42,
                        },

                    PrimitiveConverterData =
                        new TestPrimitiveConverterType()
                        {
                            Data = 1701,
                        },
                };

            const string ExpectedJSON = @"{""converterData"":{""data"":42},""primitiveConverterData"":{""data"":1701}}";

            // Then
            serializer.Serialize(data).ShouldEqual(ExpectedJSON);

            serializer.Deserialize<TestData>(ExpectedJSON).ShouldEqual(data);
        }
コード例 #21
0
        public async Task StoreAsync_WithStorageFile_ThrowsException_IfFileIsNull()
        {
            StorageManager storageManager = new StorageManager();

            TestData data = new TestData() { Text = "Test Text", Number = 42 };
            await AssertEx.ThrowsExceptionAsync<ArgumentNullException>(() => storageManager.StoreAsync(null, data));
        }
コード例 #22
0
        public void TestStepFinished_Test()
        {
            var testStepRun = new TestStepRun(new TestStepData("root", "name", "fullName", "root"))
              {
                  TestLog = new StructuredDocument()
              };
            testStepRun.TestLog.Attachments.Add(new TextAttachment("name", "contentType", "text").ToAttachmentData());
            
            var report = new Report
                {
                    TestPackageRun = new TestPackageRun(),
                    TestModel = new TestModelData()
                };
            report.TestPackageRun.RootTestStepRun = testStepRun;

            testController.Stub(x => x.ReadReport(null)).IgnoreArguments().Do((Action<ReadAction<Report>>)(action => action(report)));
            testTreeModel.Stub(x => x.Root).Return(new TestTreeNode("root", "root"));

            var flag = false;
            executionLogController.ExecutionLogUpdated += (sender, e) =>
            {
                Assert.Count(1, e.TestStepRuns);
                flag = true;
            };
            var testData = new TestData("root", "name", "fullName")
            {
                IsTestCase = true
            };

            executionLogController.Handle(new TestStepFinished(testData, null));

            Assert.IsTrue(flag);
        }
コード例 #23
0
ファイル: WordCountTest.cs プロジェクト: robbor78/samplecode
		public void ValidTest1()
		{
			TestData td1 = new TestData()
			{
				words = new[] { "A" },
				frequency = 6
			};

			TestData td2 = new TestData()
			{
				words = new[] { "B" },
				frequency = 3
			};

			TestData td3 = new TestData()
			{
				words = new[] { "D" },
				frequency = 2
			};

			TestData td4 = new TestData()
			{
				words = new[] { "C" },
				frequency = 1
			};


			TestData[] testSet = new[] { td1, td2, td3, td4 };
			RunTest(testSet, 2, 2);
		}
コード例 #24
0
		public void CombinedClassAndCollectionFiltersEnabled()
		{
			TestData testData = new TestData(this);
			testData.Prepare();

			ISession session = OpenSession();
			session.EnableFilter("regionlist").SetParameterList("regions", new string[] {"LA", "APAC"});
			session.EnableFilter("fulfilledOrders").SetParameter("asOfDate", testData.lastMonth);

			// test retreival through hql with the collection as non-eager
			IList salespersons = session.CreateQuery("select s from Salesperson as s").List();
			Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count");
			Salesperson sp = (Salesperson) salespersons[0];
			Assert.AreEqual(1, sp.Orders.Count, "Incorrect order count");

			session.Clear();

			// test retreival through hql with the collection join fetched
			salespersons = session.CreateQuery("select s from Salesperson as s left join fetch s.Orders").List();
			Assert.AreEqual(1, salespersons.Count, "Incorrect salesperson count");
			sp = (Salesperson) salespersons[0];
			Assert.AreEqual(sp.Orders.Count, 1, "Incorrect order count");

			session.Close();
			testData.Release();
		}
コード例 #25
0
        public static GallioTestElement CreateFromTest(TestData test, ICodeElementInfo codeElement, IUnitTestProvider provider, 
			GallioTestElement parent)
        {
            if (test == null)
                throw new ArgumentNullException("test");

            // The idea here is to generate a test element object that does not retain any direct
            // references to the code element info and other heavyweight objects.  A test element may
            // survive in memory for quite a long time so we don't want it holding on to all sorts of
            // irrelevant stuff.  Basically we flatten out the test to just those properties that we
            // need to keep.
            var element = new GallioTestElement(provider, parent,
                test.Id,
                test.Name,
                test.Metadata.GetValue(MetadataKeys.TestKind) ?? "Unknown",
                test.IsTestCase,
                ReSharperReflectionPolicy.GetProject(codeElement),
                ReSharperReflectionPolicy.GetDeclaredElementResolver(codeElement),
                GetAssemblyPath(codeElement),
                GetTypeName(codeElement),
                GetNamespaceName(codeElement));

            var categories = test.Metadata[MetadataKeys.Category];
            if (categories.Count != 0)
                element.Categories = UnitTestElementCategory.Create(categories);

            var reason = test.Metadata.GetValue(MetadataKeys.IgnoreReason);
            if (reason != null)
                element.ExplicitReason = reason;

            return element;
        }
コード例 #26
0
ファイル: Bench.cs プロジェクト: kiidax/xlangbench
    public void Load()
    {
        // No error check for brevity.
        string[] lines = System.IO.File.ReadAllLines(@"userdata.csv");
        for (int index = 0; index < lines.Length; index++)
        {
            string[] record = lines[index].Split(',');
            string name = record[0];
            string email = record[2];
            string id = IndexToId(index);
            idUserMap[id] = new User {
                Name = name,
                Email = email
            };
        }

        var rnd = new Random();
        int numUsers = idUserMap.Count;
        for (int i = 0; i < TEST_SIZE; i++) {
            string fromId = IndexToId(rnd.Next(numUsers));
            string toId = IndexToId(rnd.Next(numUsers));
            TestData data = new TestData {
                FromId = fromId,
                ToId = toId
            };
            testDataList.AddLast(data);
        }
    }
コード例 #27
0
		public void WithClause()
		{
			var data = new TestData(this);
			data.Prepare();

			ISession s = OpenSession();
			ITransaction txn = s.BeginTransaction();

			// one-to-many
				IList list =
				s.CreateQuery("from Human h inner join h.offspring as o with o.bodyWeight < :someLimit").SetDouble("someLimit", 1).
					List();
			Assert.That(list, Is.Empty, "ad-hoc on did not take effect");

			// many-to-one
			list =
				s.CreateQuery("from Animal a inner join a.mother as m with m.bodyWeight < :someLimit").SetDouble("someLimit", 1).
					List();
			Assert.That(list, Is.Empty, "ad-hoc on did not take effect");

			// many-to-many
			list = s.CreateQuery("from Human h inner join h.friends as f with f.nickName like 'bubba'").List();
			Assert.That(list, Is.Empty, "ad-hoc on did not take effect");

			txn.Commit();
			s.Close();

			data.Cleanup();
		}
        /// <summary>
        /// Initializes the event arguments.
        /// </summary>
        /// <param name="report">The report.</param>
        /// <param name="test">The test data.</param>
        /// <param name="testStepRun">The test step run.</param>
        /// <param name="logStreamName">The log stream name.</param>
        /// <param name="sectionName">The name of the section that was started.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="report"/>, <paramref name="test"/>
        /// <paramref name="testStepRun"/>, <paramref name="logStreamName"/>, or <paramref name="sectionName"/> is null.</exception>
        public TestStepLogStreamBeginSectionBlockEventArgs(Report report, TestData test, TestStepRun testStepRun, string logStreamName, string sectionName)
            : base(report, test, testStepRun, logStreamName)
        {
            if (sectionName == null)
                throw new ArgumentNullException("sectionName");

            this.sectionName = sectionName;
        }
コード例 #29
0
        /// <summary>
        /// Initializes the event arguments.
        /// </summary>
        /// <param name="report">The report.</param>
        /// <param name="test">The test data.</param>
        /// <param name="testStepRun">The test step run.</param>
        /// <param name="attachment">The attachment.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="report"/>, <paramref name="test"/>
        /// <paramref name="testStepRun"/> or <paramref name="attachment"/> is null.</exception>
        public TestStepLogAttachEventArgs(Report report, TestData test, TestStepRun testStepRun, Attachment attachment)
            : base(report, test, testStepRun)
        {
            if (attachment == null)
                throw new ArgumentNullException("attachment");

            this.attachment = attachment;
        }
コード例 #30
0
        /// <summary>
        /// Initializes the event arguments.
        /// </summary>
        /// <param name="report">The report.</param>
        /// <param name="test">The test data.</param>
        /// <param name="testStepRun">The test step run.</param>
        /// <param name="logStreamName">The log stream name.</param>
        /// <param name="attachmentName">The name of the attachment that was embedded.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="report"/>, <paramref name="test"/>
        /// <paramref name="testStepRun"/>, <paramref name="logStreamName"/>, or <paramref name="attachmentName"/> is null.</exception>
        public TestStepLogStreamEmbedEventArgs(Report report, TestData test, TestStepRun testStepRun, string logStreamName, string attachmentName)
            : base(report, test, testStepRun, logStreamName)
        {
            if (attachmentName == null)
                throw new ArgumentNullException("attachmentName");

            this.attachmentName = attachmentName;
        }
コード例 #31
0
        TestClass()
        {
            TestData [] aoTestData = new TestData [] {
                // Twitter REST API format, JSON, as of April 2012:

                new TestData("Sat Jan 12 19:12:20 +0000 2008", true,
                             new DateTime(2008, 1, 12, 19, 12, 20, DateTimeKind.Utc),
                             "2008-01-12 19:12:20"),

                new TestData("Fri May 15 15:12:24 +0000 2009", true,
                             new DateTime(2009, 5, 15, 15, 12, 24, DateTimeKind.Utc),
                             "2009-05-15 15:12:24"),

                new TestData("Fri Feb 12 14:58:06 +0000 2010", true,
                             new DateTime(2010, 2, 12, 14, 58, 6, DateTimeKind.Utc),
                             "2010-02-12 14:58:06"),

                new TestData("Xri Feb 12 14:58:06 +0000 2010", false,
                             DateTime.Now,
                             "Xri Feb 12 14:58:06 +0000 2010"),


                // Twitter search API format, JSON, as of April 2012:

                new TestData("Thu, 06 Oct 2011 19:36:17 +0000", true,
                             new DateTime(2011, 10, 6, 19, 36, 17, DateTimeKind.Utc),
                             "2011-10-06 19:36:17"),

                new TestData("Wed, 19 Jan 2011 02:35:29 +0000", true,
                             new DateTime(2011, 1, 19, 2, 35, 29, DateTimeKind.Utc),
                             "2011-01-19 02:35:29"),

                new TestData("Xed, 19 Jan 2011 02:35:29 +0000", false,
                             new DateTime(2011, 1, 19, 2, 35, 29, DateTimeKind.Utc),
                             "Xed, 19 Jan 2011 02:35:29 +0000"),


                // Twitter search API format, ATOM, as of April 2012:

                new TestData("2010-07-19T19:09:32Z", true,
                             new DateTime(2010, 7, 19, 19, 9, 32, DateTimeKind.Utc),
                             "2010-07-19 19:09:32"),

                new TestData("2010-07-14T21:33:32Z", true,
                             new DateTime(2010, 7, 14, 21, 33, 32, DateTimeKind.Utc),
                             "2010-07-14 21:33:32"),

                new TestData("2009-01-09T00:01:02Z", true,
                             new DateTime(2009, 1, 9, 0, 1, 2, DateTimeKind.Utc),
                             "2009-01-09 00:01:02"),

                new TestData("X009-01-09T00:01:02Z", false,
                             DateTime.Now,
                             "X009-01-09T00:01:02Z"),
            };

            foreach (TestData oTestData in aoTestData)
            {
                DateTime oParsedTwitterDate;

                Boolean bParseable = TwitterDateParser.TryParseTwitterDate(
                    oTestData.TwitterDate, out oParsedTwitterDate);

                Assert.AreEqual(oTestData.Parseable, bParseable);

                if (bParseable)
                {
                    Assert.AreEqual(oTestData.ParsedTwitterDate,
                                    oParsedTwitterDate);
                }

                String sParsedTwitterDateAsString =
                    TwitterDateParser.ParseTwitterDate(oTestData.TwitterDate);

                Assert.AreEqual(oTestData.ParsedTwitterDateAsString,
                                sParsedTwitterDateAsString);
            }
        }
コード例 #32
0
 public MainWindowViewModel()
 {
     _doubleValue = 0.5;
     TestDataList = TestData.GetTestData().ToList();
 }
コード例 #33
0
ファイル: SchemaFieldTests.cs プロジェクト: zxbe/squidex
 public void Should_freeze_field_properties(FieldProperties action)
 {
     TestData.TestFreeze(action);
 }
コード例 #34
0
ファイル: WebProjectTests.cs プロジェクト: zyxws012/PTVS
        public void WebProjectStaticUri(PythonVisualStudioApp app)
        {
            var project = app.CreateProject(
                PythonVisualStudioApp.TemplateLanguageName,
                PythonVisualStudioApp.EmptyWebProjectTemplate,
                TestData.GetTempPath(),
                "WebProjectStaticUri"
                );

            var proj = project.GetCommonProject();

            Assert.IsNotNull(proj);

            app.ServiceProvider.GetUIThread().Invoke(() => {
                proj.SetProjectProperty("PythonWsgiHandler", "NoHandler");

                proj.SetProjectProperty("StaticUriPattern", "");
                proj.SetProjectProperty("StaticUriRewrite", "");
            });
            app.ExecuteCommand("Build.RebuildSolution");
            app.WaitForOutputWindowText("Build", "1 succeeded");

            var webConfig = File.ReadAllText(Path.Combine(Path.GetDirectoryName(project.FullName), "web.config"));

            if (!webConfig.Contains(@"<add input=""true"" pattern=""false"" />"))
            {
                Assert.Fail(string.Format("Did not find Static Files condition in:{0}{0}{1}",
                                          Environment.NewLine,
                                          webConfig
                                          ));
            }

            app.ServiceProvider.GetUIThread().Invoke(() => {
                proj.SetProjectProperty("StaticUriPattern", "^static/.*$");
            });
            app.ExecuteCommand("Build.RebuildSolution");
            app.WaitForOutputWindowText("Build", "1 succeeded");

            webConfig = File.ReadAllText(Path.Combine(Path.GetDirectoryName(project.FullName), "web.config"));
            if (!webConfig.Contains(@"<add input=""{REQUEST_URI}"" pattern=""^static/.*$"" ignoreCase=""true"" negate=""true"" />"))
            {
                Assert.Fail(string.Format("Did not find rewrite condition in:{0}{0}{1}",
                                          Environment.NewLine,
                                          webConfig
                                          ));
            }
            if (!webConfig.Contains(@"<add input=""true"" pattern=""false"" />"))
            {
                Assert.Fail(string.Format("Did not find Static Files condition in:{0}{0}{1}",
                                          Environment.NewLine,
                                          webConfig
                                          ));
            }

            app.ServiceProvider.GetUIThread().Invoke(() => {
                proj.SetProjectProperty("StaticUriRewrite", "static_files/{R:1}");
            });
            app.ExecuteCommand("Build.RebuildSolution");
            app.WaitForOutputWindowText("Build", "1 succeeded");

            webConfig = File.ReadAllText(Path.Combine(Path.GetDirectoryName(project.FullName), "web.config"));
            if (webConfig.Contains(@"<add input=""{REQUEST_URI}"" pattern=""^static/.*$"" ignoreCase=""true"" negate=""true"" />"))
            {
                Assert.Fail(string.Format("Found old rewrite condition in:{0}{0}{1}",
                                          Environment.NewLine,
                                          webConfig
                                          ));
            }
            if (!webConfig.Contains(@"<action type=""Rewrite"" url=""static_files/{R:1}"" appendQueryString=""true"" />"))
            {
                Assert.Fail(string.Format("Did not find rewrite action in:{0}{0}{1}",
                                          Environment.NewLine,
                                          webConfig
                                          ));
            }
            if (webConfig.Contains(@"<add input=""true"" pattern=""false"" />"))
            {
                Assert.Fail(string.Format("Should not have found Static Files condition in:{0}{0}{1}",
                                          Environment.NewLine,
                                          webConfig
                                          ));
            }

            app.ServiceProvider.GetUIThread().Invoke(() => {
                proj.SetProjectProperty("StaticUriPattern", "invalid[pattern");
            });
            app.ExecuteCommand("Build.RebuildSolution");
            app.WaitForOutputWindowText("Build", "1 failed");
        }
コード例 #35
0
ファイル: WebProjectTests.cs プロジェクト: zyxws012/PTVS
        private static void CloudProjectTest(PythonVisualStudioApp app, string roleType, bool openServiceDefinition)
        {
            Assert.IsTrue(roleType == "Web" || roleType == "Worker", "Invalid roleType: " + roleType);

            Assembly asm = null;

            try {
                asm = Assembly.Load("Microsoft.VisualStudio.CloudService.Wizard,Version=1.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a");
            } catch {
                // Failed to load - we'll skip the test below
            }

            if (asm != null && asm.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false)
                .OfType <AssemblyFileVersionAttribute>()
                .Any(a => {
                Version ver;
                return(Version.TryParse(a.Version, out ver) && ver < new Version(2, 5));
            })
                )
            {
                Assert.Inconclusive("Test requires Microsoft Azure Tools 2.5 or later");
            }

            using (FileUtils.Backup(TestData.GetPath(@"TestData\CloudProject\ServiceDefinition.csdef"))) {
                app.OpenProject("TestData\\CloudProject.sln", expectedProjects: 3);

                var ccproj = app.Dte.Solution.Projects.Cast <Project>().FirstOrDefault(p => p.Name == "CloudProject");
                Assert.IsNotNull(ccproj);

                if (openServiceDefinition)
                {
                    var wnd = ccproj.ProjectItems.Item("ServiceDefinition.csdef").Open();
                    wnd.Activate();
                    app.OnDispose(() => wnd.Close());
                }

                IVsHierarchy hier;
                var          sln = app.GetService <IVsSolution>(typeof(SVsSolution));
                ErrorHandler.ThrowOnFailure(sln.GetProjectOfUniqueName(ccproj.FullName, out hier));

                var pyproj = app.Dte.Solution.Projects.Cast <Project>().FirstOrDefault(p => p.Name == roleType + "Role1");
                Assert.IsNotNull(pyproj);
                app.ServiceProvider.GetUIThread().InvokeAsync(() => {
                    Assert.IsNotNull(pyproj.GetPythonProject());
                    ((IAzureRoleProject)pyproj.GetPythonProject()).AddedAsRole(hier, roleType);
                }).GetAwaiter().GetResult();

                // AddedAsRole runs in the background, so wait a second for it to
                // do its thing.
                Thread.Sleep(1000);

                var doc = new XmlDocument();
                for (int retries = 5; retries > 0; --retries)
                {
                    try {
                        doc.Load(TestData.GetPath(@"TestData\CloudProject\ServiceDefinition.csdef"));
                        break;
                    } catch (IOException ex) {
                        Console.WriteLine("Exception while reading ServiceDefinition.csdef.{0}{1}", Environment.NewLine, ex);
                    } catch (XmlException) {
                        var copyTo = TestData.GetPath(@"TestData\CloudProject\" + Path.GetRandomFileName());
                        File.Copy(TestData.GetPath(@"TestData\CloudProject\ServiceDefinition.csdef"), copyTo);
                        Console.WriteLine("Copied file to " + copyTo);
                        throw;
                    }
                    Thread.Sleep(100);
                }
                var ns = new XmlNamespaceManager(doc.NameTable);
                ns.AddNamespace("sd", "http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition");
                doc.Save(Console.Out);

                var nav = doc.CreateNavigator();
                if (roleType == "Web")
                {
                    Assert.IsNotNull(nav.SelectSingleNode(
                                         "/sd:ServiceDefinition/sd:WebRole[@name='WebRole1']/sd:Startup/sd:Task[@commandLine='ps.cmd ConfigureCloudService.ps1']",
                                         ns
                                         ));
                }
                else if (roleType == "Worker")
                {
                    Assert.IsNotNull(nav.SelectSingleNode(
                                         "/sd:ServiceDefinition/sd:WorkerRole[@name='WorkerRole1']/sd:Startup/sd:Task[@commandLine='bin\\ps.cmd ConfigureCloudService.ps1']",
                                         ns
                                         ));
                    Assert.IsNotNull(nav.SelectSingleNode(
                                         "/sd:ServiceDefinition/sd:WorkerRole[@name='WorkerRole1']/sd:Runtime/sd:EntryPoint/sd:ProgramEntryPoint[@commandLine='bin\\ps.cmd LaunchWorker.ps1 worker.py']",
                                         ns
                                         ));
                }
            }
        }
コード例 #36
0
 public FooComplexResponse(string val)
 {
     FooComplexResult = new TestData(val);
 }
コード例 #37
0
 public void SetOneDay(string sourceName, TestData oneDay)
 {
     TestObject.Find(sourceName).ASetOneDay(oneDay);
 }
コード例 #38
0
ファイル: TestDataService.cs プロジェクト: Gnail-nehc/Black
 public bool UpdateTestData(TestData testData, out string log)
 {
     Guard.ArgumentNotNull(testData, "testDataObject");
     testData.ProjectId = (this.CurrentProjectId > 0) ? this.CurrentProjectId : 1;
     return(this.TestDataRepository.UpdateTestData(testData, out log));
 }
コード例 #39
0
        private void TestOpen(PythonVersion path)
        {
            path.AssertInstalled();
            Console.WriteLine(path.InterpreterPath);

            Guid testId  = Guid.NewGuid();
            var  testDir = TestData.GetTempPath(testId.ToString());

            var scraper = Path.Combine(Path.GetDirectoryName(GetType().Assembly.Location), "PythonScraper.py");

            Assert.IsTrue(File.Exists(scraper), $"Did not find {scraper}");

            // run the scraper
            using (var proc = ProcessOutput.RunHiddenAndCapture(
                       path.InterpreterPath,
                       scraper,
                       testDir,
                       CompletionDB
                       )) {
                Console.WriteLine("Command: " + proc.Arguments);

                proc.Wait();

                // it should succeed
                Console.WriteLine("**Stdout**");
                foreach (var line in proc.StandardOutputLines)
                {
                    Console.WriteLine(line);
                }
                Console.WriteLine("");
                Console.WriteLine("**Stdout**");
                foreach (var line in proc.StandardErrorLines)
                {
                    Console.WriteLine(line);
                }

                Assert.AreEqual(0, proc.ExitCode, "Bad exit code: " + proc.ExitCode);
            }

            // perform some basic validation
            dynamic builtinDb = Unpickle.Load(new FileStream(Path.Combine(testDir, path.Version.Is3x() ? "builtins.idb" : "__builtin__.idb"), FileMode.Open, FileAccess.Read));

            if (path.Version.Is2x())   // no open in 3.x
            {
                foreach (var overload in builtinDb["members"]["open"]["value"]["overloads"])
                {
                    Assert.AreEqual("__builtin__", overload["ret_type"][0][0]);
                    Assert.AreEqual("file", overload["ret_type"][0][1]);
                }

                if (!path.InterpreterPath.Contains("Iron"))
                {
                    // http://pytools.codeplex.com/workitem/799
                    var arr = (IList <object>)builtinDb["members"]["list"]["value"]["members"]["__init__"]["value"]["overloads"];
                    Assert.AreEqual(
                        "args",
                        ((dynamic)(arr[0]))["args"][1]["name"]
                        );
                }
            }

            if (!path.InterpreterPath.Contains("Iron"))
            {
                dynamic itertoolsDb = Unpickle.Load(new FileStream(Path.Combine(testDir, "itertools.idb"), FileMode.Open, FileAccess.Read));
                var     tee         = itertoolsDb["members"]["tee"]["value"];
                var     overloads   = tee["overloads"];
                var     nArg        = overloads[0]["args"][1];
                Assert.AreEqual("n", nArg["name"]);
                Assert.AreEqual("2", nArg["default_value"]);

                dynamic sreDb   = Unpickle.Load(new FileStream(Path.Combine(testDir, "_sre.idb"), FileMode.Open, FileAccess.Read));
                var     members = sreDb["members"];
                Assert.IsTrue(members.ContainsKey("SRE_Pattern"));
                Assert.IsTrue(members.ContainsKey("SRE_Match"));
            }

            Console.WriteLine("Passed: {0}", path.InterpreterPath);
        }
コード例 #40
0
        public async Task DoesNotWriteToNuGetScratch()
        {
            // Arrange
            OptimizedZipPackage.PurgeCache();
            var expectedTempEntries = Directory
                                      .GetFileSystemEntries(Path.Combine(Path.GetTempPath(), "NuGetScratch"))
                                      .OrderBy(x => x)
                                      .ToList();

            using (var tc = new TestContext())
            {
                tc.Settings["enableFrameworkFiltering"]           = "true";
                tc.Settings["allowOverrideExistingPackageOnPush"] = "true";

                string apiKey = "foobar";
                tc.SetApiKey(apiKey);

                // Act & Assert
                // 1. Write a package to the drop folder.
                var packagePath = Path.Combine(tc.PackagesDirectory, "package.nupkg");
                TestData.CopyResourceToPath(TestData.PackageResource, packagePath);

                // 2. Search for packages.
                using (var request = new HttpRequestMessage(
                           HttpMethod.Get,
                           $"/nuget/Search?targetFramework='net46'"))
                    using (var response = await tc.Client.SendAsync(request))
                    {
                        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                    }

                // 3. Push the package.
                var pushPath = Path.Combine(tc.TemporaryDirectory, "package.nupkg");
                TestData.CopyResourceToPath(TestData.PackageResource, pushPath);
                using (var request = new HttpRequestMessage(HttpMethod.Put, "/nuget")
                {
                    Headers =
                    {
                        { "X-NUGET-APIKEY", apiKey }
                    },
                    Content = tc.GetFileUploadContent(pushPath),
                })
                {
                    using (request)
                        using (var response = await tc.Client.SendAsync(request))
                        {
                            Assert.Equal(HttpStatusCode.Created, response.StatusCode);
                        }
                }

                // 4. Search for packages again.
                using (var request = new HttpRequestMessage(
                           HttpMethod.Get,
                           $"/nuget/Search?targetFramework='net46'"))
                    using (var response = await tc.Client.SendAsync(request))
                    {
                        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                    }

                // 6. Make sure we have not added more temp files.
                var actualTempEntries = Directory
                                        .GetFileSystemEntries(Path.Combine(Path.GetTempPath(), "NuGetScratch"))
                                        .OrderBy(x => x)
                                        .ToList();
                Assert.Equal(expectedTempEntries, actualTempEntries);
            }
        }
        public async Task UpdateDefaultChannel()
        {
            using TestData data = await BuildDefaultAsync();

            string channelName    = "TEST-CHANNEL-TO-UPDATE";
            string classification = "TEST-CLASSIFICATION";
            string repository     = "FAKE-REPOSITORY";
            string branch         = "FAKE-BRANCH";

            Channel channel1, channel2;
            {
                var result = await data.ChannelsController.CreateChannel($"{channelName}-1", classification);

                channel1 = (Channel)((ObjectResult)result).Value;
                result   = await data.ChannelsController.CreateChannel($"{channelName}-2", classification);

                channel2 = (Channel)((ObjectResult)result).Value;
            }

            DefaultChannel defaultChannel;
            {
                DefaultChannelCreateData testDefaultChannelData = new DefaultChannelCreateData()
                {
                    Branch     = branch,
                    ChannelId  = channel1.Id,
                    Enabled    = true,
                    Repository = repository
                };
                var result = await data.DefaultChannelsController.Create(testDefaultChannelData);

                defaultChannel = (DefaultChannel)((ObjectResult)result).Value;
            }

            DefaultChannel updatedDefaultChannel;
            {
                DefaultChannelUpdateData defaultChannelUpdateData = new DefaultChannelUpdateData()
                {
                    Branch     = $"{branch}-UPDATED",
                    ChannelId  = channel2.Id,
                    Enabled    = false,
                    Repository = $"NEW-{repository}"
                };
                var result = await data.DefaultChannelsController.Update(defaultChannel.Id, defaultChannelUpdateData);

                updatedDefaultChannel = (DefaultChannel)((ObjectResult)result).Value;
            }

            List <DefaultChannel> defaultChannels;

            {
                IActionResult result = data.DefaultChannelsController.List($"NEW-{repository}", $"{branch}-UPDATED", channel2.Id, false);
                result.Should().BeAssignableTo <ObjectResult>();
                var objResult = (ObjectResult)result;
                objResult.StatusCode.Should().Be((int)HttpStatusCode.OK);
                objResult.Value.Should().BeAssignableTo <IEnumerable <DefaultChannel> >();
                defaultChannels = ((IEnumerable <DefaultChannel>)objResult.Value).ToList();
            }

            defaultChannels.Should().ContainSingle();
            defaultChannels.Single().Channel.Id.Should().Be(channel2.Id, "Only fake channel #2's id should show up as a default channel");
        }
コード例 #42
0
 public LoaderTest()
 {
     _testData = new TestData();
     _loader   = new Mod.Loader.Loader(true);
     _loader.LoadForCurrentProcess();
 }
コード例 #43
0
 public static void Deploy(bool includeTestData = true)
 {
     TestData.Deploy(DataSourcePath, includeTestData);
 }
コード例 #44
0
        private async Task CompiledBuiltinScrapeAsync(InterpreterConfiguration configuration)
        {
            configuration.AssertInstalled();

            var moduleUri       = TestData.GetDefaultModuleUri();
            var moduleDirectory = Path.GetDirectoryName(moduleUri.LocalPath);

            var services = await CreateServicesAsync(moduleDirectory, configuration);

            var interpreter = services.GetService <IPythonInterpreter>();

            // TODO: this is Windows only
            var dllsDir = Path.Combine(Path.GetDirectoryName(interpreter.Configuration.LibraryPath), "DLLs");

            if (!Directory.Exists(dllsDir))
            {
                Assert.Inconclusive("Configuration does not have DLLs");
            }

            var report           = new List <string>();
            var permittedImports = interpreter.LanguageVersion.Is2x() ?
                                   new[] { interpreter.ModuleResolution.BuiltinModuleName, "exceptions" } :
            new[] { interpreter.ModuleResolution.BuiltinModuleName };

            foreach (var pyd in PathUtils.EnumerateFiles(dllsDir, "*", recurse: false).Where(ModulePath.IsPythonFile))
            {
                var mp = ModulePath.FromFullPath(pyd);
                if (mp.IsDebug)
                {
                    continue;
                }

                Console.WriteLine("Importing {0} from {1}", mp.ModuleName, mp.SourceFile);
                var mod = await interpreter.ModuleResolution.ImportModuleAsync(mp.ModuleName);

                Assert.IsInstanceOfType(mod, typeof(CompiledPythonModule));

                var modPath = interpreter.ModuleResolution.ModuleCache.GetCacheFilePath(pyd);
                Assert.IsTrue(File.Exists(modPath), "No cache file created");
                var moduleCache = File.ReadAllText(modPath);

                var doc = (IDocument)mod;
                var ast = await doc.GetAstAsync();

                var errors = doc.GetParseErrors().ToArray();
                foreach (var err in errors)
                {
                    Console.WriteLine(err);
                }
                Assert.AreEqual(0, errors.Count(), "Parse errors occurred");


                var imports = ((SuiteStatement)ast.Body).Statements
                              .OfType <ImportStatement>()
                              .SelectMany(s => s.Names)
                              .Select(n => n.MakeString())
                              .Except(permittedImports)
                              .ToArray();

                // We expect no imports (after excluding builtins)
                report.AddRange(imports.Select(n => $"{mp.ModuleName} imported {n}"));
            }

            report.Should().BeEmpty();
        }
コード例 #45
0
        public void TestImpressionEventEqualsSerializedPayload()
        {
            var guid      = Guid.NewGuid();
            var timeStamp = TestData.SecondsSince1970();
            var userId    = "TestUserId";

            var expectedPayload = new Dictionary <string, object>
            {
                { "visitors", new object[]
                  {
                      new Dictionary <string, object>()
                      {
                          { "snapshots", new object[]
                            {
                                new Dictionary <string, object>
                                {
                                    { "decisions", new object[]
                                        {
                                            new Dictionary <string, object>
                                            {
                                                { "campaign_id", "7719770039" },
                                                { "experiment_id", "7716830082" },
                                                { "variation_id", "77210100090" }
                                            }
                                        } },
                                    { "events", new object[]
                                        {
                                            new Dictionary <string, object>
                                            {
                                                { "entity_id", "7719770039" },
                                                { "timestamp", timeStamp },
                                                { "uuid", guid },
                                                { "key", "campaign_activated" }
                                            }
                                        } }
                                }
                            } },
                          { "attributes", new object[]
                            {
                                new Dictionary <string, object>
                                {
                                    { "entity_id", "7723280020" },
                                    { "key", "device_type" },
                                    { "type", "custom" },
                                    { "value", "iPhone" }
                                },
                                new Dictionary <string, object>
                                {
                                    { "entity_id", ControlAttributes.BOT_FILTERING_ATTRIBUTE },
                                    { "key", ControlAttributes.BOT_FILTERING_ATTRIBUTE },
                                    { "type", "custom" },
                                    { "value", true }
                                }
                            } },
                          { "visitor_id", userId }
                      }
                  } },
                { "project_id", "7720880029" },
                { "account_id", "1592310167" },
                { "enrich_decisions", true },
                { "client_name", "csharp-sdk" },
                { "client_version", Optimizely.SDK_VERSION },
                { "revision", "15" },
                { "anonymize_ip", false }
            };

            EventBatch.Builder builder = new EventBatch.Builder();
            builder.WithAccountId("1592310167")
            .WithProjectID("7720880029")
            .WithClientVersion(Optimizely.SDK_VERSION)
            .WithRevision("15")
            .WithClientName("csharp-sdk")
            .WithAnonymizeIP(false)
            .WithEnrichDecisions(true);

            var visitorAttribute1 = new VisitorAttribute(entityId: "7723280020", type: "custom", value: "iPhone", key: "device_type");
            var visitorAttribute2 = new VisitorAttribute(entityId: ControlAttributes.BOT_FILTERING_ATTRIBUTE, type: "custom", value: true, key: ControlAttributes.BOT_FILTERING_ATTRIBUTE);
            var snapshotEvent     = new SnapshotEvent.Builder()
                                    .WithUUID(guid.ToString())
                                    .WithEntityId("7719770039")
                                    .WithKey("campaign_activated")
                                    .WithValue(null)
                                    .WithRevenue(null)
                                    .WithTimeStamp(timeStamp)
                                    .WithEventTags(null)
                                    .Build();

            var decision = new Decision("7719770039", "7716830082", "77210100090");
            var snapshot = new Snapshot(events: new SnapshotEvent[] { snapshotEvent }, decisions: new Decision[] { decision });

            var visitor = new Visitor(
                snapshots: new Snapshot[] {
                snapshot
            },
                attributes: new VisitorAttribute[] {
                visitorAttribute1, visitorAttribute2
            },
                visitorId: "test_user");

            builder.WithVisitors(new Visitor[] { visitor });

            EventBatch eventBatch = builder.Build();

            // Single Conversion Event
            TestData.CompareObjects(expectedPayload, eventBatch);
        }
コード例 #46
0
 public TestMessage(string a, string b)
 {
     data = new TestData(a); msg = new TestData(b);
 }
コード例 #47
0
        public void PydInPackage()
        {
            PythonPaths.Python27.AssertInstalled();

            var outputPath = TestData.GetTempPath();

            Console.WriteLine("Writing to: " + outputPath);

            // run the analyzer
            using (var output = ProcessOutput.RunHiddenAndCapture("Microsoft.PythonTools.Analyzer.exe",
                                                                  "/python", PythonPaths.Python27.InterpreterPath,
                                                                  "/lib", TestData.GetPath(@"TestData\PydStdLib"),
                                                                  "/version", "2.7",
                                                                  "/outdir", outputPath,
                                                                  "/indir", CompletionDB,
                                                                  "/unittest",
                                                                  "/log", "AnalysisLog.txt")) {
                output.Wait();
                Console.WriteLine("* Stdout *");
                foreach (var line in output.StandardOutputLines)
                {
                    Console.WriteLine(line);
                }
                Console.WriteLine("* Stderr *");
                foreach (var line in output.StandardErrorLines)
                {
                    Console.WriteLine(line);
                }
                Assert.AreEqual(0, output.ExitCode);
            }

            var fact  = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(new Version(2, 7));
            var paths = new List <string> {
                outputPath
            };

            paths.AddRange(Directory.EnumerateDirectories(outputPath));
            var typeDb = new PythonTypeDatabase(fact, paths);
            var module = typeDb.GetModule("Package.winsound");

            Assert.IsNotNull(module, "Package.winsound was not analyzed");
            var package = typeDb.GetModule("Package");

            Assert.IsNotNull(package, "Could not import Package");
            var member = package.GetMember(null, "winsound");

            Assert.IsNotNull(member, "Could not get member Package.winsound");
            Assert.AreSame(module, member);

            module = typeDb.GetModule("Package._testcapi");
            Assert.IsNotNull(module, "Package._testcapi was not analyzed");
            package = typeDb.GetModule("Package");
            Assert.IsNotNull(package, "Could not import Package");
            member = package.GetMember(null, "_testcapi");
            Assert.IsNotNull(member, "Could not get member Package._testcapi");
            Assert.IsNotInstanceOfType(member, typeof(CPythonMultipleMembers));
            Assert.AreSame(module, member);

            module = typeDb.GetModule("Package.select");
            Assert.IsNotNull(module, "Package.select was not analyzed");
            package = typeDb.GetModule("Package");
            Assert.IsNotNull(package, "Could not import Package");
            member = package.GetMember(null, "select");
            Assert.IsNotNull(member, "Could not get member Package.select");
            Assert.IsInstanceOfType(member, typeof(CPythonMultipleMembers));
            var mm = (CPythonMultipleMembers)member;

            AssertUtil.ContainsExactly(mm.Members.Select(m => m.MemberType),
                                       PythonMemberType.Module,
                                       PythonMemberType.Constant,
                                       PythonMemberType.Class
                                       );
            Assert.IsNotNull(mm.Members.Contains(module));

            try {
                // Only clean up if the test passed
                Directory.Delete(outputPath, true);
            } catch { }
        }
コード例 #48
0
 private void AddAsTestData(DataEntry entry)
 {
     TestData.Add(entry);
 }
コード例 #49
0
ファイル: SanityChecker.cs プロジェクト: CodingWoes/CKAN
 public void Setup()
 {
     registry = CKAN.Registry.Empty();
     CKAN.Repo.UpdateRegistry(TestData.TestKAN(), registry);
 }
コード例 #50
0
 public TestResult(string a, string b)
 {
     resData = new TestData(a); resMsg = new TestData(b);
 }
コード例 #51
0
        public List <LeadUserDetail> getLeadsPlanMonth(int month)
        {
            var listLeadCategory = TestData.GetLeadCategoryForNextMonth().Where(n => n.planmonthdate != null && n.planmonthdate.Value.Month == month && n.IsConfirm != true).ToList();

            return(listLeadCategory);
        }
コード例 #52
0
        public async Task Get_RendersRowsCorrectly()
        {
            // Arrange

            var standard = await TestData.CreateStandard(standardCode : 1234, version : 1, standardName : "Test Standard");

            var provider1 = await TestData.CreateProvider(
                providerName : "Provider 1",
                apprenticeshipQAStatus : ApprenticeshipQAStatus.Submitted);

            var provider1User = await TestData.CreateUser(providerId : provider1.ProviderId);

            await TestData.CreateUserSignIn(provider1User.UserId, new DateTime(2018, 4, 1, 10, 4, 3));

            var provider1ApprenticeshipId = (await TestData.CreateApprenticeship(provider1.ProviderId, standard, createdBy: User.ToUserInfo())).ApprenticeshipId;
            await TestData.CreateApprenticeshipQASubmission(
                provider1.ProviderId,
                submittedOn : new DateTime(2018, 4, 1, 12, 30, 37),
                submittedByUserId : provider1User.UserId,
                providerMarketingInformation : "Provider 1 overview",
                apprenticeshipIds : new[] { provider1ApprenticeshipId });

            var provider2 = await TestData.CreateProvider(
                providerName : "Provider 2",
                apprenticeshipQAStatus : ApprenticeshipQAStatus.Submitted);

            var provider2User = await TestData.CreateUser(providerId : provider2.ProviderId);

            await TestData.CreateUserSignIn(provider2User.UserId, new DateTime(2019, 5, 3, 14, 55, 17));

            var provider2ApprenticeshipId = (await TestData.CreateApprenticeship(provider2.ProviderId, standard, createdBy: User.ToUserInfo())).ApprenticeshipId;
            await TestData.CreateApprenticeshipQASubmission(
                provider2.ProviderId,
                submittedOn : new DateTime(2019, 5, 3, 15, 01, 23),
                submittedByUserId : provider2User.UserId,
                providerMarketingInformation : "Provider 2 overview",
                apprenticeshipIds : new[] { provider2ApprenticeshipId });

            var provider3 = await TestData.CreateProvider(
                providerName : "Provider 3",
                apprenticeshipQAStatus : ApprenticeshipQAStatus.NotStarted);

            var provider3User = await TestData.CreateUser(providerId : provider3.ProviderId);

            await TestData.CreateUserSignIn(provider3User.UserId, new DateTime(2019, 2, 6, 7, 22, 9));

            // TODO Add more here once we have a way of modelling other statuses

            // Act
            var response = await HttpClient.GetAsync("apprenticeship-qa");

            // Assert
            response.EnsureSuccessStatusCode();

            var doc = await response.GetDocument();

            var newProviders    = doc.QuerySelector("#notstarted");
            var newProviderRows = newProviders.QuerySelectorAll("tbody>tr");

            var firstNewProviderRow = newProviderRows[0];

            Assert.Equal("Provider 3", firstNewProviderRow.QuerySelector(":nth-child(1)").TextContent);
            Assert.Equal(provider3.Ukprn.ToString(), firstNewProviderRow.QuerySelector(":nth-child(2)").TextContent);
            Assert.Equal("06 Feb 2019", firstNewProviderRow.QuerySelector(":nth-child(3)").TextContent);

            var submitted     = doc.QuerySelector("#submitted");
            var submittedRows = submitted.QuerySelectorAll("tbody>tr");

            var firstSubmittedRow = submittedRows[0];

            Assert.Equal("Provider 2", firstSubmittedRow.QuerySelector(":nth-child(1)").TextContent);
            Assert.Equal(provider2.Ukprn.ToString(), firstSubmittedRow.QuerySelector(":nth-child(2)").TextContent);
            Assert.Equal("03 May 2019", firstSubmittedRow.QuerySelector(":nth-child(3)").TextContent);

            var secondSubmittedRow = submittedRows[1];

            Assert.Equal("Provider 1", secondSubmittedRow.QuerySelector(":nth-child(1)").TextContent);
            Assert.Equal(provider1.Ukprn.ToString(), secondSubmittedRow.QuerySelector(":nth-child(2)").TextContent);
            Assert.Equal("01 Apr 2018", secondSubmittedRow.QuerySelector(":nth-child(3)").TextContent);
        }
        public async Task DefaultChannelRegularExpressionMatching()
        {
            using TestData data = await BuildDefaultAsync();

            string channelName    = "TEST-CHANNEL-REGEX-FOR-DEFAULT";
            string classification = "TEST-CLASSIFICATION";
            string repository     = "FAKE-REPOSITORY";
            string branch         = "-regex:FAKE-BRANCH-REGEX-.*";

            Channel channel;
            {
                var result = await data.ChannelsController.CreateChannel($"{channelName}", classification);

                channel = (Channel)((ObjectResult)result).Value;
            }

            DefaultChannel defaultChannel;

            {
                DefaultChannelCreateData testDefaultChannelData = new DefaultChannelCreateData()
                {
                    Branch     = branch,
                    ChannelId  = channel.Id,
                    Enabled    = true,
                    Repository = repository
                };
                var result = await data.DefaultChannelsController.Create(testDefaultChannelData);

                defaultChannel = (DefaultChannel)((ObjectResult)result).Value;
            }

            string[] branchesThatMatch     = new string[] { "FAKE-BRANCH-REGEX-", "FAKE-BRANCH-REGEX-RELEASE-BRANCH-1", "FAKE-BRANCH-REGEX-RELEASE-BRANCH-2" };
            string[] branchesThatDontMatch = new string[] { "I-DONT-MATCH", "REAL-BRANCH-REGEX" };

            foreach (string branchName in branchesThatMatch)
            {
                List <DefaultChannel> defaultChannels;
                {
                    IActionResult result = data.DefaultChannelsController.List(repository, branchName, channel.Id);
                    result.Should().BeAssignableTo <ObjectResult>();
                    var objResult = (ObjectResult)result;
                    objResult.StatusCode.Should().Be((int)HttpStatusCode.OK);
                    objResult.Value.Should().BeAssignableTo <IEnumerable <DefaultChannel> >();
                    defaultChannels = ((IEnumerable <DefaultChannel>)objResult.Value).ToList();
                }
                defaultChannels.Should().ContainSingle();
                defaultChannels.Single().Channel.Id.Should().Be(channel.Id);
            }

            foreach (string branchName in branchesThatDontMatch)
            {
                List <DefaultChannel> defaultChannels;
                {
                    IActionResult result = data.DefaultChannelsController.List(repository, branchName, channel.Id);
                    result.Should().BeAssignableTo <ObjectResult>();
                    var objResult = (ObjectResult)result;
                    objResult.StatusCode.Should().Be((int)HttpStatusCode.OK);
                    objResult.Value.Should().BeAssignableTo <IEnumerable <DefaultChannel> >();
                    defaultChannels = ((IEnumerable <DefaultChannel>)objResult.Value).ToList();
                }
                defaultChannels.Should().BeEmpty();
            }
        }
コード例 #54
0
        public void RepresentationEqualityEqualsTests()
        {
            var gp1 = TestData.PointG();
            var gp2 = TestData.PointG();
            Assert.True(gp1.Equals(gp2), "Values must be equal for points with same values");

            var fullGlobe1 = TestData.FullGlobe();
            var fullGlobe2 = TestData.FullGlobe();
            var fullGlobe3 = TestData.FullGlobe(CoordinateSystem.Geography(5555));
            Assert.True(fullGlobe1.Equals(fullGlobe2), "Values must be equal for globes in same coordinate system");
            Assert.False(fullGlobe1.Equals(fullGlobe3), "Values must be non-equal if they are in different coordinate systems");

            var geometryPoint1 = TestData.PointM();
            var geometryPoint2 = TestData.PointM();
            Assert.True(geometryPoint1.Equals(geometryPoint2), "Values must be equal for points with same values");

            var lineString1 = TestData.LineStringG();
            var lineString2 = TestData.LineStringG();
            Assert.True(lineString1.Equals(lineString2), "Values must be equal for line string with same values");

            var multiLineString1 = TestData.MultiLineStringG();
            var multiLineString2 = TestData.MultiLineStringG();
            Assert.True(multiLineString1.Equals(multiLineString2), "Values must be equal for multiLineString with same values");

            var multiPointImplementation1 = TestData.MultiPointG();
            var multiPointImplementation2 = TestData.MultiPointG();
            Assert.True(multiPointImplementation1.Equals(multiPointImplementation2), "Values must be equal for multiPoint with same values");

            var polygon1 = TestData.PolygonG();
            var polygon2 = TestData.PolygonG();
            Assert.True(polygon1.Equals(polygon2), "Values must be equal for polygon with same values");

            var multiPolygon1 = TestData.MultiPolygonG();
            var multiPolygon2 = TestData.MultiPolygonG();
            Assert.True(multiPolygon1.Equals(multiPolygon2), "Values must be equal for multiPolygon with same values");

            var geographyCollection1 = TestData.GeographyCollection();
            var geographyCollection2 = TestData.GeographyCollection();
            Assert.True(geographyCollection1.Equals(geographyCollection2), "Values must be equal for GeographyCollection with same values");

            var geometryLineString1 = TestData.LineStringM();
            var geometryLineString2 = TestData.LineStringM();
            Assert.True(geometryLineString1.Equals(geometryLineString2), "Values must be equal for line string with same values");

            var geometryMultiLineString1 = TestData.MultiLineStringM();
            var geometryMultiLineString2 = TestData.MultiLineStringM();
            Assert.True(geometryMultiLineString1.Equals(geometryMultiLineString2), "Values must be equal for multiLineString with same values");

            var geometryMultiPointImplementation1 = TestData.MultiPointM();
            var geometryMultiPointImplementation2 = TestData.MultiPointM();
            Assert.True(geometryMultiPointImplementation1.Equals(geometryMultiPointImplementation2), "Values must be equal for multiPoint with same values");

            var geometryPolygon1 = TestData.PolygonM();
            var geometryPolygon2 = TestData.PolygonM();
            Assert.True(geometryPolygon1.Equals(geometryPolygon2), "Values must be equal for polygon with same values");

            var geometryMultiPolygon1 = TestData.MultiPolygonM();
            var geometryMultiPolygon2 = TestData.MultiPolygonM();
            Assert.True(geometryMultiPolygon1.Equals(geometryMultiPolygon2), "Values must be equal for MultiPolygon with same values");

            var geometryCollection1 = TestData.GeometryCollection();
            var geometryCollection2 = TestData.GeometryCollection();
            Assert.True(geometryCollection1.Equals(geometryCollection2), "Values must be equal for GeometryCollection with same values");
        }
コード例 #55
0
ファイル: ProjectUpgradeTests.cs プロジェクト: wqhbuaa/PTVS
        public void OldWebProjectUpgrade()
        {
            // PTVS 2.1 Beta 1 shipped with separate .targets files for Bottle
            // and Flask. In PTVS 2.1 Beta 2 these were removed. This test
            // ensures that we upgrade projects created in 2.1 Beta 1.
            var factory = new PythonProjectFactory(null);
            var sp      = new MockServiceProvider();

            sp.Services[typeof(SVsQueryEditQuerySave).GUID] = null;
            sp.Services[typeof(SVsActivityLog).GUID]        = new MockActivityLog();
            factory.Site = sp;

            var upgrade = (IVsProjectUpgradeViaFactory)factory;

            foreach (var testCase in new[] {
                new { Name = "OldBottleProject.pyproj", Expected = 1 },
                new { Name = "OldFlaskProject.pyproj", Expected = 1 }
            })
            {
                int    actual;
                Guid   factoryGuid;
                string newLocation;

                // Use a copy of the project so we don't interfere with other
                // tests using them.
                var origProject = Path.Combine("TestData", "ProjectUpgrade", testCase.Name);
                var tempProject = Path.Combine(TestData.GetTempPath("ProjectUpgrade"), testCase.Name);
                File.Copy(origProject, tempProject);

                var hr = upgrade.UpgradeProject(
                    tempProject,
                    0u,  // no backups
                    null,
                    out newLocation,
                    null,
                    out actual,
                    out factoryGuid
                    );

                Assert.AreEqual(0, hr, string.Format("Wrong HR for {0}", testCase.Name));
                Assert.AreEqual(testCase.Expected, actual, string.Format("Wrong result for {0}", testCase.Name));
                Assert.AreEqual(tempProject, newLocation, string.Format("Wrong location for {0}", testCase.Name));
                if (testCase.Expected != 0)
                {
                    Assert.IsFalse(
                        File.ReadAllText(tempProject).Contains("<Import Project=\"$(VSToolsPath)"),
                        string.Format("Upgraded {0} should not import from $(VSToolsPath)", testCase.Name)
                        );
                    Assert.IsTrue(
                        File.ReadAllText(tempProject).Contains("Microsoft.PythonTools.Web.targets"),
                        string.Format("Upgraded {0} should import Web.targets", testCase.Name)
                        );
                    Assert.IsTrue(
                        File.ReadAllText(tempProject).Contains("<PythonWsgiHandler>"),
                        string.Format("Upgraded {0} should contain <PythonWsgiHandler>", testCase.Name)
                        );
                }
                else
                {
                    Assert.IsTrue(
                        File.ReadAllText(tempProject) == File.ReadAllText(origProject),
                        string.Format("Non-upgraded {0} has different content to original", testCase.Name)
                        );
                }
                Assert.AreEqual(Guid.Empty, factoryGuid);
            }
        }
コード例 #56
0
        public void GetHashCodeTests()
        {
            var gp1 = TestData.PointG();
            var gp2 = TestData.PointG();
            Assert.True(gp1.GetHashCode() == gp2.GetHashCode(), "HashCode must be equal for points with same values");

            var fullGlobe1 = TestData.FullGlobe();
            var fullGlobe2 = TestData.FullGlobe();
            var fullGlobe3 = TestData.FullGlobe(CoordinateSystem.Geography(5555));
            Assert.True(fullGlobe1.GetHashCode() == fullGlobe2.GetHashCode(), "HashCode must be equal for GeographyCollection with same values");
            Assert.True(fullGlobe1.GetHashCode() != fullGlobe3.GetHashCode(), "HashCode must be equal for GeographyCollection with same values");

            var geometryPoint1 = TestData.PointM();
            var geometryPoint2 = TestData.PointM();
            Assert.True(geometryPoint1.GetHashCode() == geometryPoint2.GetHashCode(), "HashCode must be equal for points with same values");

            var lineString1 = TestData.LineStringG();
            var lineString2 = TestData.LineStringG();
            Assert.True(lineString1.GetHashCode() == lineString2.GetHashCode(), "HashCode must be equal for line string with same values");

            var multiLineString1 = TestData.MultiLineStringG();
            var multiLineString2 = TestData.MultiLineStringG();
            Assert.True(multiLineString1.GetHashCode() == multiLineString2.GetHashCode(), "HashCode must be equal for multiLineString with same values");

            var multiPointImplementation1 = TestData.MultiPointG();
            var multiPointImplementation2 = TestData.MultiPointG();
            Assert.True(multiPointImplementation1.GetHashCode() == multiPointImplementation2.GetHashCode(), "HashCode must be equal for multiPoint with same values");

            var polygon1 = TestData.PolygonG();
            var polygon2 = TestData.PolygonG();
            Assert.True(polygon1.GetHashCode() == polygon2.GetHashCode(), "HashCode must be equal for polygon with same values");

            var multiPolygon1 = TestData.MultiPolygonG();
            var multiPolygon2 = TestData.MultiPolygonG();
            Assert.True(multiPolygon1.GetHashCode() == multiPolygon2.GetHashCode(), "HashCode must be equal for multiPolygon with same values");

            var geographyCollection1 = TestData.GeographyCollection();
            var geographyCollection2 = TestData.GeographyCollection();
            Assert.True(geographyCollection1.GetHashCode() == geographyCollection2.GetHashCode(), "HashCode must be equal for GeographyCollection with same values");

            var geometryLineString1 = TestData.LineStringM();
            var geometryLineString2 = TestData.LineStringM();
            Assert.True(geometryLineString1.GetHashCode() == geometryLineString2.GetHashCode(), "HashCode must be equal for line string with same values");

            var geometrymultiLineString1 = TestData.MultiLineStringM();
            var geometrymultiLineString2 = TestData.MultiLineStringM();
            Assert.True(geometrymultiLineString1.GetHashCode() == geometrymultiLineString2.GetHashCode(), "HashCode must be equal for multiLineString with same values");

            var geometrymultiPointImplementation1 = TestData.MultiPointM();
            var geometrymultiPointImplementation2 = TestData.MultiPointM();
            Assert.True(geometrymultiPointImplementation1.GetHashCode() == geometrymultiPointImplementation2.GetHashCode(), "HashCode must be equal for multiPoint with same values");

            var geometryPolygon1 = TestData.PolygonM();
            var geometryPolygon2 = TestData.PolygonM();
            Assert.True(geometryPolygon1.GetHashCode() == geometryPolygon2.GetHashCode(), "HashCode must be equal for polygon with same values");

            var geometryMultiPolygon1 = TestData.MultiPolygonM();
            var geometryMultiPolygon2 = TestData.MultiPolygonM();
            Assert.True(geometryMultiPolygon1.GetHashCode() == geometryMultiPolygon2.GetHashCode(), "HashCode must be equal for MultiPolygon with same values");

            var geometryCollection1 = TestData.GeometryCollection();
            var geometryCollection2 = TestData.GeometryCollection();
            Assert.True(geometryCollection1.GetHashCode() == geometryCollection2.GetHashCode(), "HashCode must be equal for GeometryCollection with same values");
        }
コード例 #57
0
 public void MyTestInitialize()
 {
     TestData = new TestData();
 }
コード例 #58
0
 public OperationResult <TestData> NewData(TestData data)
 {
     data.Id = "2";
     return(OpRes.Success(data));
 }
コード例 #59
0
        public void TestConversionEventEqualsSerializedPayload()
        {
            var guid      = Guid.NewGuid();
            var timeStamp = TestData.SecondsSince1970();

            var expectdPayload = new Dictionary <string, object>
            {
                { "client_version", Optimizely.SDK_VERSION },
                { "project_id", "111001" },
                { "enrich_decisions", true },
                { "account_id", "12001" },
                { "client_name", "csharp-sdk" },
                { "anonymize_ip", false },
                { "revision", "2" },
                { "visitors", new object[]
                  {
                      new Dictionary <string, object>
                      {
                          //visitors[0].attributes
                          {
                              "attributes", new object[]
                              {
                                  new Dictionary <string, string>
                                  {
                                      { "entity_id", "111094" },
                                      { "type", "custom" },
                                      { "value", "test_value" },
                                      { "key", "test_attribute" }
                                  }
                              }
                          },
                          //visitors[0].visitor_id
                          { "visitor_id", "test_user" },
                          //visitors[0].snapshots
                          { "snapshots", new object[]
                            {
                                //snapshots[0]
                                new Dictionary <string, object>
                                {
                                    //snapshots[0].events
                                    {
                                        "events", new object[]
                                        {
                                            new Dictionary <string, object>
                                            {
                                                { "uuid", guid },
                                                { "timestamp", timeStamp },
                                                { "revenue", 4200 },
                                                { "value", 1.234 },
                                                { "key", "event_with_multiple_running_experiments" },
                                                { "entity_id", "111095" },
                                                {
                                                    "tags", new Dictionary <string, object>
                                                    {
                                                        { "non-revenue", "abc" },
                                                        { "revenue", 4200 },
                                                        { "value", 1.234 },
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            } }
                      }
                  } }
            };

            EventBatch.Builder builder = new EventBatch.Builder();
            builder.WithAccountId("12001")
            .WithProjectID("111001")
            .WithClientVersion(Optimizely.SDK_VERSION)
            .WithRevision("2")
            .WithClientName("csharp-sdk")
            .WithAnonymizeIP(false)
            .WithEnrichDecisions(true);

            var visitorAttribute = new VisitorAttribute(entityId: "111094", type: "custom", value: "test_value", key: "test_attribute");

            var snapshotEvent = new SnapshotEvent.Builder()
                                .WithUUID(guid.ToString())
                                .WithEntityId("111095")
                                .WithKey("event_with_multiple_running_experiments")
                                .WithValue((long?)1.234)
                                .WithRevenue(4200)
                                .WithTimeStamp(timeStamp)
                                .WithEventTags(new EventTags
            {
                { "non-revenue", "abc" },
                { "revenue", 4200 },
                { "value", 1.234 }
            })
                                .Build();

            var snapshot = new Snapshot(events: new SnapshotEvent[] { snapshotEvent });

            var visitor = new Visitor(
                snapshots: new Snapshot[] {
                snapshot
            },
                attributes: new VisitorAttribute[] {
                visitorAttribute
            },
                visitorId: "test_user");

            builder.WithVisitors(new Visitor[] { visitor });

            EventBatch eventBatch = builder.Build();

            // Single Conversion Event
            TestData.CompareObjects(expectdPayload, eventBatch);
        }
コード例 #60
0
 public void Setup()
 {
     _Connection = TestData.SetupConnection();
 }