private static void Main(string[] args) { var service = new EngineBuilder(options => { options.Warps = 10; options.RequestsPerWarp = 10; options.SlidingStep = TimeSpan.FromSeconds(1); options.SlidingRadius = 5; }) .LogTo(Logger) .ReceiveRequestsFrom(Transports) .ReadMetadataFrom(MetadataProviders) .Then(Steps) .Finally(builder => new CqrsStrategy(new BuiltInRequestTypeFinder(typeof(Program).Assembly)) { Dispatcher = new Dispatcher(new DemoServiceProvider(builder.GetLogger("Handlers"))), Formatter = JsonRequestContentFormatter.Default }) .BuildOrchestrator(); service.StartAsync(); Console.ReadKey(); service.StopAsync(TimeSpan.Zero).ConfigureAwait(false).GetAwaiter().GetResult(); }
private static Engine NoneMain() { var builder = new EngineBuilder(); Build(builder); return(builder.Build()); }
public void Test() { var kernel = new StandardKernel(); kernel.Bind <MyService>().ToSelf().InTransientScope(); kernel.Bind <IHandlerBase>().To <TestHandler>().InTransientScope(); var output = new TestOutput(); var engine = new EngineBuilder() .SetupHandlers(h => h.UseNinjectHandlerSource(kernel)) .SetupOutput(o => o.DoNotUseConsole().Add(output)) .SetupEnvironments(e => e.UseFactory(new MyEnvironmentFactory())) .SetupEvents(e => { e.EnvironmentChanged.Clear(); }) .Build(); kernel .Bind <MyEnvironment>() .ToMethod(c => (MyEnvironment)engine.Environments.Current) .InTransientScope(); engine.RunHeadless("A test"); output.Lines.Count.Should().Be(1); output.Lines[0].Should().Be("A"); }
public void ScriptInLimit_Test() { // Script with 4 commands. Loop limit of 4. Engine executes all 4 commands // without issue var output = new TestOutput(); var engine = new EngineBuilder() .SetupOutput(o => o.DoNotUseConsole().Add(output)) .SetupHandlers(h => h .UseHandlerTypes(typeof(EchoHandler), typeof(ExitHandler)) .AddScript("test", new[] { "echo 1", "echo 2", "echo 3", "echo 4" }) ) .SetupSettings(s => { s.MaxInputlessCommands = 4; }) .Build(); engine.RunHeadless("test"); output.Lines.Count.Should().Be(4); output.Lines[0].Should().Be("1"); output.Lines[1].Should().Be("2"); output.Lines[2].Should().Be("3"); output.Lines[3].Should().Be("4"); }
public async Task HrefJavaScriptOnClickOrder() { var signal = new AutoResetEvent(false); var console = new Mock <IConsole>(); var log = new ArrayList(); console.Setup(x => x.Log(It.IsAny <double>())).Callback <object[]>(x => { log.Add(x[0]); if (log.Count == 2) { signal.Set(); } }); var resourceProvider = Mocks.ResourceProvider("http://loc/", "<html><body><a id=a href='JavaScript:console.log(1)'><div id=d></div></a>" + "<script>var a = document.getElementById('a');" + "a.click();" + "console.log(2);</script></body></html>"); var engine = EngineBuilder.New() .SetResourceProvider(resourceProvider) .UseJint() .Window(w => w.SetConsole(console.Object)) .Build(); await engine.OpenUrl("http://loc/"); Assert.IsTrue(signal.WaitOne(1000), "Should be called"); Assert.AreEqual(new object[] { 2d, 1d }, log); }
public async Task NavigatorPlugins() { var plugins = new [] { new PluginInfo("Pdf reader", "Pdf document reader", "", "", new PluginMimeTypeInfo[] { new PluginMimeTypeInfo("application/pdf", "", "pdf") }), new PluginInfo("Video plugin", "", "", "", new PluginMimeTypeInfo[] { new PluginMimeTypeInfo("application/mpeg", "", "mpg"), new PluginMimeTypeInfo("application/avi", "", "avi"), }), }; var resourceProvider = Mocks.ResourceProvider("http://localhost", "<html><script>" + "console.log(navigator.mimeTypes.length);" + "console.log(navigator.plugins.length);" + "console.log(navigator.plugins[0].name);" + "console.log(navigator.plugins[0].length);" + "console.log(navigator.plugins[0][0].type)" + "</script></html>"); var engine = new EngineBuilder() .SetResourceProvider(resourceProvider) .UseJint() .Window(w => w.SetNavigatorPlugins(plugins)) .Build(); var log = engine.Console.ToList(); await engine.OpenUrl("http://localhost"); Assert.AreEqual(new object[] { 3, 2, "Pdf reader", 1, "application/pdf" }, log); }
public async Task DoAsync_ConsumesRequests_WhenRequestsAvailable() { var transport = new FakeTransport(100); var dispatcher = new FakeDispatcher(); var cqrs = new CqrsStrategy(new RequestTypeFinder(new[] { typeof(FakeCommand) })) { Dispatcher = dispatcher, Formatter = new JsonRequestContentFormatter() }; var orchestrator = new EngineBuilder(options => { options.Warps = 5; options.RequestsPerWarp = 5; options.RunRequestsInWarpAllAtOnce = true; options.SlidingStep = TimeSpan.FromMilliseconds(10); }) .ReceiveRequestsFrom(r => r.Add(transport)) .Finally(cqrs) .BuildOrchestrator(); await orchestrator.StartAsync(); var completed = await transport.Complete(); await orchestrator.StopAsync(TimeSpan.Zero); Assert.Equal(100, dispatcher.CallCounter); Assert.Equal(100, completed); }
public async Task Engine_With_Multiple_Compiler_And_Streaming_Mode_Should_Match_Patterns() { var loggerProvider = new XunitLoggerProvider(_testOutputHelper); var engineBuilder = new EngineBuilder(); engineBuilder.WithLogger(loggerProvider.CreateLogger("Hyperscan")); engineBuilder.WithDatabase(() => new Database()); engineBuilder.WithCompiler(() => new MultipleCompiler(new List <Expression> { new Expression("foo(?i)bar(?-i)baz", ExpressionFlag.HsFlagSomLeftmost), new Expression("foo", ExpressionFlag.HsFlagSomLeftmost), new Expression("foo(?i)bar", ExpressionFlag.HsFlagSomLeftmost) }, CompilerMode.HsModeStream | CompilerMode.HsModeSomHorizonLarge)); await using var engine = engineBuilder.Build(); var observer = new TestScheduler().CreateObserver <Match>(); using var onMatch = engine.OnMatch.Subscribe(observer); await engine.ScanAsync("fo", CancellationToken.None); await engine.ScanAsync("o", CancellationToken.None); await engine.ScanAsync("fo", CancellationToken.None); await engine.ScanAsync("o", CancellationToken.None); await engine.ScanAsync("barbazbaz", CancellationToken.None); await Task.Delay(100); observer.Messages.Count.Should().Be(4); observer.Messages.Should().Contain(message => message.Value.Value.FullMatch == "foo"); observer.Messages.Should().Contain(message => message.Value.Value.FullMatch == "foobar"); observer.Messages.Should().Contain(message => message.Value.Value.FullMatch == "foobarbaz"); }
public void CutOffScript_Test() { // Script with 4 commands. Loop limit of 2. Engine executes 2 commands and // then terminates with an error message var output = new TestOutput(); var engine = new EngineBuilder() .SetupOutput(o => o.DoNotUseConsole().Add(output)) .SetupHandlers(h => h .UseHandlerTypes(typeof(EchoHandler), typeof(ExitHandler)) .AddScript("test", new[] { "echo 1", "echo 2", "echo 3", "echo 4" }) ) .SetupSettings(s => { s.MaxInputlessCommands = 2; }) .Build(); engine.RunHeadless("test"); output.Lines.Count.Should().Be(3); output.Lines[0].Should().Be("1"); output.Lines[1].Should().Be("2"); output.Lines[2].Should().StartWith("Maximum"); }
static void Main(string[] args) { using var engine = new EngineBuilder() .WithReferenceTypes(true) .Build(); using var module = Module.FromFile(engine, "./zig/zig-cache/lib/zig.wasm"); using var host = new Host(engine); using var hFun = host.DefineFunction( "env", "hello", () => Console.WriteLine("Hello from C#!") ); using var prFun = host.DefineFunction( "env", "print", (Caller caller, int str_ptr) => { var str = caller.GetMemory("memory").ReadNullTerminatedString(str_ptr); Console.WriteLine(str); } ); using dynamic instance = host.Instantiate(module); Console.WriteLine($"1 + 2 = {instance.add(1, 2)} according to Zig"); }
public async Task MapsToCommand() { //Arrange var cfg = Config.Reset(); cfg.UseInMemoryFileSystem(); var settings = Config.Current.GetSettings <EngineSettings>(); var storageProvider = cfg.GetStorageProvider(); var builder = new EngineBuilder(); var engine = builder.Build <ITestModel>().Result; var client = new LocalClient <ITestModel>(engine); var proxy = client.GetDispatchProxy(); //Act proxy.SetCustomer(new Customer()); //release the lock on the journal await engine.DisposeAsync(); var journalEntry = storageProvider.CreateJournalReader().GetRecords().FirstOrDefault(); // If MapTo is correct, a SetCustomerCommand will be written to the journal // if not, then a ProxyCommand will be written Assert.NotNull(journalEntry); Assert.IsInstanceOf <SetCustomerCommand>(journalEntry.Command); }
public async Task HrefJavaScriptOnClickPrevent() { var signal = new AutoResetEvent(false); var console = new Mock <IConsole>(); console.Setup(x => x.Log(1d)).Callback(() => signal.Set()); var resourceProvider = Mocks.ResourceProvider("http://loc/", "<html><body><a id=a href='JavaScript:console.log(1)'><div id=d></div></a></body></html>"); var engine = EngineBuilder.New() .SetResourceProvider(resourceProvider) .UseJint() .Window(w => w.SetConsole(console.Object)) .Build(); var page = await engine.OpenUrl("http://loc/"); var a = (HtmlAnchorElement)page.Document.GetElementById("a"); a.OnClick += evt => { evt.PreventDefault(); return(true); }; a.Click(); Assert.IsFalse(signal.WaitOne(1000), "Should not be called"); }
public void Ajax() { var resourceProvider = Mock.Of <IResourceProvider>().Resource("http://localhost/unicorn.xml", "hello"); string responseText = null; var engine = EngineBuilder.New() .SetResourceProvider(resourceProvider) .UseJint() .Build(); var client = new XmlHttpRequest(engine.ResourceProvider, () => this, engine.Document, (u, m) => engine.CreateRequest(u, m)); client.OnReadyStateChange += () => { if (client.ReadyState == XmlHttpRequest.DONE) { if (client.Status == 200) { responseText = client.ResponseText; } } }; client.Open("GET", "http://localhost/unicorn.xml", false); client.Send(); Mock.Get(resourceProvider).Verify(x => x.SendRequestAsync(It.IsAny <Request>()), Times.Once()); Assert.AreEqual("hello", responseText); }
public void Post() { var resourceProvider = Mock.Of <IResourceProvider>() .Resource("http://localhost", "<html><head><script> " + R.JQueryJs + " </script><script src='test.js' defer/></head><body><div id='uca'></div></body></html>") .Resource("http://localhost/test.js", "$.post('http://localhost/data').done(function(x){console.log(x);});") .Resource("http://localhost/data", "OK"); var engine = EngineBuilder.New().SetResourceProvider(resourceProvider).UseJint().Build(); var log = new List <string>(); var signal = new ManualResetEvent(false); engine.Console.OnLog += o => { System.Console.WriteLine(o ?? "<null>"); log.Add(o.ToString()); signal.Set(); }; engine.OpenUrl("http://localhost"); Assert.IsTrue(signal.WaitOne(10000)); CollectionAssert.AreEqual(new[] { "OK" }, log); }
public void Database_Not_Configured_With_Engine_Builder_Should_Throw_Exception() { var engineBuilder = new EngineBuilder(); engineBuilder.WithCompiler(() => new SimpleCompiler(new Expression("", ExpressionFlag.HsFlagAllowempty), CompilerMode.HsModeBlock)); FluentActions.Invoking(() => engineBuilder.Build()).Should().Throw <HyperscanException>(); }
public static void Main(string[] args) { var engineBuilder = new EngineBuilder() // I don't know if using a property is nicer than a getter method, but here it is. .WindowOptions .Name("Game Window") .Width(1024) .Height(768) .Flags(WindowFlags.Titlebar | WindowFlags.Resize | WindowFlags.Close) // Calling the End{Section} method lets you keep using the builder fluently .EndWindowOptions(); // Can use the builder without the End{Section} methods if you want engineBuilder.Systems // Just a hacky hack to display registering an instance of something to be injected .Register(new Rectangle2D()) // Registering systems by type .Register <MyInitSystem>() .Register <MyUpdateSystem>() .Register <MyDrawSystem>() .Register <DebugTextHandler>(); // Build the engine, finalizing the DI container and all that jazz. Everything else remains the same using var engine = engineBuilder.Build(); engine.EntityManager.Add(new Hero()); var text = engine.EntityManager.CreateEntity("Debug Info"); text.AddComponent(new TextComponent(new Text("Elapsed Time: 0.00"))); engine.Run(); }
public static void Run(JsEngines engineType, string testName, [CallerMemberName] string fixture = null) { var builder = new EngineBuilder().SetResourceProvider(new TestingResourceProvider()); switch (engineType) { case JsEngines.Jurassic: builder.UseJurassic(); break; case JsEngines.Jint: builder.UseJint(); break; } var engine = builder.Build(); engine.OpenUrl($"http://test/{fixture}").Wait(); object res; lock (engine.Document) { res = engine.ScriptExecutor.Evaluate("text/javascript", @"Run('" + fixture + "', '" + testName + "');"); } if (res != null) { Assert.Fail(res.ToString()); } }
public void CallSaveDailyIntake_WhenInputIsCorrect() { var jsonSerializerMock = new Mock <IJsonSerializer>(); var dailyIntakeMock = new Mock <IDailyIntake>(); jsonSerializerMock.Setup(x => x.GetDailyIntake()).Returns(dailyIntakeMock.Object); var goalFactoryMock = new Mock <IGoalFactory>(); var startingWeight = (double)68; var goalWeight = (double)80; var height = (double)178; var age = 21; var gender = GenderType.male; var goalType = GoalType.gainweight; var activityLevel = ActivityLevel.moderate; var goalMock = new Mock <IGoal>(); goalFactoryMock .Setup(x => x.CreateGoal(startingWeight, goalWeight, height, age, gender, goalType, activityLevel)) .Returns(goalMock.Object); var args = new object[] { startingWeight, goalWeight, height, age, gender, goalType, activityLevel }; var engine = new EngineBuilder().WithJsonSerializer(jsonSerializerMock.Object) .WithGoalFactory(goalFactoryMock.Object).Build(); engine.SetGoalCommand.Execute(args); jsonSerializerMock.Verify(x => x.SaveDailyIntake(dailyIntakeMock.Object), Times.Once); }
public static ServiceRegistry SetupEngineScannerless(ServiceRegistry services, Action <IEngineBuilder> build) { EngineBuilder.SetupEngineRegistrations(services, build); services.AddSingleton <IHandlerSource>(provider => new LamarHandlerSource(provider, TypeVerbExtractor.DefaultInstance)); return(services); }
public async Task HrefJavaScriptOnClickOrder() { var signal = new AutoResetEvent(false); var console = new TestingConsole(); console.OnLog += x => { if (console.LogHistory.Count == 2) { signal.Set(); } }; var resourceProvider = Mocks.ResourceProvider("http://loc/", "<html><body><a id=a href='JavaScript:console.log(1)'><div id=d></div></a>" + "<script>var a = document.getElementById('a');" + "a.click();" + "console.log(2);</script></body></html>"); var engine = EngineBuilder.New() .SetResourceProvider(resourceProvider) .UseJint() .Window(w => w.SetConsole(console)) .Build(); await engine.OpenUrl("http://loc/"); signal.WaitOne(5000); Assert.AreEqual(new object[] { 2d, 1d }, console.LogHistory); }
public void Html5Score() { var engine = EngineBuilder.New().UseJint().Build(); engine.OpenUrl("https://html5test.com").Wait(timeout); var tagWithValue = engine.WaitSelector("#score strong").FirstOrDefault(); Assert.IsNotNull(tagWithValue, "strong"); System.Console.WriteLine("Score: " + tagWithValue.InnerHTML); Thread.Sleep(500); foreach (var category in ("parsing elements form location output input communication " + "interaction performance security offline " + "storage files streams video audio responsive " + "canvas animation components scripting other").Split(' ')) { var headerRow = engine.Document.WaitId($"head-{category}"); if (headerRow == null) { System.Console.WriteLine($"Header of {category} not found"); continue; } var scoreElement = engine.WaitSelector($"#head-{category} span").FirstOrDefault(); if (scoreElement == null) { System.Console.WriteLine($"Score of {category} category not found."); continue; } System.Console.WriteLine(category + ": " + scoreElement.InnerHTML); } }
public async Task Start(string[] arguments) { Settings = new MemstateSettings(arguments); Settings.WithRandomSuffixAppendedToStreamName(); Settings.LoggerFactory.AddConsole((category, level) => level > LogLevel.Debug); Logger = Settings.CreateLogger <Benchmark>(); Engine = new EngineBuilder(Settings).Build <KeyValueStore <int> >(); var totals = new List <TimeSpan>(Runs); for (var run = 0; run < Runs; run++) { Logger.LogInformation($"Run {run + 1}"); var stopwatch = Stopwatch.StartNew(); await Run(); stopwatch.Stop(); totals.Add(stopwatch.Elapsed); await Total(stopwatch.Elapsed); } await Engine.DisposeAsync(); await Totals(totals); Done?.Invoke(this, EventArgs.Empty); }
public void PreloadResourceUsingPredictedResourceProvider() { var prerequests = new List <Request>(); var index = "<html><head><script src='test.js'/>"; var script = "console.log('hi')"; var resourceProvider = Mock.Of <IPredictedResourceProvider>(); Mock.Get(resourceProvider).Setup(x => x.SendRequestAsync(It.IsAny <Request>())) .Returns <Request>(req => Task.Run(() => req.Url.ToString() == "http://localhost/" ? new Response("text/html", new MemoryStream(Encoding.UTF8.GetBytes(index))) : req.Url.ToString() == "http://localhost/test.js" ? new Response("text/html", new MemoryStream(Encoding.UTF8.GetBytes(script))) : (IResource)null)); Mock.Get(resourceProvider).Setup(x => x.Preload(It.IsAny <Request>())).Callback <Request>(req => prerequests.Add(req)); var engine = EngineBuilder.New().SetResourceProvider(resourceProvider).Build(); engine.OpenUrl("http://localhost").Wait(); Assert.AreEqual(1, prerequests.Count); Assert.Greater(prerequests[0].Headers.Count, 0); }
public void ScriptCutOff_y() { // Script with 4 commands, loop limit of 2. User enters "y" at the prompt to // continue. The loop continues and executes all commands var output = new TestOutput("test", "y"); var engine = new EngineBuilder() .SetupOutput(o => o.DoNotUseConsole().Add(output)) .SetupHandlers(h => h .UseHandlerTypes(typeof(EchoHandler)) .AddScript("test", new[] { "echo 1", "echo 2", "echo 3", "echo 4" }) ) .SetupSettings(s => { s.MaxInputlessCommands = 2; }) .SetupEvents(c => { c.EngineStartInteractive.Clear(); //c.EngineStopInteractive.Clear(); }) .Build(); engine.RunInteractively(); output.Lines.Count.Should().Be(4); output.Lines[0].Should().Be("1"); output.Lines[1].Should().Be("2"); output.Lines[2].Should().Be("3"); output.Lines[3].Should().Be("4"); }
public async Task Smoke(MemstateSettings settings) { const int NumRecords = 100; settings.LoggerFactory.AddProvider(new TestOutputLoggingProvider(_log)); settings.StreamName = _randomStreamName; var builder = new EngineBuilder(settings); var engine = builder.Build <List <string> >(); foreach (var number in Enumerable.Range(1, NumRecords)) { var command = new AddStringCommand(number.ToString()); var count = await engine.ExecuteAsync(command).ConfigureAwait(false); Assert.Equal(number, count); } await engine.DisposeAsync().ConfigureAwait(false); engine = builder.Build <List <string> >(); var strings = await engine.ExecuteAsync(new GetStringsQuery()).ConfigureAwait(false); Assert.Equal(NumRecords, strings.Count); await engine.DisposeAsync().ConfigureAwait(false); }
public void Compiler_Not_Configured_With_Engine_Builder_Should_Throw_Exception() { var engineBuilder = new EngineBuilder(); engineBuilder.WithDatabase(() => new Database()); FluentActions.Invoking(() => engineBuilder.Build()).Should().Throw <HyperscanException>(); }
public static ServiceRegistry SetupEngineScannerless <TEnvironment>(ServiceRegistry services, Action <IEngineBuilder> build) where TEnvironment : class { SetupEngineScannerless(services, build); EngineBuilder.SetupExplicitEnvironmentRegistration <TEnvironment>(services); return(services); }
public static CleeEngine Create(Action <IEngineConfiguration> configure) { var builder = new EngineBuilder(); configure(builder); return(builder.Build()); }
private static MemstateServer <T> CreateServer <T>(MemstateSettings settings, T model) where T : class { var engine = new EngineBuilder(settings).Build(model); var server = new MemstateServer <T>(settings, engine); return(server); }
public ProxyOverloadingTests() { var settings = new MemstateSettings().WithInmemoryStorage(); var storageProvider = settings.CreateStorageProvider(); var engine = new EngineBuilder(settings, storageProvider).Build <ModelWithOverloads>(); var client = new LocalClient <ModelWithOverloads>(engine); _db = client.GetDispatchProxy(); }
public EngineBuilder<MotorCycleBuilder> HasEngine() { this.engine = new EngineBuilder<MotorCycleBuilder>(this); return engine; }
public EngineBuilder Configure(EngineBuilder builder) { builder.AddRule(_rule); return builder; }
public EngineBuilder<CarBuilder> HasEngine() { this.engineBuilder = new EngineBuilder<CarBuilder>(this); return engineBuilder; }