static TestCaseData T <T>(bool expectMutable, string name = null) { var tc = new TestCaseData(typeof(T)).Returns(expectMutable); if (!String.IsNullOrWhiteSpace(name)) { tc.SetName(name); } return(tc); }
/// <summary> /// Reads the Csv data drive file and set test name. /// </summary> /// <param name="file">Full path to csv DataDriveFile file</param> /// <param name="diffParam">The difference parameter.</param> /// <param name="testName">Name of the test, use as prefix for test case name.</param> /// <returns> /// IEnumerable TestCaseData /// </returns> /// <exception cref="System.InvalidOperationException">Exception when wrong cell type in file</exception> /// <exception cref="DataDrivenReadException">Exception when parameter not found in row</exception> /// <example>How to use it: <code> /// { /// var path = TestContext.CurrentContext.TestDirectory; /// path = string.Format(CultureInfo.CurrentCulture, "{0}{1}", path, @"\DataDriven\TestDataCsv.csv"); /// return DataDrivenHelper.ReadDataDriveFileCsv(path, new[] { "user", "password" }, "credentialCsv"); /// } /// </code></example> public static IEnumerable <TestCaseData> ReadDataDriveFileCsv(string file, string[] diffParam, string testName) { using (var fs = File.OpenRead(file)) using (var sr = new StreamReader(fs)) { string line = string.Empty; line = sr.ReadLine(); string[] columns = line.Split( new char[] { ',' }, StringSplitOptions.None); var columnsNumber = columns.Length; var row = 1; while (line != null) { string testCaseName; line = sr.ReadLine(); if (line != null) { var testParams = new Dictionary <string, string>(); string[] split = line.Split( new char[] { ',' }, StringSplitOptions.None); for (int i = 0; i < columnsNumber; i++) { testParams.Add(columns[i], split[i]); } try { testCaseName = TestCaseName(diffParam, testParams, testName); } catch (DataDrivenReadException e) { throw new DataDrivenReadException( string.Format( " Exception while reading Csv Data Driven file\n searched key '{0}' not found \n for test {1} in file '{2}' at row {3}", e.Message, testName, file, row)); } row = row + 1; var data = new TestCaseData(testParams); data.SetName(testCaseName); yield return(data); } } } }
/// <summary> /// Debug: 1 Axis Labels not centered /// </summary> private static TestCaseData DebugXAxisLabels() { var series = JsonConvert.DeserializeObject <ChartSeries[]>("[ { 'seriesName': 'Skynet', 'dataValues': [ null, null, null, null, null, null, null, null, 82.0, 55.0, 128.0, 3.0, 139.0, 90.0 ], 'dataPoints': [], 'style': null, 'color': null } ]"); var labels = JsonConvert.DeserializeObject <string[]>("[ 'Mar 2019', 'Apr 2019', 'May 2019', 'Jun 2019', 'Jul 2019', 'Aug 2019', 'Sep 2019', 'Oct 2019', 'Nov 2019', 'Dec 2019', 'Jan 2020', 'Feb 2020', 'Mar 2020', 'Apr 2020' ]"); var testCase = new TestCaseData(series, labels); testCase.SetName("Debug 1 - Axis Labels not centered"); testCase.SetDescription("Debug 1 - Axis Labels not centered"); return(testCase); }
/// <summary> /// Debug: Partial series joining /// </summary> private static TestCaseData DebugPartialSeriesJoining() { var series = JsonConvert.DeserializeObject <ChartSeries[]>("[ { 'seriesName': '2019-2020', 'dataValues': [ null, null, null, 82.0, 55.0, 128.0, 3.0, 139.0, 90.0, null, null, null ], 'dataPoints': [], 'style': null, 'color': null }, { 'seriesName': 'Forecast usage', 'dataValues': [ null, null, null, null, null, null, null, null, 90.0, 77.33, 102.11, 89.81 ], 'dataPoints': [], 'style': null, 'color': null } ]"); var labels = JsonConvert.DeserializeObject <string[]>("[ 'Aug 2019', 'Sep 2019', 'Oct 2019', 'Nov 2019', 'Dec 2019', 'Jan 2020', 'Feb 2020', 'Mar 2020', 'Apr 2020', 'May 2020', 'Jun 2020', 'Jul 2020' ]"); var testCase = new TestCaseData(series, labels); testCase.SetName("Debug 2 - 2 partial series"); testCase.SetDescription("Debug 2 - 2 partial series needs to appear like a single line, but the first series adds 0 instead of nulls at the end"); return(testCase); }
/// <summary> /// Debug: Argument exception /// </summary> private static TestCaseData DebugTest3() { var series = JsonConvert.DeserializeObject <ChartSeries[]>("[{\"SeriesName\":\"2019-2020\",\"DataValues\":[null,null,null,null,1.0,0.0,0.0,0.0,2.0,null,null,null],\"DataPoints\":[],\"Style\":null,\"Color\":null},{\"SeriesName\":\"Forecast usage\",\"DataValues\":[null,null,null,null,null,null,null,null,2.0,0.67,0.89,1.19],\"DataPoints\":[],\"Style\":null,\"Color\":null},{\"SeriesName\":\"Trend\",\"DataValues\":[0.12,0.14,0.16,0.19,0.21,0.24,0.26,0.29,0.31,0.34,0.36,0.38],\"DataPoints\":[],\"Style\":{\"IsDefaultStyle\":false,\"LabelStyle\":{\"Font\":\"Arial\",\"Draw\":false,\"StrokeWidth\":0,\"WidthPixels\":0.0,\"HeightPixels\":0.0,\"Size\":0,\"Fill\":\"grey\",\"FillOpacity\":1.0,\"StrokeOpacity\":1.0,\"StrokeColor\":\"none\",\"HasFill\":true,\"Overflow\":0},\"DrawLabel\":false,\"DataPointLabelPosition\":0,\"MarkerStyle\":{\"Radius\":0.0,\"Fill\":\"none\",\"FillOpacity\":1.0,\"StrokeOpacity\":1.0,\"StrokeColor\":\"grey\",\"StrokeWidth\":0.0,\"Draw\":false,\"HasFill\":false,\"Overflow\":0},\"ElementStyle\":{\"Fill\":\"none\",\"FillOpacity\":1.0,\"StrokeOpacity\":0.4,\"StrokeColor\":\"#F37748\",\"StrokeWidth\":4.0,\"Draw\":true,\"HasFill\":false,\"Overflow\":0}},\"Color\":null}]"); var labels = JsonConvert.DeserializeObject <string[]>("[\"Sep 2019\",\"Oct 2019\",\"Nov 2019\",\"Dec 2019\",\"Jan 2020\",\"Feb 2020\",\"Mar 2020\",\"Apr 2020\",\"May 2020\",\"Jun 2020\",\"Jul 2020\",\"Aug 2020\"]"); var testCase = new TestCaseData(series, labels); testCase.SetName("Debug 3 - Exception during YAxis export"); testCase.SetDescription("Exception when exporting YAxis data"); return(testCase); }
/// <summary> /// Debug: Incorrect dataPoints /// </summary> private static TestCaseData DebugTest4() { var series = JsonConvert.DeserializeObject <ChartSeries[]>("[ { \"seriesName\": \"Usage\", \"dataValues\": [ 1332.0, 1536.0, 1631.0, 1900.0, 2367.0, 2285.0, 4245.0, 5499.0, 4595.0, null, null, null, null, null ], \"dataPoints\": [], \"style\": null, \"color\": null } ]"); var labels = JsonConvert.DeserializeObject <string[]>("[ \"Apr 2019\", \"May 2019\", \"Jun 2019\", \"Jul 2019\", \"Aug 2019\", \"Sep 2019\", \"Oct 2019\", \"Nov 2019\", \"Dec 2019\", \"Jan 2020\", \"Feb 2020\", \"Mar 2020\", \"Apr 2020\", \"May 2020\" ]"); var testCase = new TestCaseData(series, labels); testCase.SetName("Debug 4 - DataPoints looks wrong"); testCase.SetDescription("Testing dataPoints"); return(testCase); }
public static IEnumerable <TestCaseData> Suite() { string[] files = Directory.GetFiles(@"..\..\Ralph.Core.Tests\AstCompareTests\TestCases", "*.cs"); foreach (string codefile in files) { string codefile1 = Path.GetFullPath(codefile); var tcase = new TestCaseData(codefile1); tcase.SetName(Path.GetFileNameWithoutExtension(codefile)); yield return(tcase); } }
//[TestCaseSource(nameof(GetDefaultGitPath_TestCases))] //public void GetDefaultGitPath(string localAppDataPath, string gitHubRootPath, string[] gitHubRootPathChildren, string gitExecutablePath) //{ // var environment = Substitute.For<IEnvironment>(); // environment.GetSpecialFolder(Arg.Is(Environment.SpecialFolder.LocalApplicationData)) // .Returns(localAppDataPath); // var filesystem = Substitute.For<IFileSystem>(); // filesystem.GetDirectories(gitHubRootPath) // .Returns(gitHubRootPathChildren); // var windowsGitInstallationStrategy = new WindowsGitEnvironment(environment, filesystem); // windowsGitInstallationStrategy.FindGitInstallationPath(TODO).Should().Be(gitExecutablePath); //} public static IEnumerable <TestCaseData> ValidateGitPath_TestCases() { var testCase = new TestCaseData(true, true); testCase.SetName("Should be found"); yield return(testCase); testCase = new TestCaseData(false, false); testCase.SetName("Should not be found"); yield return(testCase); }
IEnumerable <TestMethod> ITestBuilder.BuildFrom(IMethodInfo method, Test suite) { List <TestMethod> results = new List <TestMethod>(); var nameCounts = new Dictionary <string, int>(); if (m_sampleSet == null) { throw new Exception("SampleSet not set"); } try { foreach (var testCase in m_sampleSet) { var data = new TestCaseData(new object[] { testCase }); var uri = new Uri(testCase); string origName = System.IO.Path.GetFileName(uri.LocalPath); string name; if (nameCounts.TryGetValue(origName, out int count)) { name = string.Format("{0}-{1}", origName, count); nameCounts[origName] = count + 1; } else { name = origName; nameCounts[origName] = 1; } data.SetName(name); data.ExpectedResult = new UnityEngine.Object(); data.HasExpectedResult = true; var test = this._builder.BuildTestMethod(method, suite, data); if (test.parms != null) { test.parms.HasExpectedResult = false; } test.Name = name; results.Add(test); } } catch (Exception ex) { Console.WriteLine("Failed to generate glTF testcases!"); Debug.LogException(ex); throw; } Console.WriteLine("Generated {0} glTF test cases.", results.Count); return(results); }
public static void ResettingNameAfterSettingArgDisplayNamesIsNoOp() { var caseData = new TestCaseData(42).SetArgDisplayNames("42"); caseData.SetName(null); Assert.That(caseData.ArgDisplayNames, Is.EqualTo(new[] { "42" })); var fixtureData = new TestCaseData(42).SetArgDisplayNames("42"); fixtureData.SetName(null); Assert.That(fixtureData.ArgDisplayNames, Is.EqualTo(new[] { "42" })); }
private static TestCaseData GenData(int fullYears) { Organization.Manager managerEmployee = new Organization.Manager("Manager", "Manageroff", DateTime.Now.AddYears(-fullYears), Organization.BASEPAYRATE); TestCaseData data = new TestCaseData(managerEmployee); data.SetName(string.Format(namePattern, fullYears)); data.SetCategory(categoryName); return(data); }
public static void NullNameCanBeSet() { var caseData = new TestCaseData(42).SetName("Name"); caseData.SetName(null); Assert.That(caseData.TestName, Is.Null); var fixtureData = new TestFixtureData(42).SetName("Name"); fixtureData.SetName(null); Assert.That(fixtureData.TestName, Is.Null); }
/// <summary> /// Test case 9 /// </summary> private static TestCaseData ChartWithPartialSeries() { var testData = GetTestDataSet4(); var chart = new LineChart(testData.series, testData.labels); var testCase = new TestCaseData(chart); testCase.SetName("TestCase 9 - Test partial series"); testCase.SetDescription("Test case 9 : Test chart with partial series"); testCase.ExpectedResult = GetExpectedResults("TestCase-9.xml"); return(testCase); }
public static IEnumerable Cases() { var root = Path.GetDirectoryName(typeof(Tests).Assembly.Location); var tests = JArray.Parse(File.ReadAllText(Path.Combine(root, "ResolverTests.Json"))); foreach (var token in tests) { var data = token.ToObject <ResolverTestCase>(); var testCase = new TestCaseData(data); testCase.SetName(data.Name); yield return(testCase); } }
private static object ParseTestLine(object[] line) { var wif = (string)line[0]; var bytes = Encoders.Hex.GetBytes((string)line[1]); var metadata = (JObject)line[2]; var tc = new TestCaseData( wif, bytes, (string)metadata["isPrivkey"] == "True", (string)metadata["isTestnet"] == "True", (string)metadata["addrType"], (string)metadata["isCompressed"] == "True"); tc.SetName("Valid Key - " + wif); return(tc); }
public static IEnumerable <TestCaseData> SiteList() { var file = File.ReadAllText("sites.json", Encoding.UTF8); var jsonByte = Encoding.UTF8.GetBytes(file); var sites = JsonSerializer.Deserialize <Site[]>(jsonByte, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); return(sites !.Select(x => { var testCaseData = new TestCaseData(x); testCaseData.SetName(x.Name); return testCaseData; })); }
public static List <TestCaseData> GetTestData(string testDirPath, string configurationTemplate, string testNameSuffix) { List <string> configurations = GetTestConfigurations(testDirPath, configurationTemplate); List <TestCaseData> testDataList = new List <TestCaseData>(); foreach (string configuration in configurations) { var programArgs = JsonConvert.DeserializeObject <TestProjectRunnerArguments>(configuration); var testName = $"{GetTestName(programArgs.Versions[0])}_{testNameSuffix}"; var testData = new TestCaseData(configuration); testData.SetName(testName); testDataList.Add(testData); } return(testDataList); }
public IEnumerable GetObservations() { Type currentType = GetType(); string categoryName = "Uncategorized"; string description = string.Empty; IEnumerable <CategoryAttribute> categoryAttributes = currentType.GetTypeInfo().GetCustomAttributes(typeof(CategoryAttribute), true) .OfType <CategoryAttribute>() .ToArray(); IEnumerable <SubjectAttribute> subjectAttributes = currentType.GetTypeInfo().GetCustomAttributes(typeof(SubjectAttribute), true).OfType <SubjectAttribute>() .ToArray(); if (categoryAttributes.Any()) { CategoryAttribute categoryAttribute = categoryAttributes.First(); categoryName = categoryAttribute.Name; } if (subjectAttributes.Any()) { //SubjectAttribute subjectAttribute = subjectAttributes.First(); //description = subjectAttribute.Subject; } FieldInfo[] fieldInfos = currentType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy); FieldInfo[] itFieldInfos = fieldInfos.Where(field => field.FieldType == typeof(Then)).ToArray(); foreach (FieldInfo thenFieldInfo in itFieldInfos) { var data = new TestCaseData(thenFieldInfo.GetValue(this)); string caseDescription = (string.IsNullOrWhiteSpace(description) ? thenFieldInfo.Name : description) .NormalizeTestName().EnsureStartsWithPrefix(); data.SetDescription(caseDescription); data.SetName(thenFieldInfo.Name.NormalizeTestName().EnsureStartsWithPrefix() + " [" + thenFieldInfo.Name + "]"); data.SetCategory(categoryName); yield return(data); } }
public static IEnumerable <TestCaseData> ExtractMethodTestFactoryMethod() { string[] files = Directory.GetFiles(@"..\..\Ralph.Core.Tests\ExtractMethodTests\TestCases", "*.cs"); foreach (var file in files) { string codefile = Path.GetFullPath(file); string codeText = File.ReadAllText(codefile); var testCaseData = new TestCaseData(codeText); testCaseData.SetName(Path.GetFileNameWithoutExtension(codefile)); testCaseData.SetDescription(ParseDesc(codeText)); yield return(testCaseData); } }
private static List <TestCaseData> GetCollectorHostnameTestData() { var testDatas = new List <TestCaseData>(); var dllPath = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath); var jsonPath = Path.Combine(dllPath, "CrossAgentTests", "DataTransport", "collector_hostname.json"); var jsonString = File.ReadAllText(jsonPath); var objectArray = JArray.Parse(jsonString); foreach (var obj in objectArray) { var testData = new TestCaseData(new string[] { (string)obj["config_file_key"], (string)obj["env_key"], (string)obj["config_override_host"], (string)obj["env_override_host"], (string)obj["hostname"] }); testData.SetName("RunCrossAgentCollectorHostnameTests: " + (string)obj["name"]); testDatas.Add(testData); } return(testDatas); }
/// <summary> /// Test case 1 /// </summary> private static TestCaseData LineChartWithAllElements() { var testData = GetTestDataSet1(); var chart = new LineChart(testData.series, testData.labels, drawDefaultDataPointLabels: true, drawDefaultDataMarkers: true) { Height = 500, Width = 800, BackgroundColor = "#CCCCCC", LineType = LineType.Straight, Legend = { LegendIcon = LegendIcon.Circle, LabelStyle = { } }, XAxis = { MinorTickStyle = { StrokeWidth = 0.25, Length = 3 }, MajorTickStyle = { StrokeWidth = 0.5, Length = 5 } }, YAxis = { MinorTickStyle = { StrokeWidth = 0.25, Length = 3 }, MajorTickStyle = { StrokeWidth = 0.5, Length = 5 } }, ChartArea = { ChartAreaStyle = { StrokeWidth = 0.5 }, XGridLineStyle = { MajorLineStyle = { StrokeWidth = 0.5}, MinorLineStyle = { StrokeWidth = 0.25 } }, YGridLineStyle = { MajorLineStyle = { StrokeWidth = 0.5}, MinorLineStyle = { StrokeWidth = 0.25 } }, }, Title = { Text = "Test Case 1", }, DrawDebug = false }; var testCase = new TestCaseData(chart); testCase.SetName("TestCase 1 - Test most chart features"); testCase.SetDescription("Test case 1 : line chart with 3 series and the following all elements draw :\r\n" + "- Straight lines\r\n" + "- DataPoints drawn\r\n" + "- DataPointLabels drawn\r\n" + "- Major and minor X grid lines\r\n" + "- Major and minor Y grid lines\r\n" + "- X axis with labels, minor and major ticks\r\n" + "- Y axis with labels, minor and major ticks\r\n" + "- Legend with label and circle icon\r\n"); testCase.ExpectedResult = GetExpectedResults("TestCase-1.xml"); return(testCase); }
public static IEnumerable <TestCaseData> TestCases() { foreach (Type nestedType in typeof(TestHelpers.PubSub).GetNestedTypes()) { var publications = GetCalls(nestedType, Channel.PublisherToBroker, new[] { WampMessageType.v2Publish }); var publicationAcks = GetCalls(nestedType, Channel.BrokerToPublisher, new[] { WampMessageType.v2Published }) .ToArray(); var publicationErrors = GetCalls(nestedType, Channel.BrokerToPublisher, new[] { WampMessageType.v2Error }); var subscriptions = GetCalls(nestedType, Channel.SubscriberToBroker, new[] { WampMessageType.v2Subscribe }); var subscriptionAcks = GetCalls(nestedType, Channel.BrokerToSubscriber, new[] { WampMessageType.v2Subscribed }) .ToArray(); var events = GetCalls(nestedType, Channel.BrokerToSubscriber, new[] { WampMessageType.v2Event }) .ToArray(); BrokerScenario scenario = new BrokerScenario(); scenario.Publications = publications; scenario.PublicationAcks = publicationAcks; scenario.PublicationErrors = publicationErrors; scenario.Subscriptions = subscriptions; scenario.Events = events; MockClient <IWampClientProxy <MockRaw> > subscriber = GetSubscriber(nestedType, scenario.ClientBuilder, scenario.Handler, events.Concat(subscriptionAcks)); MockClient <IWampClientProxy <MockRaw> > publisher = GetPublisher(nestedType, scenario.ClientBuilder, publicationAcks); scenario.Subscriber = subscriber; scenario.Publisher = publisher; TestCaseData testCase = new TestCaseData(scenario); testCase.SetName(string.Format("PubSubIntegrationTest.{0}", nestedType.Name)); yield return(testCase); } }
/// <summary> /// Test case 21 /// </summary> private static TestCaseData DocumentationSample2() { var testData = DocumentationSampleDataSet2(); var chart = new LineChart(testData.series, testData.labels) { Height = 300, Width = 1500, LineType = LineType.Curved, PaddingRight = 15, XAxis = { StartOnMajor = true }, ChartArea = { SeriesStyles = new[] { new LineSeriesStyle() { ElementStyle = { StrokeColor = "none", StrokeWidth = 1, Fill = "#4674C5", FillOpacity = 0.4 }, MarkerStyle = { StrokeWidth = 0 }, LabelStyle = { Size = 0, StrokeColor = "#3D3D3D" }, DataPointLabelPosition = Position.Centre }, new LineSeriesStyle() { ElementStyle = { StrokeColor = "none", StrokeWidth = 1, Fill = "#267F00", FillOpacity = 0.4 }, MarkerStyle = { StrokeWidth = 0 }, LabelStyle = { Size = 0, StrokeColor = "#3D3D3D" }, DataPointLabelPosition = Position.Centre }, }, YGridLineStyle = { MajorLineStyle = { StrokeWidth = 0.7, StrokeStyle = LineStyle.Dashed }, MinorLineStyle = { StrokeWidth = 0 } } }, DrawDebug = false }; var testCase = new TestCaseData(chart); testCase.SetName("TestCase 21 - Documentation sample 2."); testCase.SetDescription("Test case 21 : Curved line chart with custom data points, only dataPoint labels are drawn in centre position"); testCase.ExpectedResult = GetExpectedResults("TestCase-21.xml"); return(testCase); }
public IEnumerable <TestCaseData> TestCases() { foreach (Type nestedType in typeof(TestHelpers.Rpc).GetNestedTypes()) { var scenarioCalls = GetCalls(nestedType, Channel.CallerToDealer, MessageTypes.Rpc) .Concat(GetCalls(nestedType, Channel.DealerToCaller, MessageTypes.Rpc)) .GroupBy(x => x.GetRequestId()) .Where(x => x.Key != null); var registrations = GetCalls(nestedType, Channel.CalleeToDealer, new WampMessageType[] { WampMessageType.v2Register }); foreach (var currentCase in scenarioCalls) { DealerScenario scenario = new DealerScenario(); MockClient <IWampClientProxy <MockRaw> > callee = GetCallee(nestedType, scenario.ClientBuilder, scenario.Handler); MockClient <IWampClientProxy <MockRaw> > caller = GetCaller(nestedType, scenario.ClientBuilder); WampMessage <MockRaw> request = currentCase.FirstOrDefault(x => x.MessageType == WampMessageType.v2Call); WampMessage <MockRaw>[] responses = currentCase.Where(x => x.MessageType != WampMessageType.v2Call) .ToArray(); scenario.Call = new DealerCall() { Request = request, Responses = responses }; scenario.Registrations = registrations; scenario.Callee = callee; scenario.Caller = caller; TestCaseData testCase = new TestCaseData(scenario); testCase.SetName(string.Format("DealerIntegrationTest.{0}.{1}", nestedType.Name, request.Arguments[2].Value)); yield return(testCase); } } }
/// <summary> /// Debug : Weird series /// </summary> private static TestCaseData DebugTest5() { var series = new[] { new ChartSeries("Usage", new double?[] { null, null, null, null, null, null, null, null, 1.0, 0, 0, 0, 2, 386 }), }; var labels = new[] { "Apr 2019", "May 2019", "Jun 2019", "Jul 2019", "Aug 2019", "Sep 2019", "Oct 2019", "Nov 2019", "Dec 2019", "Jan 2020", "Feb 2020", "Mar 2020", "Apr 2020", "May 2020" }; var testCase = new TestCaseData(series, labels); testCase.SetName("Debug 5 - Test dataSet"); testCase.SetDescription("Testing dataPoints"); return(testCase); }
public static IEnumerable <ITestCaseData> GetTestCases() { const string prefix = "MongoDB.Driver.Specifications.server_selection.tests.server_selection."; return(Assembly .GetExecutingAssembly() .GetManifestResourceNames() .Where(path => path.StartsWith(prefix) && path.EndsWith(".json")) .Select(path => { var definition = ReadDefinition(path); var fullName = path.Remove(0, prefix.Length); var data = new TestCaseData(definition); data.Categories.Add("Specifications"); data.Categories.Add("server-selection"); return data.SetName(fullName.Remove(fullName.Length - 5).Replace(".", "_")); })); }
private static TestCaseData GetTestCaseData <TToSerialize, TTargetValue>( string name, TToSerialize objectToSerialize, Func <TToSerialize, TTargetValue> getTargetValue, Func <XElement, object> getTargetNodeValue, object expectedTargetNodeValue, params Type[] extraTypes) { var testCaseData = new TestCaseData( objectToSerialize, (Func <object, object>)(target => getTargetValue((TToSerialize)target)), getTargetNodeValue, expectedTargetNodeValue, extraTypes); return(testCaseData.SetName(name)); }
private static TestCaseData GetManagerWithSubordinnatesData(int fullYears, double expectedResult, int[] gruntYears = null, int[] managersYears = null, int[] salesYears = null) { var manager = new Organization.Manager("Manager", "Manageroff", DateTime.Now.AddYears(-fullYears), Organization.BASEPAYRATE); int gruntsCount = 0; int managersCount = 0; int salesCount = 0; if (gruntYears != null) { gruntsCount = gruntYears.Length; foreach (var fullYear in gruntYears) { GetGrunt(fullYear).SetManager(manager); } } if (managersYears != null) { managersCount = managersYears.Length; foreach (var fullYear in managersYears) { GetManager(fullYear).SetManager(manager); } } if (salesYears != null) { salesCount = salesYears.Length; foreach (var fullYear in salesYears) { GetSales(fullYear).SetManager(manager); } } var data = new TestCaseData(manager); data.SetCategory(categoryName); data.SetDescription(string.Format(descriptionPattern, fullYears, gruntsCount, managersCount, salesCount)); data.SetName(string.Format(namePattern, fullYears, gruntsCount + managersCount + salesCount)); data.Returns(expectedResult); return(data); }
public IEnumerable GetObservations() { var t = GetType(); var categoryName = "Uncategorized"; var description = string.Empty; var categoryAttributes = t.GetTypeInfo().GetCustomAttributes(typeof(CategoryAttribute), true); var subjectAttributes = t.GetTypeInfo().GetCustomAttributes(typeof(SubjectAttribute), true); if (categoryAttributes.Any()) { var categoryAttribute = (CategoryAttribute)categoryAttributes.First(); categoryName = categoryAttribute.Name; } if (subjectAttributes.Any()) { var subjectAttribute = (SubjectAttribute)subjectAttributes.First(); description = subjectAttribute.Subject; } var fieldInfos = t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy); var itFieldInfos = new List <FieldInfo>(); foreach (var info in fieldInfos) { if (info.FieldType.Name.Equals("It")) { itFieldInfos.Add(info); } } foreach (var it in itFieldInfos) { var data = new TestCaseData(it.GetValue(this)); data.SetDescription(description); data.SetName(it.Name.Replace("_", " ")); data.SetCategory(categoryName); yield return(data); } }
private IEnumerable <TestCaseData> BuildTestCases(IEnumerable <TestXml> tests) { var testCases = new List <TestCaseData>(tests.Count()); foreach (var test in tests) { TestCaseData testCaseDataNUnit = new TestCaseData(test); testCaseDataNUnit.SetName(test.GetName()); testCaseDataNUnit.SetDescription(test.Description); foreach (var category in test.Categories) { testCaseDataNUnit.SetCategory(CategoryHelper.Format(category)); } foreach (var property in test.Traits) { testCaseDataNUnit.SetProperty(property.Name, property.Value); } //Assign auto-categories if (EnableAutoCategories) { foreach (var system in test.Systems) { foreach (var category in system.GetAutoCategories()) { testCaseDataNUnit.SetCategory(CategoryHelper.Format(category)); } } } //Assign auto-categories if (EnableGroupAsCategory) { foreach (var groupName in test.GroupNames) { testCaseDataNUnit.SetCategory(CategoryHelper.Format(groupName)); } } testCases.Add(testCaseDataNUnit); } return(testCases); }
/// <summary> /// Get files to compare. /// </summary> /// <param name="type">Files type</param> /// <returns> /// Pairs of files to compare <see cref="IEnumerable"/>. /// </returns> private static IEnumerable<TestCaseData> FindFiles(FileType type) { Logger.Info("Get Files {0}:", type); var liveFiles = FilesHelper.GetFilesOfGivenType(ProjectBaseConfiguration.DownloadFolderPath, type, "live"); if (liveFiles != null) { foreach (FileInfo liveFile in liveFiles) { Logger.Trace("liveFile: {0}", liveFile); var fileNameBranch = liveFile.Name.Replace("live", "branch"); var testCaseName = liveFile.Name.Replace("_" + "live", string.Empty); TestCaseData data = new TestCaseData(liveFile.Name, fileNameBranch); data.SetName(Regex.Replace(testCaseName, @"[.]+|\s+", "_")); Logger.Trace("file Name Short: {0}", testCaseName); yield return data; } } }
/// <summary> /// Reads the data drive file and set test name. /// </summary> /// <param name="folder">Full path to XML DataDriveFile file</param> /// <param name="testData">Name of the child element in xml file.</param> /// <param name="diffParam">Values of listed parameters will be used in test case name.</param> /// <param name="testName">Name of the test, use as prefix for test case name.</param> /// <returns> /// IEnumerable TestCaseData /// </returns> /// <exception cref="System.ArgumentNullException">Exception when element not found in file</exception> /// <exception cref="DataDrivenReadException">Exception when parameter not found in row</exception> /// <example>How to use it: <code> /// public static IEnumerable Credentials /// { /// get { return DataDrivenHelper.ReadDataDriveFile(ProjectBaseConfiguration.DataDrivenFile, "credential", new[] { "user", "password" }, "credential"); } /// } /// </code></example> public static IEnumerable<TestCaseData> ReadDataDriveFile(string folder, string testData, string[] diffParam, [Optional] string testName) { var doc = XDocument.Load(folder); if (!doc.Descendants(testData).Any()) { throw new ArgumentNullException(string.Format(" Exception while reading Data Driven file\n row '{0}' not found \n in file '{1}'", testData, folder)); } foreach (XElement element in doc.Descendants(testData)) { var testParams = element.Attributes().ToDictionary(k => k.Name.ToString(), v => v.Value); var testCaseName = string.IsNullOrEmpty(testName) ? testData : testName; try { testCaseName = TestCaseName(diffParam, testParams, testCaseName); } catch (DataDrivenReadException e) { throw new DataDrivenReadException( string.Format( " Exception while reading Data Driven file\n test data '{0}' \n test name '{1}' \n searched key '{2}' not found in row \n '{3}' \n in file '{4}'", testData, testName, e.Message, element, folder)); } var data = new TestCaseData(testParams); data.SetName(testCaseName); yield return data; } }