Best NBi code snippet using NBi.Core.Variable.Instantiation.InstanceFactory.Instantiate
TestSuite.cs
Source:TestSuite.cs
...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 ..."));
...
InstanceFactoryTest.cs
Source:InstanceFactoryTest.cs
...14 public class InstanceFactoryTest15 {16 [Test]17 [Culture("en-us")]18 public void Instantiate_DerivedFromMain_Success()19 {20 var resolver = new Mock<ISequenceResolver>();21 resolver.Setup(x => x.Execute()).Returns(new[] { "BE_20190101", "BE_20190102", "BE_20190103", "BE_20190104", "BE_20190105" });22 var firstTransformation = new NativeTransformer<string>(new ServiceLocator(), null);;23 firstTransformation.Initialize("text-to-first-chars(2)");24 var secondTransformation = new NativeTransformer<string>(new ServiceLocator(), null);;25 secondTransformation.Initialize("text-to-last-chars(8) | text-to-dateTime(yyyyMMdd)");26 var thirdTransformation = new NativeTransformer<DateTime>(new ServiceLocator(), null);;27 thirdTransformation.Initialize("dateTime-to-add(7)");28 var args = new DerivedVariableInstanceArgs()29 {30 Name = "main",31 Resolver = resolver.Object,32 Derivations = new Dictionary<string, DerivationArgs>()33 {34 { "first", new DerivationArgs() { Source = "main", Transformer = firstTransformation } },35 { "second", new DerivationArgs() { Source = "main", Transformer = secondTransformation } },36 { "third", new DerivationArgs() { Source = "second", Transformer = thirdTransformation } }37 }38 };39 var factory = new InstanceFactory();40 var instances = factory.Instantiate(args);41 Assert.That(instances.Count, Is.EqualTo(5));42 Assert.That(instances.ElementAt(0).Variables.Count, Is.EqualTo(4));43 Assert.That(instances.ElementAt(0).Variables.ContainsKey("main"), Is.True);44 Assert.That(instances.ElementAt(0).Variables["main"].GetValue(), Is.EqualTo("BE_20190101"));45 Assert.That(instances.ElementAt(0).Variables.ContainsKey("first"), Is.True);46 Assert.That(instances.ElementAt(0).Variables["first"].GetValue(), Is.EqualTo("BE"));47 Assert.That(instances.ElementAt(0).Variables.ContainsKey("second"), Is.True);48 Assert.That(instances.ElementAt(0).Variables["second"].GetValue(), Is.EqualTo(new DateTime(2019, 1, 1)));49 Assert.That(instances.ElementAt(0).Variables.ContainsKey("third"), Is.True);50 Assert.That(instances.ElementAt(0).Variables["third"].GetValue(), Is.EqualTo(new DateTime(2019, 1, 8)));51 Assert.That(instances.ElementAt(1).Variables.Count, Is.EqualTo(4));52 Assert.That(instances.ElementAt(1).Variables.ContainsKey("main"), Is.True);53 Assert.That(instances.ElementAt(1).Variables["main"].GetValue(), Is.EqualTo("BE_20190102"));54 Assert.That(instances.ElementAt(1).Variables.ContainsKey("first"), Is.True);...
InstanceFactory.cs
Source:InstanceFactory.cs
...9namespace NBi.Core.Variable.Instantiation10{11 public class InstanceFactory12 {13 public IEnumerable<Instance> Instantiate(IInstanceArgs args)14 {15 switch (args)16 {17 case DefaultInstanceArgs _: return new[] { Instance.Default };18 case DerivedVariableInstanceArgs s: return Instantiate(s.Name, s.Resolver, s.Derivations, args.Categories, args.Traits);19 case SingleVariableInstanceArgs s: return Instantiate(s.Name, s.Resolver, args.Categories, args.Traits);20 default:21 throw new ArgumentOutOfRangeException();22 }23 }24 private IEnumerable<Instance> Instantiate(string variableName, ISequenceResolver resolver, IEnumerable<string> categories, IDictionary<string, string> traits)25 {26 foreach (var obj in resolver.Execute())27 {28 var instanceVariable = new InstanceVariable(obj);29 yield return new Instance(30 new Dictionary<string, IVariable>() { { variableName, instanceVariable } },31 categories,32 traits33 );34 }35 }36 private IEnumerable<Instance> Instantiate(string variableName, ISequenceResolver resolver, IDictionary<string, DerivationArgs> derivations, IEnumerable<string> categories, IDictionary<string, string> traits)37 {38 foreach (var obj in resolver.Execute())39 {40 var dico = new Dictionary<string, IVariable>() { { variableName, new InstanceVariable(obj) } };41 foreach (var derivation in derivations)42 dico.Add(derivation.Key, new InstanceVariable(derivation.Value.Transformer.Execute(dico[derivation.Value.Source].GetValue())));43 yield return new Instance(44 dico,45 categories,46 traits47 );48 }49 }50 }...
Instantiate
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using NBi.Core.Variable.Instantiation;7{8 {9 static void Main(string[] args)10 {11 var factory = new InstanceFactory();12 var instance = factory.Instantiate("1");13 Console.WriteLine(instance);14 Console.ReadLine();15 }16 }17}18using System;19using System.Collections.Generic;20using System.Linq;21using System.Text;22using System.Threading.Tasks;23using NBi.Core.Variable.Instantiation;24{25 {26 static void Main(string[] args)27 {28 var factory = new InstanceFactory();29 var instance = factory.Instantiate("2");30 Console.WriteLine(instance);31 Console.ReadLine();32 }33 }34}35using System;36using System.Collections.Generic;37using System.Linq;38using System.Text;39using System.Threading.Tasks;40using NBi.Core.Variable.Instantiation;41{42 {43 static void Main(string[] args)44 {45 var factory = new InstanceFactory();46 var instance = factory.Instantiate("3");47 Console.WriteLine(instance);48 Console.ReadLine();49 }50 }51}52using System;53using System.Collections.Generic;54using System.Linq;55using System.Text;56using System.Threading.Tasks;57using NBi.Core.Variable.Instantiation;58{59 {60 static void Main(string[] args)61 {62 var factory = new InstanceFactory();63 var instance = factory.Instantiate("4");64 Console.WriteLine(instance);65 Console.ReadLine();66 }67 }68}69using System;70using System.Collections.Generic;71using System.Linq;72using System.Text;73using System.Threading.Tasks;74using NBi.Core.Variable.Instantiation;75{76 {77 static void Main(string[] args)78 {79 var factory = new InstanceFactory();80 var instance = factory.Instantiate("5");81 Console.WriteLine(instance);82 Console.ReadLine();83 }84 }85}86using System;87using System.Collections.Generic;88using System.Linq;89using System.Text;90using System.Threading.Tasks;
Instantiate
Using AI Code Generation
1{2 public static void Main()3 {4 var factory = new InstanceFactory();5 var instance = factory.Instantiate("1");6 Console.WriteLine(instance);7 }8}9{10 public static void Main()11 {12 var factory = new InstanceFactory();13 var instance = factory.Instantiate("1");14 Console.WriteLine(instance);15 }16}17{18 public static void Main()19 {20 var factory = new InstanceFactory();21 var instance = factory.Instantiate("1");22 Console.WriteLine(instance);23 }24}25{26 public static void Main()27 {28 var factory = new InstanceFactory();29 var instance = factory.Instantiate("1");30 Console.WriteLine(instance);31 }32}33{34 public static void Main()35 {36 var factory = new InstanceFactory();37 var instance = factory.Instantiate("1");38 Console.WriteLine(instance);39 }40}41{42 public static void Main()43 {44 var factory = new InstanceFactory();45 var instance = factory.Instantiate("1");46 Console.WriteLine(instance);47 }48}49{50 public static void Main()51 {52 var factory = new InstanceFactory();53 var instance = factory.Instantiate("1");54 Console.WriteLine(instance);55 }56}57{58 public static void Main()59 {60 var factory = new InstanceFactory();61 var instance = factory.Instantiate("1");62 Console.WriteLine(instance);63 }64}
Instantiate
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using NBi.Core.Variable.Instantiation;7{8 {9 public MyClass()10 {11 var factory = new InstanceFactory();12 var instance = factory.Instantiate("NBi.Core.Variable.Instantiation.InstanceFactory");
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!!