Best NBi code snippet using NBi.NUnit.Builder.Helper.SetupHelper.Execute
TestSuiteTest.cs
Source:TestSuiteTest.cs
...300 Assert.That(TestSuite.OverridenVariables.ContainsKey("myVar"), Is.True);301 Assert.That(TestSuite.OverridenVariables["myVar"], Is.EqualTo(123.12));302 }303 [Test]304 public void ExecuteSetup_SingleDecoration_Executed()305 {306 var commandMock = new Mock<IDecorationCommand>();307 commandMock.Setup(x => x.Execute());308 var testSuite = new TestSuite();309 testSuite.ExecuteSetup(new[] { commandMock.Object });310 commandMock.Verify(x => x.Execute(), Times.Once());311 }312 [Test]313 public void ExecuteSetup_MultipleDecorationImplicitGroup_ExecutedCorrectOrder()314 {315 var firstCommandMock = new Mock<IDecorationCommand>(MockBehavior.Strict);316 var secondCommandMock = new Mock<IDecorationCommand>(MockBehavior.Strict);317 var sequence = new MockSequence();318 firstCommandMock.InSequence(sequence).Setup(x => x.Execute());319 secondCommandMock.InSequence(sequence).Setup(x => x.Execute());320 var testSuite = new TestSuite();321 testSuite.ExecuteSetup(new[] { firstCommandMock.Object, secondCommandMock.Object });322 firstCommandMock.Verify(x => x.Execute(), Times.Once());323 secondCommandMock.Verify(x => x.Execute(), Times.Once());324 }325 [Test]326 public void ExecuteSetup_MultipleDecorationExplicitGroupSequence_ExecutedCorrectOrder()327 {328 329 var firstCommandMock = new Mock<IDecorationCommand>(MockBehavior.Strict);330 var secondCommandMock = new Mock<IDecorationCommand>(MockBehavior.Strict);331 var sequence = new MockSequence();332 firstCommandMock.InSequence(sequence).Setup(x => x.Execute());333 secondCommandMock.InSequence(sequence).Setup(x => x.Execute());334 var groupCommand = new SequentialCommand(new[] { firstCommandMock.Object, secondCommandMock.Object }, false);335 336 var testSuite = new TestSuite();337 testSuite.ExecuteSetup(new[] { groupCommand });338 firstCommandMock.Verify(x => x.Execute(), Times.Once());339 secondCommandMock.Verify(x => x.Execute(), Times.Once());340 }341 [Test]342 public void ExecuteSetup_MultipleDecorationExplicitGroupSequence_NotStartingBeforePreviousIsFinalized()343 {344 var firstCommandStub = new Mock<IDecorationCommand>(MockBehavior.Strict);345 var secondCommandStub = new Mock<IDecorationCommand>(MockBehavior.Strict);346 var sequence = new MockSequence();347 Mock<IDecorationCommand> lastReturned = null;348 firstCommandStub.InSequence(sequence).Setup(x => x.Execute()).Callback(() => { System.Threading.Thread.Sleep(100); lastReturned = firstCommandStub; });349 secondCommandStub.InSequence(sequence).Setup(x => x.Execute()).Callback(() => { System.Threading.Thread.Sleep(10); lastReturned = secondCommandStub; });350 var groupCommand = new SequentialCommand(new[] { firstCommandStub.Object, secondCommandStub.Object }, false);351 var testSuite = new TestSuite();352 testSuite.ExecuteSetup(new[] { groupCommand });353 Assert.That(lastReturned, Is.EqualTo(secondCommandStub));354 }355 [Test]356 public void ExecuteSetup_MultipleDecorationExplicitGroupSequence_BothExecuted()357 {358 var firstCommandMock = new Mock<IDecorationCommand>();359 var secondCommandMock = new Mock<IDecorationCommand>();360 firstCommandMock.Setup(x => x.Execute());361 secondCommandMock.Setup(x => x.Execute());362 var groupCommand = new ParallelCommand(new[] { firstCommandMock.Object, secondCommandMock.Object }, false);363 var testSuite = new TestSuite();364 testSuite.ExecuteSetup(new[] { groupCommand });365 firstCommandMock.Verify(x => x.Execute(), Times.Once());366 secondCommandMock.Verify(x => x.Execute(), Times.Once());367 }368 [Test]369 public void ExecuteSetup_MultipleDecorationExplicitGroupParallel_ExecutedInParallel()370 {371 var firstCommandStub = new Mock<IDecorationCommand>(MockBehavior.Strict);372 var secondCommandStub = new Mock<IDecorationCommand>(MockBehavior.Strict);373 Mock<IDecorationCommand> lastReturned = null;374 firstCommandStub.Setup(x => x.Execute()).Callback(() => { System.Threading.Thread.Sleep(100); lastReturned = firstCommandStub; });375 secondCommandStub.Setup(x => x.Execute()).Callback(() => { System.Threading.Thread.Sleep(10); lastReturned = secondCommandStub; });376 var groupCommand = new ParallelCommand(new[] { firstCommandStub.Object, secondCommandStub.Object }, false);377 var testSuite = new TestSuite();378 testSuite.ExecuteSetup(new[] { groupCommand });379 Assert.That(lastReturned, Is.EqualTo(firstCommandStub));380 }381 [Test]382 public void ExecuteSetup_MultipleDecorationRunOnce_ExecutedOnce()383 {384 var commandMock = new Mock<IDecorationCommand>();385 commandMock.Setup(x => x.Execute());386 var groupCommand = new SequentialCommand(new[] { commandMock.Object }, true);387 var testSuite = new TestSuite();388 testSuite.ExecuteSetup(new[] { groupCommand });389 commandMock.Verify(x => x.Execute(), Times.Once());390 testSuite.ExecuteSetup(new[] { groupCommand });391 commandMock.Verify(x => x.Execute(), Times.Once());392 }393 [Test]394 public void ExecuteSetup_MultipleDecorationRunMultiple_ExecutedMultiple()395 {396 var commandMock = new Mock<IDecorationCommand>();397 commandMock.Setup(x => x.Execute());398 var groupCommand = new SequentialCommand(new[] { commandMock.Object }, false);399 var testSuite = new TestSuite();400 testSuite.ExecuteSetup(new[] { groupCommand });401 commandMock.Verify(x => x.Execute(), Times.Exactly(1));402 testSuite.ExecuteSetup(new[] { groupCommand });403 commandMock.Verify(x => x.Execute(), Times.Exactly(2));404 testSuite.ExecuteSetup(new[] { groupCommand });405 commandMock.Verify(x => x.Execute(), Times.Exactly(3));406 }407 [Test]408 public void BuildSetup_SameCommandWithoutRunOnce_InstantiatedMultipleTime()409 {410 var commandXml = new CommandGroupXml();411 var firstSetupXml = new SetupXml() { Commands = new List<DecorationCommandXml>() { commandXml } };412 var secondSetupXml = new SetupXml() { Commands = new List<DecorationCommandXml>() { commandXml } };413 var testSuite = new TestSuite();414 var setupHelper = new SetupHelper(new ServiceLocator(), new Dictionary<string, IVariable>());415 var commands = new List<IDecorationCommand>();416 commands.AddRange(testSuite.BuildSetup(setupHelper, firstSetupXml));417 commands.AddRange(testSuite.BuildSetup(setupHelper, secondSetupXml));418 Assert.That(commands.Count(), Is.EqualTo(2));419 Assert.That(commands[0], Is.Not.EqualTo(commands[1]));...
TestSuite.cs
Source:TestSuite.cs
...80 ConnectionStringsFinder = connectionStringsFinder;81 }8283 [Test, TestCaseSource("GetTestCases")]84 public virtual void ExecuteTestCases(TestXml test, string testName, IDictionary<string, IVariable> localVariables)85 {86 if (ConfigurationProvider != null)87 {88 Trace.WriteLineIf(NBiTraceSwitch.TraceError, string.Format("Loading configuration"));89 var config = ConfigurationProvider.GetSection();90 ApplyConfig(config);91 }92 else93 Trace.WriteLineIf(NBiTraceSwitch.TraceError, $"No configuration-finder found.");9495 Trace.WriteLineIf(NBiTraceSwitch.TraceVerbose, $"Test loaded by {GetOwnFilename()}");96 Trace.WriteLineIf(NBiTraceSwitch.TraceInfo, $"{Variables.Count()} variables defined, {Variables.Count(x => x.Value.IsEvaluated())} already evaluated.");9798 if (serviceLocator == null)99 Initialize();100101 //check if ignore is set to true102 if (test.IsNotImplemented)103 {104 Trace.WriteLineIf(NBiTraceSwitch.TraceInfo, $"Test not-implemented, will be ignored. Reason is '{test.NotImplemented.Reason}'");105 Assert.Ignore(test.IgnoreReason);106 }107 else if (test.Ignore)108 {109 Trace.WriteLineIf(NBiTraceSwitch.TraceInfo, $"Test ignored. Reason is '{test.IgnoreReason}'");110 Assert.Ignore(test.IgnoreReason);111 }112 else113 {114 Trace.WriteLineIf(NBiTraceSwitch.TraceInfo, $"Running test '{testName}' #{test.UniqueIdentifier}");115 var allVariables = Variables.Union(localVariables).ToDictionary(x => x.Key, x=>x.Value);116 ValidateConditions(test.Condition, allVariables);117 RunSetup(test.Setup, allVariables);118 foreach (var sut in test.Systems)119 {120 if ((test?.Constraints.Count ?? 0) == 0)121 Trace.WriteLineIf(NBiTraceSwitch.TraceWarning, $"Test '{testName}' has no constraint. It will always result in a success.");122 123 foreach (var ctr in test.Constraints)124 {125 var factory = new TestCaseFactory(Configuration, allVariables, serviceLocator);126 var testCase = factory.Instantiate(sut, ctr);127 try128 {129 AssertTestCase(testCase.SystemUnderTest, testCase.Constraint, test.Content);130 }131 catch132 {133 ExecuteCleanup(test.Cleanup, allVariables);134 throw;135 }136 }137 }138 ExecuteCleanup(test.Cleanup, allVariables);139 }140 }141142 private void ValidateConditions(ConditionXml condition, IDictionary<string, IVariable> allVariables)143 {144 foreach (var predicate in condition.Predicates)145 {146 var helper = new ConditionHelper(serviceLocator, allVariables);147 var args = helper.Execute(predicate);148 var impl = new DecorationFactory().Instantiate(args);149 var isVerified = impl.Validate();150 if (!isVerified)151 {152 Trace.WriteLineIf(NBiTraceSwitch.TraceInfo, $"Test ignored. At least one condition was not validated: '{impl.Message}'");153 Assert.Ignore($"This test has been ignored because following check wasn't successful: {impl.Message}");154 }155 }156 }157158 private void RunSetup(SetupXml setupXml, IDictionary<string, IVariable> allVariables)159 {160 var setupHelper = new SetupHelper(serviceLocator, allVariables);161 var commands = BuildSetup(setupHelper, setupXml);162 ExecuteSetup(commands);163 }164165 internal IEnumerable<IDecorationCommand> BuildSetup(SetupHelper helper, SetupXml setupXml)166 {167 var commandArgs = helper.Execute(setupXml.Commands);168 var factory = new DecorationFactory();169170 var commands = new List<IDecorationCommand>();171 foreach (var arg in commandArgs)172 {173 if (Setups.ContainsKey(arg.Guid))174 commands.Add(Setups[arg.Guid]);175 else176 { 177 var command = factory.Instantiate(arg);178 if (command is IGroupCommand groupCommand && groupCommand.RunOnce)179 Setups.Add(arg.Guid, command);180 commands.Add(command);181 }182 }183 return commands;184 }185186 internal void ExecuteSetup(IEnumerable<IDecorationCommand> commands)187 { 188 try189 {190 foreach (var command in commands)191 {192 if (!((command is IGroupCommand groupCommand) && groupCommand.RunOnce && groupCommand.HasRun))193 {194 command.Execute();195 if (command is IGroupCommand executedGroupCommand)196 executedGroupCommand.HasRun = true;197 }198 }199 }200 catch (Exception ex)201 {202 HandleExceptionDuringSetup(ex);203 }204 }205206 protected virtual void HandleExceptionDuringSetup(Exception ex)207 {208 var message = string.Format("Exception during the setup of the test: {0}", ex.Message);209 message += "\r\n" + ex.StackTrace;210 if (ex.InnerException != null)211 {212 message += "\r\n" + ex.InnerException.Message;213 message += "\r\n" + ex.InnerException.StackTrace;214 }215 Trace.WriteLineIf(NBiTraceSwitch.TraceWarning, message);216 //If failure during setup then the test is failed!217 Assert.Fail(message);218 }219220 private void ExecuteCleanup(CleanupXml cleanup, IDictionary<string, IVariable> allVariables)221 {222 var cleanupHelper = new SetupHelper(serviceLocator, allVariables);223 var commands = cleanupHelper.Execute(cleanup.Commands);224225 try226 {227 foreach (var command in commands)228 {229 var impl = new DecorationFactory().Instantiate(command);230 impl.Execute();231 }232 }233 catch (Exception ex)234 {235 HandleExceptionDuringCleanup(ex);236 }237 }238239 protected virtual void HandleExceptionDuringCleanup(Exception ex)240 {241 var message = string.Format("Exception during the cleanup of the test: {0}", ex.Message);242 Trace.WriteLineIf(NBiTraceSwitch.TraceWarning, message);243 Trace.WriteLineIf(NBiTraceSwitch.TraceWarning, "Next cleanup functions are skipped.");244 }245246 /// <summary>247 /// Handles the standard assertion and if needed rethrow a new AssertionException with a modified stacktrace248 /// </summary>249 /// <param name="systemUnderTest"></param>250 /// <param name="constraint"></param>251 protected internal void AssertTestCase(object systemUnderTest, NUnitCtr.Constraint constraint, string stackTrace)252 {253 try254 {255 Assert.That(systemUnderTest, constraint);256 }257 catch (AssertionException ex)258 {259 throw new CustomStackTraceAssertionException(ex, stackTrace);260 }261 catch (NBiException ex)262 {263 throw new CustomStackTraceErrorException(ex, stackTrace);264 }265 }266267 public IEnumerable<TestCaseData> GetTestCases()268 {269 Trace.WriteLineIf(NBiTraceSwitch.TraceInfo, $"GetTestCases() has been called");270 //Find configuration of NBi271 var config = ConfigurationProvider.GetSection();272 ApplyConfig(config);273274 //Find connection strings referecned from an external file275 if (ConnectionStringsFinder != null)276 TestSuiteManager.ConnectionStrings = ConnectionStringsFinder.Find();277278 //Service Locator279 if (serviceLocator == null)280 Initialize();281282 //Build the Test suite283 var testSuiteFilename = TestSuiteProvider.GetFilename(config.TestSuiteFilename);284 TestSuiteManager.Load(testSuiteFilename, SettingsFilename, AllowDtdProcessing);285 serviceLocator.SetBasePath(TestSuiteManager.TestSuite.Settings.BasePath); 286287 //Build the variables288 Variables = BuildVariables(TestSuiteManager.TestSuite.Variables, OverridenVariables);289290 return BuildTestCases();291 }292293 private IDictionary<string, IVariable> BuildVariables(IEnumerable<GlobalVariableXml> variables, IDictionary<string, object> overridenVariables)294 {295 var instances = new Dictionary<string, IVariable>();296 var resolverFactory = serviceLocator.GetScalarResolverFactory();297298 Trace.WriteLineIf(NBiTraceSwitch.TraceInfo, $"{variables.Count()} variable{(variables.Count() > 1 ? "s" : string.Empty)} defined in the test-suite.");299 var variableFactory = new VariableFactory();300 foreach (var variable in variables)301 {302 if (overridenVariables.ContainsKey(variable.Name))303 {304 var instance = new OverridenVariable(variable.Name, overridenVariables[variable.Name]);305 instances.Add(variable.Name, instance);306 }307 else308 {309 var builder = new ScalarResolverArgsBuilder(serviceLocator, new Context(instances));310 311 if (variable.Script != null)312 builder.Setup(variable.Script);313 else if (variable.QueryScalar != null)314 {315 variable.QueryScalar.Settings = TestSuiteManager.TestSuite.Settings;316 variable.QueryScalar.Default = TestSuiteManager.TestSuite.Settings.GetDefault(Xml.Settings.SettingsXml.DefaultScope.Variable);317 builder.Setup(variable.QueryScalar, variable.QueryScalar.Settings, Xml.Settings.SettingsXml.DefaultScope.Variable);318 }319 else if (variable.Environment != null)320 builder.Setup(variable.Environment);321 else if (variable.Custom != null)322 builder.Setup(variable.Custom);323 builder.Build();324 var args = builder.GetArgs();325326 var resolver = resolverFactory.Instantiate(args);327 instances.Add(variable.Name, variableFactory.Instantiate(VariableScope.Global, resolver));328 }329330 }331332 return instances;333 }334335 internal IEnumerable<TestCaseData> BuildTestCases()336 {337 List<TestCaseData> testCasesNUnit = new List<TestCaseData>();338339 testCasesNUnit.AddRange(BuildTestCases(TestSuiteManager.TestSuite.Tests));340 testCasesNUnit.AddRange(BuildTestCases(TestSuiteManager.TestSuite.Groups));341342 return testCasesNUnit;343 }344345 private IEnumerable<TestCaseData> BuildTestCases(IEnumerable<TestXml> tests)346 {347 var testCases = new List<TestCaseData>(tests.Count());348349 foreach (var test in tests)350 {351 // Build different instances for a test, if no instance-settling is defined then the default instance is created352 var instanceArgsBuilder = new InstanceArgsBuilder(serviceLocator, Variables);353 instanceArgsBuilder.Setup(TestSuiteManager.TestSuite.Settings);354 instanceArgsBuilder.Setup(test.InstanceSettling);355 instanceArgsBuilder.Build();356357 var factory = new InstanceFactory();358 var instances = factory.Instantiate(instanceArgsBuilder.GetArgs());359360 // For each instance create a test-case361 foreach (var instance in instances)362 {363 var scalarHelper = new ScalarHelper(serviceLocator, new Context(instance.Variables));364365 var testName = instance.IsDefault 366 ? $"{test.GetName()}" 367 : test.GetName().StartsWith("~")368 ? scalarHelper.InstantiateResolver<string>(test.GetName()).Execute()369 : $"{test.GetName()} ({instance.GetName()})";370 Trace.WriteLineIf(NBiTraceSwitch.TraceVerbose, $"Loading test named: {testName}");371 var testCaseDataNUnit = new TestCaseData(test, testName, instance.Variables);372 testCaseDataNUnit.SetName(testName);373374 testCaseDataNUnit.SetDescription(test.Description);375 foreach (var category in test.Categories)376 testCaseDataNUnit.SetCategory(CategoryHelper.Format(category));377 foreach (var property in test.Traits)378 testCaseDataNUnit.SetProperty(property.Name, property.Value);379380 //Assign instance categories and traits381 foreach (var category in instance.Categories)382 {383 var evaluatedCategory = scalarHelper.InstantiateResolver<string>(category).Execute();384 testCaseDataNUnit.SetCategory(CategoryHelper.Format(evaluatedCategory));385 }386387 foreach (var trait in instance.Traits)388 {389 var evaluatedTraitValue = scalarHelper.InstantiateResolver<string>(trait.Value).Execute();390 testCaseDataNUnit.SetProperty(trait.Key, evaluatedTraitValue);391 }392393 //Assign auto-categories394 if (EnableAutoCategories)395 {396 foreach (var system in test.Systems)397 foreach (var category in system.GetAutoCategories())398 testCaseDataNUnit.SetCategory(CategoryHelper.Format(category));399 }400 //Assign auto-categories401 if (EnableGroupAsCategory)402 {403 foreach (var groupName in test.GroupNames)404 testCaseDataNUnit.SetCategory(CategoryHelper.Format(groupName));405 }406407 testCases.Add(testCaseDataNUnit);408 }409 }410 return testCases;411 }412413 private IEnumerable<TestCaseData> BuildTestCases(IEnumerable<GroupXml> groups)414 {415 var testCases = new List<TestCaseData>();416417 foreach (var group in groups)418 {419 testCases.AddRange(BuildTestCases(group.Tests));420 testCases.AddRange(BuildTestCases(group.Groups));421 }422 return testCases;423 }424425 public void ApplyConfig(NBiSection config)426 {427 EnableAutoCategories = config.EnableAutoCategories;428 EnableGroupAsCategory = config.EnableGroupAsCategory;429 AllowDtdProcessing = config.AllowDtdProcessing;430 SettingsFilename = config.SettingsFilename;431432 var notableTypes = new Dictionary<Type, IDictionary<string, string>>();433 var analyzer = new ExtensionAnalyzer();434 foreach (ExtensionElement extension in config.Extensions)435 foreach (var type in analyzer.Execute(extension.Assembly))436 notableTypes.Add(type, extension.Parameters);437438 if (serviceLocator == null)439 Initialize();440441 var setupConfiguration = serviceLocator.GetConfiguration();442 setupConfiguration.LoadExtensions(notableTypes);443 setupConfiguration.LoadFailureReportProfile(config.FailureReportProfile);444 Configuration = setupConfiguration;445446 OverridenVariables = config.Variables.Cast<VariableElement>().ToDictionary(x => x.Name, y => new CasterFactory().Instantiate(y.Type).Execute(y.Value));447 }448449 450 public void Initialize()451 {452 Trace.WriteLineIf(NBiTraceSwitch.TraceInfo, $"Initializing service locator ...");453 var stopWatch = new Stopwatch();454 serviceLocator = new ServiceLocator();455 Trace.WriteLineIf(NBiTraceSwitch.TraceInfo, $"Service locator initialized in {stopWatch.Elapsed:d'.'hh':'mm':'ss'.'fff'ms'}");456457458 if (ConfigurationProvider != null)459 {460 Trace.WriteLineIf(NBiTraceSwitch.TraceError, string.Format("Loading configuration ..."));
...
SetupHelperTest.cs
Source:SetupHelperTest.cs
...21{22 public class SetupHelperTest23 {24 [Test]25 public void Execute_UniqueCommand_CorrectInterpretation()26 {27 var xml = new SetupXml()28 {29 Commands = new List<DecorationCommandXml>()30 { new FileDeleteXml() { FileName="foo.txt", Path = @"C:\Temp\" } }31 };32 var helper = new SetupHelper(new ServiceLocator(), new Dictionary<string, IVariable>());33 var listCommandArgs = helper.Execute(xml.Commands);34 Assert.That(listCommandArgs.Count(), Is.EqualTo(1));35 }36 [Test]37 public void Execute_MultipleCommands_CorrectInterpretation()38 {39 var xml = new SetupXml()40 {41 Commands = new List<DecorationCommandXml>()42 {43 new FileDeleteXml() { FileName="foo.txt", Path = @"C:\Temp\" },44 new ExeKillXml() { ProcessName="bar" },45 new WaitXml() { MilliSeconds = "2000" }46 }47 };48 var helper = new SetupHelper(new ServiceLocator(), new Dictionary<string, IVariable>());49 var listCommandArgs = helper.Execute(xml.Commands);50 Assert.That(listCommandArgs.Count(), Is.EqualTo(3));51 }52 [Test]53 [TestCase(typeof(SqlRunXml), typeof(IBatchRunCommandArgs))]54 [TestCase(typeof(TableLoadXml), typeof(ILoadCommandArgs))]55 [TestCase(typeof(TableResetXml), typeof(IResetCommandArgs))]56 [TestCase(typeof(EtlRunXml), typeof(IEtlRunCommandArgs))]57 [TestCase(typeof(ConnectionWaitXml), typeof(IConnectionWaitCommandArgs))]58 [TestCase(typeof(FileDeleteXml), typeof(IDeleteCommandArgs))]59 [TestCase(typeof(FileDeletePatternXml), typeof(IDeletePatternCommandArgs))]60 [TestCase(typeof(FileDeleteExtensionXml), typeof(IDeleteExtensionCommandArgs))]61 [TestCase(typeof(FileCopyXml), typeof(ICopyCommandArgs))]62 [TestCase(typeof(FileCopyPatternXml), typeof(ICopyPatternCommandArgs))]63 [TestCase(typeof(FileCopyExtensionXml), typeof(ICopyExtensionCommandArgs))]64 [TestCase(typeof(ExeKillXml), typeof(IKillCommandArgs))]65 [TestCase(typeof(ExeRunXml), typeof(IRunCommandArgs))]66 [TestCase(typeof(ServiceStartXml), typeof(IStartCommandArgs))]67 [TestCase(typeof(ServiceStopXml), typeof(IStopCommandArgs))]68 [TestCase(typeof(WaitXml), typeof(IWaitCommandArgs))]69 [TestCase(typeof(CustomCommandXml), typeof(ICustomCommandArgs))]70 public void Execute_DecorationCommand_CorrectlyTransformedToArgs(Type xmlType, Type argsType)71 {72 var xmlInstance = Activator.CreateInstance(xmlType);73 Assert.That(xmlInstance, Is.AssignableTo<DecorationCommandXml>());74 var xml = new SetupXml()75 {76 Commands = new List<DecorationCommandXml>()77 { xmlInstance as DecorationCommandXml }78 };79 var helper = new SetupHelper(new ServiceLocator(), new Dictionary<string, IVariable>());80 var commandArgs = helper.Execute(xml.Commands).ElementAt(0);81 Assert.That(commandArgs, Is.AssignableTo<IDecorationCommandArgs>());82 Assert.That(commandArgs, Is.AssignableTo(argsType));83 }84 [Test]85 [TestCase(true, typeof(IParallelCommandArgs))]86 [TestCase(false, typeof(ISequentialCommandArgs))]87 public void Execute_GroupCommand_CorrectlyTransformedToArgs(bool isParallel, Type argsType)88 {89 var xml = new SetupXml()90 {91 Commands = new List<DecorationCommandXml>()92 {93 new CommandGroupXml()94 {95 Parallel = isParallel,96 Commands = new List<DecorationCommandXml>()97 {98 new FileDeleteXml() { FileName="foo.txt", Path = @"C:\Temp\" },99 new ExeKillXml() { ProcessName = "bar.exe" }100 }101 }102 }103 };104 var helper = new SetupHelper(new ServiceLocator(), new Dictionary<string, IVariable>());105 var commandArgs = helper.Execute(xml.Commands).ElementAt(0);106 Assert.That(commandArgs, Is.AssignableTo(argsType));107 var groupCommandArgs = commandArgs as IGroupCommandArgs;108 Assert.That(groupCommandArgs.Commands.ElementAt(0), Is.AssignableTo<IDeleteCommandArgs>());109 Assert.That(groupCommandArgs.Commands.ElementAt(1), Is.AssignableTo<IKillCommandArgs>());110 }111 [Test]112 public void Execute_GroupsWithinGroupCommand_CorrectlyTransformedToArgs()113 {114 var xml = new SetupXml()115 {116 Commands = new List<DecorationCommandXml>()117 {118 new CommandGroupXml()119 {120 Parallel = false,121 Commands = new List<DecorationCommandXml>()122 {123 new CommandGroupXml()124 {125 Parallel = true,126 Commands = new List<DecorationCommandXml>()127 {128 new FileDeleteXml() { FileName="foo.txt", Path = @"C:\Temp\" },129 new ExeKillXml() { ProcessName = "foo.exe" }130 }131 },132 new CommandGroupXml()133 {134 Parallel = true,135 Commands = new List<DecorationCommandXml>()136 {137 new FileDeleteXml() { FileName="bar.txt", Path = @"C:\Temp\" },138 new ExeKillXml() { ProcessName = "bar.exe" }139 }140 }141 }142 }143 }144 };145 var helper = new SetupHelper(new ServiceLocator(), new Dictionary<string, IVariable>());146 var commandArgs = helper.Execute(xml.Commands).ElementAt(0);147 Assert.That(commandArgs, Is.AssignableTo<ISequentialCommandArgs>());148 var groupCommandArgs = commandArgs as IGroupCommandArgs;149 Assert.That(groupCommandArgs.Commands.ElementAt(0), Is.AssignableTo<IParallelCommandArgs>());150 Assert.That(groupCommandArgs.Commands.ElementAt(1), Is.AssignableTo<IParallelCommandArgs>());151 foreach (var subGroup in groupCommandArgs.Commands)152 {153 var subGroupCommandArgs = subGroup as IGroupCommandArgs;154 Assert.That(subGroupCommandArgs.Commands.ElementAt(0), Is.AssignableTo<IDeleteCommandArgs>());155 Assert.That(subGroupCommandArgs.Commands.ElementAt(1), Is.AssignableTo<IKillCommandArgs>());156 }157 }158 [Test]159 public void Execute_CustomCommand_CorrectlyParsed()160 {161 var xml = new SetupXml()162 {163 Commands = new List<DecorationCommandXml>()164 { new CustomCommandXml()165 {166 AssemblyPath ="NBi.Testing"167 , TypeName = @"CustomCommand"168 , Parameters = new List<CustomCommandParameterXml>()169 {170 new CustomCommandParameterXml() { Name="foo", StringValue="bar" },171 new CustomCommandParameterXml() { Name="quark", StringValue="@myVar" },172 }173 }174 }175 };176 var myVar = new GlobalVariable(new LiteralScalarResolver<object>("bar-foo"));177 var helper = new SetupHelper(new ServiceLocator(), new Dictionary<string, IVariable>() {{ "myVar", myVar } });178 var customCommandArgs = helper.Execute(xml.Commands).ElementAt(0) as ICustomCommandArgs;179 Assert.That(customCommandArgs.AssemblyPath, Is.TypeOf<LiteralScalarResolver<string>>());180 Assert.That(customCommandArgs.AssemblyPath.Execute(), Is.EqualTo("NBi.Testing"));181 Assert.That(customCommandArgs.TypeName, Is.TypeOf<LiteralScalarResolver<string>>());182 Assert.That(customCommandArgs.TypeName.Execute(), Is.EqualTo("CustomCommand"));183 Assert.That(customCommandArgs.Parameters, Has.Count.EqualTo(2));184 Assert.That(customCommandArgs.Parameters["foo"], Is.TypeOf<LiteralScalarResolver<object>>());185 var paramValue = customCommandArgs.Parameters["foo"] as LiteralScalarResolver<object>;186 Assert.That(paramValue.Execute(), Is.EqualTo("bar"));187 Assert.That(customCommandArgs.Parameters["quark"], Is.TypeOf<GlobalVariableScalarResolver<object>>());188 var paramValue2 = customCommandArgs.Parameters["quark"] as GlobalVariableScalarResolver<object>;189 Assert.That(paramValue2.Execute(), Is.EqualTo("bar-foo"));190 }191 [Test]192 public void Execute_LiteralArgument_CorrectlyParsed()193 {194 var xml = new SetupXml()195 {196 Commands = new List<DecorationCommandXml>()197 { new FileDeleteXml() { FileName="foo.txt", Path = @"C:\Temp\" } }198 };199 var helper = new SetupHelper(new ServiceLocator(), new Dictionary<string, IVariable>());200 var deleteCommandArgs = helper.Execute(xml.Commands).ElementAt(0) as IDeleteCommandArgs;201 Assert.That(deleteCommandArgs.Name, Is.TypeOf<LiteralScalarResolver<string>>());202 Assert.That(deleteCommandArgs.Name.Execute(), Is.EqualTo("foo.txt"));203 }204 [Test]205 public void Execute_VariableArgument_CorrectlyParsed()206 {207 var xml = new SetupXml()208 {209 Commands = new List<DecorationCommandXml>()210 { new FileDeleteXml() { FileName="@myvar", Path = @"C:\Temp\" } }211 };212 var myVar = new GlobalVariable(new LiteralScalarResolver<object>("bar.txt"));213 var helper = new SetupHelper(new ServiceLocator(), new Dictionary<string, IVariable>() { { "myvar", myVar } });214 var deleteCommandArgs = helper.Execute(xml.Commands).ElementAt(0) as IDeleteCommandArgs;215 Assert.That(deleteCommandArgs.Name, Is.TypeOf<GlobalVariableScalarResolver<string>>());216 Assert.That(deleteCommandArgs.Name.Execute(), Is.EqualTo("bar.txt"));217 }218 [Test]219 public void Execute_FormatArgument_CorrectlyParsed()220 {221 var xml = new SetupXml()222 {223 Commands = new List<DecorationCommandXml>()224 { new FileDeleteXml() { FileName="~{@myvar}.csv", Path = @"C:\Temp\" } }225 };226 var myVar = new GlobalVariable(new LiteralScalarResolver<object>("bar"));227 var helper = new SetupHelper(new ServiceLocator(), new Dictionary<string, IVariable>() { { "myvar", myVar } });228 var deleteCommandArgs = helper.Execute(xml.Commands).ElementAt(0) as IDeleteCommandArgs;229 Assert.That(deleteCommandArgs.Name, Is.TypeOf<FormatScalarResolver>());230 Assert.That(deleteCommandArgs.Name.Execute(), Is.EqualTo("bar.csv"));231 }232 [Test]233 public void Execute_InlineTransformationArgument_CorrectlyParsed()234 {235 var xml = new SetupXml()236 {237 Commands = new List<DecorationCommandXml>()238 { new FileDeleteXml() { FileName="@myvar | text-to-upper", Path = @"C:\Temp\" } }239 };240 var myVar = new GlobalVariable(new CSharpScalarResolver<object>(241 new CSharpScalarResolverArgs("\"foo.txt\"")242 ));243 var helper = new SetupHelper(new ServiceLocator(), new Dictionary<string, IVariable>() { { "myvar", myVar } });244 var deleteCommandArgs = helper.Execute(xml.Commands).ElementAt(0) as IDeleteCommandArgs;245 Assert.That(deleteCommandArgs.Name, Is.AssignableTo<IScalarResolver>());246 Assert.That(deleteCommandArgs.Name.Execute(), Is.EqualTo("FOO.TXT"));247 Assert.That(deleteCommandArgs.Name.Execute(), Is.Not.EqualTo("foo.txt"));248 }249 }250}...
Execute
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using NBi.NUnit.Builder.Helper;7{8 {9 static void Main(string[] args)10 {11 var setupHelper = new SetupHelper();12 setupHelper.Execute("select * from table", "connectionstring", "select * from table", "connectionstring");13 }14 }15}16NBi.NUnit.Builder.Helper.SetupHelper.Execute(String, String, String, String) => True17NBi.NUnit.Builder.Helper.SetupHelper.Execute(String, String, String, String) => False18using System;19using System.Collections.Generic;20using System.Linq;21using System.Text;22using System.Threading.Tasks;23using NBi.NUnit.Builder.Helper;24{25{26static void Main(string[] args)27{28var setupHelper = new SetupHelper();29setupHelper.Execute("select * from table", "connectionstring", "select * from table", "connectionstring");30}31}32}33using System;34using System.Collections.Generic;35using System.Linq;36using System.Text;37using System.Threading.Tasks;38using NBi.NUnit.Builder.Helper;39{40{41static void Main(string[] args)42{43var setupHelper = new SetupHelper();44setupHelper.Execute("select * from table", "connectionstring", "select * from table", "connectionstring");45}46}47}
Execute
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using NBi.NUnit.Builder.Helper;7{8 {9 static void Main(string[] args)10 {11 {12 SetupHelper setup = new SetupHelper();13 setup.Execute("SELECT * FROM [Adventure Works DW2012].[dbo].[DimCustomer]");14 }15 catch (Exception ex)16 {
Execute
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using NBi.NUnit.Builder.Helper;7using NBi.Xml.Constraints;8using NBi.Xml.Items;9using NBi.Xml.Systems;10using NUnit.Framework;11using NUnitCtr = NUnit.Framework.Constraints;12using NBi.Core.Query;13using NBi.Core.ResultSet;14using NBi.Core.ResultSet.Resolver;15using NBi.Core;16using NBi.Core.Injection;17using NBi.Core.Query.Resolver;18using NBi.Core.Query.Command;19using NBi.Core.Query.Client;20using NBi.Core.Query.Execution;21using NBi.Core.Scalar.Resolver;22using NBi.Core.Calculation;23using NBi.Core.Calculation.Predicate;24using NBi.Core.Calculation.Resolver;25using NBi.Core.Calculation.Grouping;
Execute
Using AI Code Generation
1using NBi.NUnit.Builder.Helper;2using NUnit.Framework;3using System;4using System.Collections.Generic;5using System.Linq;6using System.Text;7using System.Threading.Tasks;8{9 {10 public void Execute_QueryWithParameters_ReturnsCorrectResult()11 {12 var connectionString = "Data Source=.;Initial Catalog=AdventureWorks2012;Integrated Security=True;";13 var query = "select * from [SalesLT].[Product] where [ProductID] = @ID";14 var parameters = new Dictionary<string, object>();15 parameters.Add("ID", 1);16 var result = SetupHelper.Execute(connectionString, query, parameters);17 Assert.That(result.Rows.Count, Is.EqualTo(1));18 }19 }20}
Execute
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using System.Data;7using System.Data.SqlClient;8using System.IO;9using NBi.NUnit.Builder.Helper;10{11 {12 static void Main(string[] args)13 {14 string sqlScript = File.ReadAllText(@"D:\test.sql");15 SetupHelper.Execute(sqlScript);16 }17 }18}19using System;20using System.Collections.Generic;21using System.Linq;22using System.Text;23using System.Threading.Tasks;24using System.Data;25using System.Data.SqlClient;26using System.IO;27using NBi.NUnit.Builder.Helper;28{29 {30 static void Main(string[] args)31 {32 string sqlScript = File.ReadAllText(@"D:\test.sql");33 Dictionary<string, string> parameters = new Dictionary<string, string>();34 parameters.Add("@param1", "value1");35 parameters.Add("@param2", "value2");36 SetupHelper.Execute(sqlScript, parameters);37 }38 }39}40using System;41using System.Collections.Generic;42using System.Linq;43using System.Text;44using System.Threading.Tasks;45using System.Data;46using System.Data.SqlClient;47using System.IO;48using NBi.NUnit.Builder.Helper;49{50 {51 static void Main(string[] args)52 {53 string sqlScript = File.ReadAllText(@"D:\test.sql");54 Dictionary<string, string> parameters = new Dictionary<string, string>();55 parameters.Add("@param1", "value1");56 parameters.Add("@param2", "value2");57 SetupHelper.Execute(sqlScript, parameters, @"Data Source=.;Initial Catalog=Test;Integrated Security=True");58 }59 }60}61using System;62using System.Collections.Generic;63using System.Linq;64using System.Text;65using System.Threading.Tasks;66using System.Data;67using System.Data.SqlClient;68using System.IO;
Execute
Using AI Code Generation
1using NBi.NUnit.Builder.Helper;2using NUnit.Framework;3using System.Data;4{5{6public void Setup()7{8SetupHelper helper = new SetupHelper();9string connectionString = "Data Source=.;Initial Catalog=TestDB;Integrated Security=True";10string query = "SELECT * FROM TestTable";11DataSet ds = helper.Execute(connectionString, query);12Assert.AreEqual(2, ds.Tables[0].Rows.Count);13}14}15}16{17public void Setup()18{19SetupHelper helper = new SetupHelper();20string connectionString = "Data Source=.;Initial Catalog=TestDB;Integrated Security=True";21string query = "EXEC dbo.TestSP";22DataSet ds = helper.Execute(connectionString, query);23Assert.AreEqual(2, ds.Tables[0].Rows.Count);24}25}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!