Inheritance: MonoBehaviour
 public void CloneWithDefaults()
 {
     var settings = new TestSettings();
     var clonedSettings = settings.Clone();
     Assert.Null(clonedSettings.CallSettings);
     Assert.Null(clonedSettings.Clock);
     Assert.Equal(settings.UserAgent, clonedSettings.UserAgent);
 }
Ejemplo n.º 2
0
        public void TestInflator()
        {
            var handler = new EasySettingsHandler();
            var testSettings = new TestSettings();
            var result = handler.InflateSettingsViewModel(new SettingsClassHelper(testSettings));

            Assert.AreEqual(5, result.Count());

            //TODO: assure the viewmodel are the same
        }
        public void Bob()
        {
            var settings = new TestSettings();
            settings.Bob = "dru";
            settings.Environment = "PROD";
            HUB.Settings = settings;
            _proto = new ProtoCopyFileTask(new DotNetPath(), "C:\\from\\here");
            _proto.ToDirectory("C:\\to\\there\\{{Environment}}");
            _serv = new DeploymentServer("bob");

            _proto.RegisterRealTasks(_serv);
        }
        public void MethodArgumentsTest()
        {
            var provider = new SettingsProvider();
            var settings = new TestSettings() { Test = "Test1" };

            AssertHelper.ExpectedException<ArgumentNullException>(() => provider.SaveSettings(testSettingsPath, null));
            AssertHelper.ExpectedException<ArgumentException>(() => provider.SaveSettings(null, settings));
            AssertHelper.ExpectedException<ArgumentException>(() => provider.SaveSettings("MockSettings.xml", settings));

            AssertHelper.ExpectedException<ArgumentException>(() => provider.LoadSettings<TestSettings>(null));
            AssertHelper.ExpectedException<ArgumentException>(() => provider.LoadSettings<TestSettings>("MockSettings.xml"));
        }
Ejemplo n.º 5
0
        public void ShareKcy()
        {
            var settings = new TestSettings();

            var kcyConnector = new KarmakracyConnector(settings);
            var keyExtractor = new KeyWordExtractor();

            var kcyService = new KarmakracyService(kcyConnector, keyExtractor);

            string kcy = kcyService.Short("http://www.katayunos.com");

            kcyService.Share("Hola Katayuners", kcy);
        }
        public void Test_SettingsBase()
        {
            string directoryPath = "Test_SettingsBase";

            TestSettings testSettings = new TestSettings();
            testSettings.Text = "test";
            testSettings.Save(directoryPath);
            testSettings.Text = "";
            testSettings.Load(directoryPath);

            Assert.AreEqual(testSettings.Text, "test", "SettingsBase");

            Directory.Delete("Test_SettingsBase", true);
        }
Ejemplo n.º 7
0
        private static string GetKey(string propertyName, string attributeMemberName)
        {
            var test = new TestSettings();
            var defaultProperty = test.GetType().GetProperty(propertyName);
            var appSettingAttribute = defaultProperty.CustomAttributes
                .Where(a => a.AttributeType == typeof(AppSettingAttribute))
                .FirstOrDefault();
            var nameArgument = appSettingAttribute.NamedArguments
                .Where(arg => arg.MemberName == attributeMemberName)
                .FirstOrDefault();

            return nameArgument.TypedValue.Value != null ?
                nameArgument.TypedValue.Value.ToString() :
                null;
        }
        public void BasicSaveAndLoadTest()
        {
            var provider = new SettingsProvider();

            var defaultSettings = provider.LoadSettings<TestSettings>(testSettingsPath);
            Assert.AreEqual("Default", defaultSettings.Test);

            var settings1 = new TestSettings() { Test = "Test1" };
            provider.SaveSettings(testSettingsPath, settings1);

            var settings2 = provider.LoadSettings<TestSettings>(testSettingsPath);

            Assert.AreNotEqual(settings1, settings2);
            Assert.AreEqual(settings1.Test, settings2.Test);
        }
        protected listener_test_base(
            TestSettings settings = null)
        {
            Settings = settings ?? new TestSettings();

            var ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            _ipAddress = ipHostInfo.AddressList[1];

            _manager = new BufferManager(Settings.MaxConnections, Settings.BufferSize);
            var workerFactory = new WorkerManager(_manager, Settings.Timeout, null);

            _listener = new Listener(
                new ListenerSettings(_ipAddress, ++_port),
                s => workerFactory.Get(new WorkerSocket(s)));
            _listener.Start();
        }
 public void Clone()
 {
     var clock = new Mock<IClock>();
     var callSettings = new CallSettings(new CancellationTokenSource().Token, null, null, null, null, null);
     var settings = new TestSettings
     {
         CallSettings = callSettings,
         Clock = clock.Object,
     };
     var clonedSettings = settings.Clone();
     Assert.NotSame(settings, clonedSettings);
     // CallSettings is immutable, so just a reference copy is fine.
     Assert.Same(callSettings, clonedSettings.CallSettings);
     Assert.Equal(settings.UserAgent, clonedSettings.UserAgent);
     Assert.Equal(clock.Object, clonedSettings.Clock);
 }
Ejemplo n.º 11
0
        public ClientResult(int allBalls, int clientBalls, TestSettings settings)
        {
            this.ClientBalls = clientBalls;
            this.AllBalls = allBalls;

            this.Percent = ((float)this.ClientBalls)/((float)this.AllBalls) * 100;

            if (this.Percent >= 0 && this.Percent < (float)settings.Min3) { this.Mark = 2; }
            if (this.Percent >= (float)settings.Min3 && this.Percent < (float)settings.Min4) { this.Mark = 3; }
            if (this.Percent >= (float)settings.Min4 && this.Percent < (float)settings.Min5) { this.Mark = 4; }
            if (this.Percent >= (float)settings.Min5 && this.Percent <= 100) { this.Mark = 5; }
            if (this.Percent > 100)
            {
                this.Mark = 5;
            }
        }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            var handled = false;
            var showHelp = false;

            var settings = new TestSettings();

            var p = new OptionSet
                        {
                            { "u|url=", "Url to generate results from", value => { handled = true; settings.Url = value; } },
                            { "l|location=", "Location to run tests from [optional]", value => { settings.TestLocation = value; } },
                            { "b|browser=", "Browser to test with (Default=chrome) [optional]", value => { settings.Browser = value; } },
                            { "s|speed=", "Connections speed [optional]", value => { settings.Speed = value; } },
                            { "p|private", "Keep test results private [optional]", _ => { settings.IsPrivate = true; } },
                            { "t|timeout=", "Timeout, in seconds, while waiting for results (Default=300) [optional]", (int value) => { settings.Timeout = value; } },
                            { "username="******"Username for HTTP Basic Authentication [optional]", value => { settings.Username = value; } },
                            { "password="******"Password for HTTP Basic Authentication [optional]", value => { settings.Password = value; } },
                            { "prefix=", "Prefix to use for metric names [optional]", value => { handled = true; settings.Prefix = value; } },
                            { "h|?|help", "Show this message", x => showHelp = true }
                        };
            try
            {
                p.Parse(args);

                if (!handled || showHelp)
                {
                    Console.WriteLine("Usage: WebpageTestReporter [OPTIONS]");
                    Console.WriteLine("Options:");
                    p.WriteOptionDescriptions(Console.Out);
                }
                else
                {
                    RunPageTest(settings);
                }
            }
            catch (OptionException ex)
            {
                Console.Write("Error: ");
                Console.WriteLine(ex.Message);
                Console.WriteLine("Try 'WebpageTestReporter --help' for more information.");
            }
        }
Ejemplo n.º 13
0
        public void Can_List_Fingerprint_Templates()
        {
            using (var client = TestSettings.Connect())
                using (var p = client.Terminal.Programming())
                {
                    // Arrange
                    p.Fingerprint.DeleteAllTemplates();
                    p.Fingerprint.PutTemplate(1, TestTemplate.Data);
                    p.Fingerprint.PutTemplate(1, TestTemplate.Data);
                    p.Fingerprint.PutTemplate(2, TestTemplate.Data);

                    // Act
                    var list = p.Fingerprint.ListTemplates();

                    // Assert
                    Assert.AreEqual(2, list.Count);
                    Assert.IsTrue(list.ContainsKey(1));
                    Assert.IsTrue(list.ContainsKey(2));
                    Assert.AreEqual(2, list[1]);
                    Assert.AreEqual(1, list[2]);
                }
        }
    public async Task OnRedirectToIdentityProviderEventCanSetState(string userState)
    {
        var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider(NullLoggerFactory.Instance).CreateProtector("OIDCTest"));
        var settings    = new TestSettings(opt =>
        {
            opt.StateDataFormat = stateFormat;
            opt.ClientId        = "Test Id";
            opt.Authority       = TestServerBuilder.DefaultAuthority;
            opt.Events          = new OpenIdConnectEvents()
            {
                OnRedirectToIdentityProvider = context =>
                {
                    context.ProtocolMessage.State = userState;
                    return(Task.FromResult(0));
                }
            };
        });

        var server      = settings.CreateTestServer();
        var transaction = await server.SendAsync(ChallengeEndpoint);

        var res = transaction.Response;

        Assert.Equal(HttpStatusCode.Redirect, res.StatusCode);
        Assert.NotNull(res.Headers.Location);

        var values           = settings.ValidateChallengeRedirect(res.Headers.Location);
        var actualState      = values[OpenIdConnectParameterNames.State];
        var actualProperties = stateFormat.Unprotect(actualState);

        if (userState != null)
        {
            Assert.Equal(userState, actualProperties.Items[OpenIdConnectDefaults.UserstatePropertiesKey]);
        }
        else
        {
            Assert.False(actualProperties.Items.ContainsKey(OpenIdConnectDefaults.UserstatePropertiesKey));
        }
    }
    public async Task OnRedirectToIdentityProviderEventCanReplaceValues()
    {
        var newClientId = Guid.NewGuid().ToString();

        var settings = new TestSettings(
            opts =>
        {
            opts.ClientId  = "Test Id";
            opts.Authority = TestServerBuilder.DefaultAuthority;
            opts.Events    = new OpenIdConnectEvents()
            {
                OnRedirectToIdentityProvider = context =>
                {
                    context.ProtocolMessage.ClientId = newClientId;
                    return(Task.FromResult(0));
                }
            };
        }
            );

        var server      = settings.CreateTestServer();
        var transaction = await server.SendAsync(ChallengeEndpoint);

        var res = transaction.Response;

        Assert.Equal(HttpStatusCode.Redirect, res.StatusCode);
        Assert.NotNull(res.Headers.Location);

        settings.ValidateChallengeRedirect(
            res.Headers.Location,
            OpenIdConnectParameterNames.ResponseType,
            OpenIdConnectParameterNames.ResponseMode,
            OpenIdConnectParameterNames.Scope,
            OpenIdConnectParameterNames.RedirectUri);

        var actual = res.Headers.Location.Query.Trim('?').Split('&').Single(seg => seg.StartsWith($"{OpenIdConnectParameterNames.ClientId}=", StringComparison.Ordinal));

        Assert.Equal($"{OpenIdConnectParameterNames.ClientId}={newClientId}", actual);
    }
Ejemplo n.º 16
0
        public async void MakeRequestForFitbitIntradayHeartRate()
        {
            var credentials = TestSettings.GetToken <Fitbit, OAuth2Credentials>();

            if (credentials.IsTokenExpired)
            {
                throw new Exception("Expired credentials!!!");
            }

            var request = new FitbitIntradayHeartRate()
            {
                Startdate = DateTime.Today,
                Enddate   = DateTime.Today,
                Starttime = DateTime.Now.Subtract(TimeSpan.FromHours(5)),
                Endtime   = DateTime.Now
            };
            var response = await new OAuthRequester(credentials)
                           .MakeOAuthRequestAsync <FitbitIntradayHeartRate, string>(request)
                           .ConfigureAwait(false);

            Assert.NotNull(response);
        }
        public void CanCrawlPopulatedTableWithEventTable()
        {
            var settings = new TestSettings();

            var db = new TestDatabase(settings, new PopulatedTable(), new PopulatedEventTable());

            db.Setup();
            try
            {
                var connector = CreateConnector();
                connector.ResetConnector("CrawlPopulatedTableWithEventTable");
                var configuration = GetTestConfiguration(
                    "CrawlPopulatedTableWithEventTable",
                    settings.TestSqlDatabaseConnection.ToString(),
                    PopulatedTable.TableName,
                    new List <TableDetail>(),
                    new List <EventTable>()
                {
                    new EventTable()
                    {
                        EventSequenceColumnName = "Id",
                        MainTableIdColumnName   = "Name",
                        EventTypeColumnName     = PopulatedEventTable.EventTypeColumnName,
                        DeleteEventTypeValue    = "delete",
                        TableName = PopulatedEventTable.TableName
                    }
                });
                var sourceChanges = connector.ExecuteFetch(configuration);
                sourceChanges.Adds.Count.Should().Be(2);

                sourceChanges = connector.ExecuteFetch(configuration);
                sourceChanges.Adds.Count.Should().Be(0);
                sourceChanges.Deletes.Count.Should().Be(0);
            }
            finally
            {
                db.Destroy();
            }
        }
        public void UCITestUpdateActiveOpportunity()
        {
            var client = new WebClient(TestSettings.Options);

            using (var xrmApp = new XrmApp(client))
            {
                xrmApp.OnlineLogin.Login(_xrmUri, _username, _password, _mfaSecretKey);

                xrmApp.Navigation.OpenApp(UCIAppName.Sales);

                xrmApp.Navigation.OpenSubArea("Sales", "Opportunities");

                xrmApp.Grid.SwitchView("Open Opportunities");

                xrmApp.Grid.OpenRecord(0);
                xrmApp.ThinkTime(3000);

                xrmApp.Entity.SetValue("name", TestSettings.GetRandomString(10, 15));

                xrmApp.Entity.Save();
            }
        }
Ejemplo n.º 19
0
    public async Task RemoteSignOut_WithInvalidIssuer()
    {
        var settings = new TestSettings(o =>
        {
            o.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            o.Authority    = TestServerBuilder.DefaultAuthority;
            o.ClientId     = "Test Id";
        });
        var server = settings.CreateTestServer(handler: async context =>
        {
            var claimsIdentity = new ClaimsIdentity("Cookies");
            claimsIdentity.AddClaim(new Claim("iss", "test"));
            await context.SignInAsync(new ClaimsPrincipal(claimsIdentity));
        });

        var signInTransaction = await server.SendAsync(DefaultHost);

        var remoteSignOutTransaction = await server.SendAsync(DefaultHost + "/signout-oidc?iss=invalid", signInTransaction.AuthenticationCookieValue);

        Assert.Equal(HttpStatusCode.OK, remoteSignOutTransaction.Response.StatusCode);
        Assert.DoesNotContain(remoteSignOutTransaction.Response.Headers, h => h.Key == "Set-Cookie");
    }
Ejemplo n.º 20
0
    public async Task EndSessionRequestDoesNotIncludeTelemetryParametersWhenDisabled()
    {
        var configuration = TestServerBuilder.CreateDefaultOpenIdConnectConfiguration();
        var setting       = new TestSettings(opt =>
        {
            opt.ClientId         = "Test Id";
            opt.Configuration    = configuration;
            opt.SignInScheme     = CookieAuthenticationDefaults.AuthenticationScheme;
            opt.DisableTelemetry = true;
        });

        var server = setting.CreateTestServer();

        var transaction = await server.SendAsync(DefaultHost + TestServerBuilder.Signout);

        var res = transaction.Response;

        Assert.Equal(HttpStatusCode.Redirect, res.StatusCode);
        Assert.DoesNotContain(OpenIdConnectParameterNames.SkuTelemetry, res.Headers.Location.Query);
        Assert.DoesNotContain(OpenIdConnectParameterNames.VersionTelemetry, res.Headers.Location.Query);
        setting.ValidateSignoutRedirect(transaction.Response.Headers.Location);
    }
Ejemplo n.º 21
0
        public void UCITestUpdateActiveContact()
        {
            var client = new WebClient(TestSettings.Options);

            using (var xrmApp = new XrmApp(client))
            {
                xrmApp.OnlineLogin.Login(_xrmUri, _username, _password, _mfaSecrectKey);

                xrmApp.Navigation.OpenApp(UCIAppName.Sales);

                xrmApp.Navigation.OpenSubArea("Sales", "Contacts");

                xrmApp.Grid.OpenRecord(0);

                xrmApp.ThinkTime(3000);

                xrmApp.Entity.SetValue("firstname", TestSettings.GetRandomString(5, 10));
                xrmApp.Entity.SetValue("lastname", TestSettings.GetRandomString(5, 10));

                xrmApp.Entity.Save();
            }
        }
    public async Task Challenge_HasOverwrittenPromptParam()
    {
        var settings = new TestSettings(opt =>
        {
            opt.ClientId  = "Test Id";
            opt.Authority = TestServerBuilder.DefaultAuthority;
            opt.Prompt    = "consent";
        });
        var properties = new OpenIdConnectChallengeProperties()
        {
            Prompt = "login",
        };

        var server      = settings.CreateTestServer(properties);
        var transaction = await server.SendAsync(TestServerBuilder.TestHost + TestServerBuilder.ChallengeWithProperties);

        var res = transaction.Response;

        Assert.Equal(HttpStatusCode.Redirect, res.StatusCode);
        settings.ValidateChallengeRedirect(res.Headers.Location);
        Assert.Contains("prompt=login", res.Headers.Location.Query);
    }
Ejemplo n.º 23
0
        private TraceListener GetListener(string name)
        {
            object value = TestSettings.Get(name);

            if (value == null)
            {
                return(null);
            }
            if (value is string)
            {
                return(LookupListener((string)value));
            }
            if (value is bool)
            {
                if ((bool)value)
                {
                    return(new TextWriterTraceListener(System.Console.Out));
                }
                return(null);
            }
            throw new InvalidCastException("The '" + name + "' setting has invalid data type.");
        }
Ejemplo n.º 24
0
 public JoggingViewModel(ITesterService testerService, IValveManager valveManager, IDriver driver, TestSettings testSettings, ConfigurationSettings configurationSettings, IDigitalIO digitalIO)
 {
     this.digitalIO             = digitalIO;
     this.driver                = driver;
     this.testerService         = testerService;
     this.testSettings          = testSettings;
     this.configurationSettings = configurationSettings;
     this.valveManager          = valveManager;
     valveTypes.Add(new ValveModel("", "Sprawdzanie obecności"));
     valveTypes.Add(new ValveModel("2Up", "GM MBM 2UP LIN"));
     valveTypes.Add(new ValveModel("3_5Up", "JLR 3,5UP LIN"));
     valveTypes.Add(new ValveModel("6Up", "GM MBM 6UP LIN"));
     SelectedType        = valveTypes[0];
     IsLogInDataSelected = true;
     valveManager.ActiveErrorsChanged     += ValveManager_ActiveErrorsChanged;
     valveManager.OccuredErrorsChanged    += ValveManager_OccuredErrorsChanged;
     valveManager.ResultChanged           += ValveManager_ResultChanged;
     valveManager.CommunicationLogChanged += CommunicationLogChanged;
     testerService.ProgramStateChanged    += TesterService_ProgramStateEventHandler_Change;
     driver.CommunicationLogChanged       += CommunicationLogChanged;
     digitalIO.CommunicationLogChanged    += CommunicationLogChanged;
 }
        protected CommandResult RunTest(
            DotNetCli dotnet,
            TestApp app,
            TestSettings settings,
            Action <CommandResult> resultAction = null,
            bool multiLevelLookup = false)
        {
            using (DotNetCliExtensions.DotNetCliCustomizer dotnetCustomizer = settings.DotnetCustomizer == null ? null : dotnet.Customize())
            {
                settings.DotnetCustomizer?.Invoke(dotnetCustomizer);

                if (settings.RuntimeConfigCustomizer != null)
                {
                    settings.RuntimeConfigCustomizer(RuntimeConfig.Path(app.RuntimeConfigJson)).Save();
                }

                settings.WithCommandLine(app.AppDll);

                Command command = dotnet.Exec(settings.CommandLine.First(), settings.CommandLine.Skip(1).ToArray());

                if (settings.WorkingDirectory != null)
                {
                    command = command.WorkingDirectory(settings.WorkingDirectory);
                }

                CommandResult result = command
                                       .EnvironmentVariable("COREHOST_TRACE", "1")
                                       .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", multiLevelLookup ? "1" : "0")
                                       .Environment(settings.Environment)
                                       .CaptureStdOut()
                                       .CaptureStdErr()
                                       .Execute();

                resultAction?.Invoke(result);

                return(result);
            }
        }
Ejemplo n.º 26
0
        private static void TestMatrixVectorMultiplicationIntoResult(LinearAlgebraProviderChoice providers)
        {
            TestSettings.RunMultiproviderTest(providers, delegate()
            {
                // The result vectors will first be set to some non zero values to make sure that the result overwrites
                // them instead of being added to them.

                // MultiplyIntoResult() - untransposed
                var A1            = Matrix.CreateFromArray(RectangularFullRank10by5.Matrix);
                var x1            = Vector.CreateFromArray(RectangularFullRank10by5.Lhs5);
                var b1Expected    = Vector.CreateFromArray(RectangularFullRank10by5.Rhs10);
                Vector b1Computed = Vector.CreateWithValue(A1.NumRows, 1.0);
                A1.MultiplyIntoResult(x1, b1Computed, false);
                comparer.AssertEqual(b1Expected, b1Computed);

                // MultiplyIntoResult() - transposed
                var x2            = Vector.CreateFromArray(RectangularFullRank10by5.Lhs10);
                var b2Expected    = Vector.CreateFromArray(RectangularFullRank10by5.Rhs5);
                Vector b2Computed = Vector.CreateWithValue(A1.NumColumns, 1.0);
                A1.MultiplyIntoResult(x2, b2Computed, true);
                comparer.AssertEqual(b2Expected, b2Computed);
            });
        }
    public async Task RegularGetRequestToCallbackPathSkips()
    {
        // Arrange
        var settings = new TestSettings(
            opt =>
        {
            opt.Authority                = TestServerBuilder.DefaultAuthority;
            opt.CallbackPath             = new PathString("/");
            opt.SkipUnrecognizedRequests = true;
            opt.ClientId = "Test Id";
        });

        var server = settings.CreateTestServer(handler: async context =>
        {
            await context.Response.WriteAsync("Hi from the callback path");
        });

        // Act
        var transaction = await server.SendAsync("/");

        // Assert
        Assert.Equal("Hi from the callback path", transaction.ResponseText);
    }
Ejemplo n.º 28
0
        public static SettingsProvider CreateProvider()
        {
            var provider = new SettingsProvider("Project/Hinode Test Settings", SettingsScope.Project)
            {
                label      = "Hinode Test Settings",
                keywords   = new HashSet <string>(new[] { "Test", "Hinode" }),
                guiHandler = (searchContext) =>
                {
                    var settings = TestSettings.CreateOrGet();
                    var SO       = new SerializedObject(settings);
                    EditorGUILayout.PropertyField(SO.FindProperty("_doTakeSnapshot"), new GUIContent("Do Take Snapshot"));
                    EditorGUILayout.PropertyField(SO.FindProperty("_enableABTest"), new GUIContent("Enable A/B Test"));
                    EditorGUILayout.PropertyField(SO.FindProperty("_defaultABTestLoopCount"), new GUIContent("Default A/B Test Loop Count"));

                    if (SO.ApplyModifiedPropertiesWithoutUndo())
                    {
                        TestSettings.Save(SO.targetObject as TestSettings);
                    }
                }
            };

            return(provider);
        }
Ejemplo n.º 29
0
        public override void Step(TestSettings settings)
        {
            if (m_go && settings.hz > 0.0f)
            {
                m_time += 1.0f / settings.hz;
            }

            Vec2 linearOffset;

            linearOffset.X = 6.0f * (float)Math.Sin(2.0f * m_time);
            linearOffset.Y = 8.0f + 4.0f * (float)Math.Sin(1.0f * m_time);

            float angularOffset = 4.0f * m_time;

            m_joint.SetLinearOffset(linearOffset);
            m_joint.SetAngularOffset(angularOffset);

            m_debugDraw.DrawPoint(linearOffset, 4.0f, Color.FromArgb(225, 225, 225));

            base.Step(settings);
            m_debugDraw.DrawString("Keys: (s) pause");
            m_textLine += 15;
        }
Ejemplo n.º 30
0
        public async void CanGetValidAccessTokenFromFacebook()
        {
            var credentials = _settings
                              .GetClientCredentials <Facebook, OAuth2Credentials>();
            var token = await new OAuth2App <Facebook>(
                credentials.ClientId,
                credentials.ClientSecret,
                credentials.CallbackUrl)
                        .AddScope <FacebookEvent>()
                        .AddScope <FacebookFeed>()
                        .AddScope <FacebookFriend>()
                        .AddScope <FacebookPageLike>()
                        .GetCredentialsAsync()
                        .ConfigureAwait(false);

            Assert.True(IsValidOAuth2Token(token));
            Assert.Equal(0, token.AdditionalParameters.Count);

            if (TestSettings.ShouldPersistCredentials)
            {
                TestSettings.WriteCredentials <Facebook>(token);
            }
        }
    public async Task ChallengeDoesNotIncludePkceForOtherResponseTypes(string responseType)
    {
        var settings = new TestSettings(
            opt =>
        {
            opt.Authority            = TestServerBuilder.DefaultAuthority;
            opt.AuthenticationMethod = OpenIdConnectRedirectBehavior.RedirectGet;
            opt.ResponseType         = responseType;
            opt.ClientId             = "Test Id";
            opt.UsePkce = true;
        });

        var server      = settings.CreateTestServer();
        var transaction = await server.SendAsync(ChallengeEndpoint);

        var res = transaction.Response;

        Assert.Equal(HttpStatusCode.Redirect, res.StatusCode);
        Assert.NotNull(res.Headers.Location);

        Assert.DoesNotContain("code_challenge=", res.Headers.Location.Query);
        Assert.DoesNotContain("code_challenge_method=", res.Headers.Location.Query);
    }
    public async Task Challenge_HasOverwrittenScopeParamFromBaseAuthenticationProperties()
    {
        var settings = new TestSettings(opt =>
        {
            opt.ClientId  = "Test Id";
            opt.Authority = TestServerBuilder.DefaultAuthority;
            opt.Scope.Clear();
            opt.Scope.Add("foo");
            opt.Scope.Add("bar");
        });
        var properties = new AuthenticationProperties();

        properties.SetParameter(OpenIdConnectChallengeProperties.ScopeKey, new string[] { "baz", "qux" });

        var server      = settings.CreateTestServer(properties);
        var transaction = await server.SendAsync(TestServerBuilder.TestHost + TestServerBuilder.ChallengeWithProperties);

        var res = transaction.Response;

        Assert.Equal(HttpStatusCode.Redirect, res.StatusCode);
        settings.ValidateChallengeRedirect(res.Headers.Location);
        Assert.Contains("scope=baz%20qux", res.Headers.Location.Query);
    }
Ejemplo n.º 33
0
        public void UCITestCreateLead()
        {
            var client = new WebClient(TestSettings.Options);

            using (var xrmApp = new XrmApp(client))
            {
                xrmApp.OnlineLogin.Login(_xrmUri, _username, _password, _mfaSecrectKey);

                xrmApp.Navigation.OpenApp(UCIAppName.Sales);

                xrmApp.Navigation.OpenSubArea("Sales", "Leads");

                xrmApp.CommandBar.ClickCommand("New");

                xrmApp.ThinkTime(5000);

                xrmApp.Entity.SetValue("subject", TestSettings.GetRandomString(5, 15));
                xrmApp.Entity.SetValue("firstname", TestSettings.GetRandomString(5, 10));
                xrmApp.Entity.SetValue("lastname", TestSettings.GetRandomString(5, 10));

                xrmApp.Entity.Save();
            }
        }
Ejemplo n.º 34
0
        private void WriteTestSettingsJson(string configDirectory, TestSettings testSettings)
        {
            if (!Directory.Exists(configDirectory))
            {
                Directory.CreateDirectory(configDirectory);
            }

            var configFilePath = Path.Combine(configDirectory, String.Format("{0}.json", testSettings.GetType().Name));

            if (File.Exists(configFilePath))
            {
                File.Delete(configFilePath);
            }

            var serializerSettings = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            };

            var settingsJson = JsonConvert.SerializeObject(testSettings, serializerSettings);

            File.WriteAllText(configFilePath, settingsJson);
        }
Ejemplo n.º 35
0
        public void SaveSettings_SupplyValueForNonExistingParameter_SuccessfullyUpdatesValue()
        {
            // arrange
            TestSettings existingValue = new TestSettings {
                TestValue = 44
            };
            string existingJsonValue = JsonConvert.SerializeObject(existingValue);

            SettingsStub settingsStub = new SettingsStub();

            settingsStub["Test"] = existingJsonValue;

            SettingsService service = new SettingsService(settingsStub);

            existingValue.TestValue = 55;
            existingJsonValue       = JsonConvert.SerializeObject(existingValue);

            // act
            service.SaveSettings <TestSettings>("Test", existingValue);

            // assert
            Assert.AreEqual(existingJsonValue, settingsStub["Test"]);
        }
Ejemplo n.º 36
0
        protected RepositoryTests(DatabaseFixture fixture)
        {
            var webHost = WebHost.CreateDefaultBuilder()
                          .UseEnvironment("SapIntegrationTesting")
                          .UseStartup <Startup>()
                          .Build();

            var configuration = (IConfiguration)webHost.Services.GetService(typeof(IConfiguration));
            var settings      = new TestSettings();

            configuration.Bind(nameof(TestSettings), settings);
            var sapServerSettings = new SapServerSettings();

            configuration.Bind(nameof(SapServerSettings), sapServerSettings);
            fixture.SetBackupPath(settings.SqlBackupPath);

            DalService = (IDalService)webHost.Services.GetService(typeof(IDalService));

            //Clear tests after dispose
            fixture.SetConnectionString(sapServerSettings.SapServerSql);
            fixture.BackupDatabase();
            fixture.RestoreDatabaseOnDispose(true);
        }
Ejemplo n.º 37
0
        public void SettingsLoadSaveTest()
        {
            string dir  = Path.Combine(this.TestContext.TestRunDirectory, this.TestContext.TestName + DateTime.UtcNow.Ticks, "Settings Test Sub Directory");
            string file = Path.Combine(dir, "Settings Test File.xml");

            string key   = "hello";
            string value = "world !";

            TestSettings s1 = new TestSettings();

            Assert.IsTrue(!Directory.Exists(dir));
            s1.LoadSettings(file);
            s1[key] = value;
            s1.SaveSettings(file);
            Assert.IsTrue(File.Exists(file));

            TestSettings s2 = new TestSettings();

            s2.LoadSettings(file);
            Assert.AreEqual(value, s2[key]);

            File.Delete(file);
        }
Ejemplo n.º 38
0
        public void UCITestQuickCreateCase()
        {
            using (var xrmApp = CreateApp())
            {
                xrmApp.Navigation.OpenApp(UCIAppName.CustomerService);

                xrmApp.Navigation.QuickCreate("case");

                xrmApp.QuickCreate.SetValue(new LookupItem {
                    Name = "customerid", Value = "Adventure"
                });

                xrmApp.QuickCreate.SetValue("title", TestSettings.GetRandomString(5, 10));

                xrmApp.QuickCreate.SetValue(new OptionSet {
                    Name = "casetypecode", Value = "Problem"
                });

                xrmApp.QuickCreate.Save();

                xrmApp.ThinkTime(5.Seconds());
            }
        }
        public void HttpClientFactory_TryCreateProxy_ProxyWithBypass_ReturnsTrueOutProxyWithBypassedHosts()
        {
            const string proxyUrl   = "https://proxy.example.com/git";
            const string repoPath   = "/tmp/repos/foo";
            const string repoRemote = "https://remote.example.com/foo.git";

            var bypassList = new List <string> {
                "https://contoso.com", ".*fabrikam\\.com"
            };
            var repoRemoteUri = new Uri(repoRemote);
            var proxyConfig   = new ProxyConfiguration(
                new Uri(proxyUrl),
                userName: null,
                password: null,
                bypassHosts: bypassList);

            var settings = new TestSettings
            {
                RemoteUri          = repoRemoteUri,
                RepositoryPath     = repoPath,
                ProxyConfiguration = proxyConfig
            };
            var httpFactory = new HttpClientFactory(Mock.Of <IFileSystem>(), Mock.Of <ITrace>(), settings, Mock.Of <IStandardStreams>());

            bool result = httpFactory.TryCreateProxy(out IWebProxy proxy);

            Assert.True(result);
            Assert.NotNull(proxy);
            Uri configuredProxyUrl = proxy.GetProxy(repoRemoteUri);

            Assert.Equal(proxyUrl, configuredProxyUrl?.ToString());

            Assert.True(proxy.IsBypassed(new Uri("https://contoso.com")));
            Assert.True(proxy.IsBypassed(new Uri("http://fabrikam.com")));
            Assert.True(proxy.IsBypassed(new Uri("https://subdomain.fabrikam.com")));
            Assert.False(proxy.IsBypassed(repoRemoteUri));
        }
        public void HttpClientFactory_TryCreateProxy_ProxyWithCredentials_ReturnsTrueOutProxyWithUrlConfiguredCredentials()
        {
            const string proxyUser  = "******";
            const string proxyPass  = "******";
            const string proxyUrl   = "https://proxy.example.com/git";
            const string repoPath   = "/tmp/repos/foo";
            const string repoRemote = "https://remote.example.com/foo.git";

            var repoRemoteUri = new Uri(repoRemote);
            var proxyConfig   = new ProxyConfiguration(
                new Uri(proxyUrl),
                proxyUser,
                proxyPass);

            var settings = new TestSettings
            {
                RemoteUri          = repoRemoteUri,
                RepositoryPath     = repoPath,
                ProxyConfiguration = proxyConfig
            };
            var httpFactory = new HttpClientFactory(Mock.Of <IFileSystem>(), Mock.Of <ITrace>(), settings, Mock.Of <IStandardStreams>());

            bool result = httpFactory.TryCreateProxy(out IWebProxy proxy);

            Assert.True(result);
            Assert.NotNull(proxy);
            Uri configuredProxyUrl = proxy.GetProxy(repoRemoteUri);

            Assert.Equal(proxyUrl, configuredProxyUrl?.ToString());

            Assert.NotNull(proxy.Credentials);
            Assert.IsType <NetworkCredential>(proxy.Credentials);
            var configuredCredentials = (NetworkCredential)proxy.Credentials;

            Assert.Equal(proxyUser, configuredCredentials.UserName);
            Assert.Equal(proxyPass, configuredCredentials.Password);
        }
        public async Task MigrateNewest()
        {
            TestSettings.SkipTestIfNecessary();

            var now = DateTime.UtcNow;

            await using var container = CreateContainer();
            var engine = container.GetRequiredService <MigrationEngine>();

            using var session = container.GetRequiredService <IDocumentStore>().OpenAsyncSession();
            session.Advanced.WaitForIndexesAfterSaveChanges();
            await session.StoreAsync(new MigrationInfo { Id = "migrationInfos/1.0.0", Name = nameof(FirstMigration), Version = "1.0.0", AppliedAt = now.AddDays(-1) });

            await session.SaveChangesAsync();

            var summary = await engine.MigrateAsync(now, new[] { GetType().Assembly });

            summary.TryGetAppliedMigrations(out var appliedMigrations).Should().BeTrue();
            var expectedMigrationInfo = new MigrationInfo {
                Id = "migrationInfos/2.0.0", Name = nameof(SecondMigration), Version = "2.0.0", AppliedAt = now
            };
            var expectedMigrationInfos = new List <MigrationInfo> {
                expectedMigrationInfo
            };

            appliedMigrations.Should().BeEquivalentTo(expectedMigrationInfos);
            var storedEntities = await session.Query <Entity>().ToListAsync();

            var expectedStoredEntities = new List <Entity> {
                new () { Id = "entities/1-A", Value = "Bar" }
            };

            storedEntities.Should().BeEquivalentTo(expectedStoredEntities);
            var storedMigrationInfo = await session.LoadAsync <MigrationInfo?>(expectedMigrationInfo.Id);

            storedMigrationInfo.Should().BeEquivalentTo(expectedMigrationInfo);
        }
    public async Task OnRedirectToIdentityProviderEventCanReplaceMessage()
    {
        var newMessage = new MockOpenIdConnectMessage
        {
            IssuerAddress         = "http://example.com/",
            TestAuthorizeEndpoint = $"http://example.com/{Guid.NewGuid()}/oauth2/signin"
        };

        var settings = new TestSettings(
            opts =>
        {
            opts.ClientId  = "Test Id";
            opts.Authority = TestServerBuilder.DefaultAuthority;
            opts.Events    = new OpenIdConnectEvents()
            {
                OnRedirectToIdentityProvider = context =>
                {
                    context.ProtocolMessage = newMessage;

                    return(Task.FromResult(0));
                }
            };
        }
            );

        var server      = settings.CreateTestServer();
        var transaction = await server.SendAsync(ChallengeEndpoint);

        var res = transaction.Response;

        Assert.Equal(HttpStatusCode.Redirect, res.StatusCode);
        Assert.NotNull(res.Headers.Location);

        // The CreateAuthenticationRequestUrl method is overridden MockOpenIdConnectMessage where
        // query string is not generated and the authorization endpoint is replaced.
        Assert.Equal(newMessage.TestAuthorizeEndpoint, res.Headers.Location.AbsoluteUri);
    }
        public RequestEvaluatorTestFixture()
        {
            var settings = new TestSettings {
                Mode = Mode.On,
                IgnoreAjaxRequests = true,
                IgnoreImages = true,
                IgnoreStyleSheets = true,
                IgnoreSystemHandlers = true,
                Paths = {
                    new TestPathSetting("/Info/ContactUs.aspx", PathMatchType.StartsWith, true, RequestSecurity.Insecure),
                    new TestPathSetting("/Login.aspx"),
                    new TestPathSetting("/Admin/ViewOrders.aspx"),

                    new TestPathSetting("/info/contactus", PathMatchType.StartsWith, true, RequestSecurity.Insecure),
                    new TestPathSetting("/login/"),
                    new TestPathSetting("/admin/vieworders/"),

                    new TestPathSetting("/Manage")
                }
            };
            settings.CallPostDeserialize();

            Settings = settings;
        }
           public void AttemptToSetTheUnsettableResultsInAnException()
           {
               var settingsSource = new NameValueCollection();
               settingsSource["Test:Unsettable"] = "Bang";
               var reader = new SimpleSettingsReader(settingsSource);
               var injector = new SimpleSettingsInjector();
               var settings = new TestSettings();

               injector.Inject(settings, reader);
           }
Ejemplo n.º 45
0
        private static void RunPageTest(TestSettings settings)
        {
            string url;
            using (var browser = new IE(ConfigurationManager.AppSettings["WebpageTestUrl"]))
            {
                browser.TextField(Find.ById("url")).Value = settings.Url;

                if (!string.IsNullOrEmpty(settings.TestLocation))
                    browser.SelectList(Find.ById("location")).SelectByValue(settings.TestLocation);
                if (!string.IsNullOrEmpty(settings.Browser))
                    browser.SelectList(Find.ById("browser")).SelectByValue(settings.Browser);
                browser.Link(Find.ById("advanced_settings")).ClickNoWait();
                if (!string.IsNullOrEmpty(settings.Speed))
                    browser.SelectList(Find.ById("connection")).SelectByValue(settings.Speed);
                if (settings.IsPrivate)
                    browser.CheckBox(Find.ById("keep_test_private")).Change();

                if (!string.IsNullOrEmpty(settings.Username))
                    browser.TextField(Find.ById("username")).TypeText(settings.Username);
                if (!string.IsNullOrEmpty(settings.Password))
                    browser.TextField(Find.ById("password")).TypeText(settings.Password);

                browser.Button(Find.ByName("submit")).Click();

                browser.WaitUntilContainsText("First View", settings.Timeout);
                if (browser.ContainsText("partially complete"))
                {
                    Thread.Sleep(10000);
                    browser.Refresh();
                }

                browser.WaitUntilContainsText("Raw page data", settings.Timeout);

                url = browser.Link(Find.ByText("Raw page data")).Url;
            }
            var csvRequest = (HttpWebRequest) WebRequest.Create(url);
            csvRequest.Accept = "text/csv";

            var data = new List<PageData>();
            using (var stream = csvRequest.GetResponse().GetResponseStream())
            {
                if (stream != null)
                {
                    using (var reader = new StreamReader(stream))
                    {
                        using (var context = new CsvReader(reader))
                        {
                            while (context.Read())
                            {
                                var counter = data.Count;
                                var item = new PageData();
                                item.EventName = counter == 0 ? "Empty Cache" : "Cached Run " + counter;
                                item.Url = context.GetField<string>(3);
                                item.LoadTime = TimeSpan.FromMilliseconds(context.GetField<int>(4));
                                item.TimeToFirstByte = TimeSpan.FromMilliseconds(context.GetField<int>(5));
                                item.Requests = context.GetField<int>(11);
                                data.Add(item);
                            }
                        }
                    }
                }
            }

            var host = ConfigurationManager.AppSettings["MetricTracking:Host"];
            var port = int.Parse(ConfigurationManager.AppSettings["MetricTracking:Port"]);

            using (var metric = new MetricTracker(host, port))
            {
                foreach (var run in data)
                {
                    Console.WriteLine(run.EventName + "\t" + run.LoadTime);

                    var prefix = settings.Prefix + run.EventName.Replace(" ", string.Empty) + ".";
                    metric.Timing(prefix + "LoadTime", run.LoadTime.TotalMilliseconds);
                    metric.Timing(prefix + "TimeToFirstByte", run.TimeToFirstByte.TotalMilliseconds);
                    metric.Value(prefix + "Requests", run.Requests);
                }
            }
        }
Ejemplo n.º 46
0
 public ComparisonTestCases(TestSettings testSettings)
 {
     _testSettings = testSettings;
     _collection = Enumerable.Range(0, _testSettings.TestCollectionSize);
 }
Ejemplo n.º 47
0
 public async void PostingAJsonObject_ParsingTheLocationHeader_SupplyingResponseParserViaSettings()
 {
     var settings = new TestSettings().OverrideContentDeserializer(new ExtendedContentDeserializer(new JsonSerializer()));
     var customerApi = Api.For<ICustomerApi>(Host, settings);
     var result = await customerApi.CreateDriverWithLocation(new Customer { Id = 1, Name = "Mighty Gazelle" });
     Assert.AreEqual("Mighty Gazelle", result.Name);
     Assert.AreEqual("api/customer/1", result.Location);
     Assert.AreEqual(1, result.Id);
 }
Ejemplo n.º 48
0
 public void Initialize()
 {
     _settings = new TestSettings();
     _container = ApplicationData.Current.LocalSettings;
 }
Ejemplo n.º 49
0
 public TestNode(TestSettings testSettings) : base(testSettings) {
     packetQueue = new Queue<Packet>();
     nodeStateQueue = new Queue<TestNodeState>();
 }
Ejemplo n.º 50
0
 public async void PostingAJsonObjectModifyingContentWithResolver()
 {
     var settings = new TestSettings();
     settings.ListTransformers.Add(new ContentExtender());
     var customerApi = Api.For<ICustomerApi>(Host, settings);
     var result = await customerApi.CreateCustomer2(new Customer { Id = 1, Name = "Placeholder" });
     Assert.AreEqual("Mighty Gazelle", result.Name);
     Assert.AreEqual(1, result.Id);
 }
 private TestSettings(TestSettings existing) : base(existing) { }
 public void DefaultToNulls()
 {
     var settings = new TestSettings();
     Assert.Null(settings.CallSettings);
     Assert.Null(settings.Clock);
 }