Esempio n. 1
0
        public async Task Single_item_data_is_deserialized_properly()
        {
            var dataStore = TestDataStore.Create(new StubRequestExecutor(FakeJson.Account).Object);

            var account = await dataStore.GetResourceAsync <IAccount>("/account", CancellationToken.None);

            // Verify against data from FakeJson.Account
            account.CreatedAt.ShouldBe(Iso8601.Parse("2015-07-21T23:50:49.078Z"));
            account.Email.ShouldBe("*****@*****.**");
            account.FullName.ShouldBe("Han Solo");
            account.GivenName.ShouldBe("Han");
            account.Href.ShouldBe("https://api.stormpath.com/v1/accounts/foobarAccount");
            account.MiddleName.ShouldBeNull();
            account.ModifiedAt.ShouldBe(Iso8601.Parse("2015-07-21T23:50:49.078Z"));
            account.Status.ShouldBe(AccountStatus.Enabled);
            account.Surname.ShouldBe("Solo");
            account.Username.ShouldBe("*****@*****.**");

            (account as DefaultAccount).AccessTokens.Href.ShouldBe("https://api.stormpath.com/v1/accounts/foobarAccount/accessTokens");
            (account as DefaultAccount).ApiKeys.Href.ShouldBe("https://api.stormpath.com/v1/accounts/foobarAccount/apiKeys");
            (account as DefaultAccount).Applications.Href.ShouldBe("https://api.stormpath.com/v1/accounts/foobarAccount/applications");
            (account as DefaultAccount).CustomData.Href.ShouldBe("https://api.stormpath.com/v1/accounts/foobarAccount/customData");
            (account as DefaultAccount).Directory.Href.ShouldBe("https://api.stormpath.com/v1/directories/foobarDirectory");
            (account as DefaultAccount).EmailVerificationToken.Href.ShouldBeNull();
            (account as DefaultAccount).GroupMemberships.Href.ShouldBe("https://api.stormpath.com/v1/accounts/foobarAccount/groupMemberships");
            (account as DefaultAccount).Groups.Href.ShouldBe("https://api.stormpath.com/v1/accounts/foobarAccount/groups");
            (account as DefaultAccount).ProviderData.Href.ShouldBe("https://api.stormpath.com/v1/accounts/foobarAccount/providerData");
            (account as DefaultAccount).RefreshTokens.Href.ShouldBe("https://api.stormpath.com/v1/accounts/foobarAccount/refreshTokens");
            (account as DefaultAccount).Tenant.Href.ShouldBe("https://api.stormpath.com/v1/tenants/foobarTenant");
        }
Esempio n. 2
0
        public void Updating_custom_data_with_proxy_updates_cache()
        {
            var cacheProvider   = Caches.NewInMemoryCacheProvider().Build();
            var requestExecutor = Substitute.For <IRequestExecutor>();

            this.dataStore = TestDataStore.Create(requestExecutor, cacheProvider);

            // GET returns expanded request
            requestExecutor
            .Execute(Arg.Is <IHttpRequest>(req => req.Method == HttpMethod.Get))
            .Returns(new DefaultHttpResponse(200, "OK", new HttpHeaders(), FakeJson.AccountWithExpandedCustomData, "application/json", transportError: false));

            // Save is not an expanded request
            requestExecutor
            .Execute(Arg.Is <IHttpRequest>(req => req.Method == HttpMethod.Post))
            .Returns(new DefaultHttpResponse(201, "Created", new HttpHeaders(), FakeJson.Account, "application/json", transportError: false));

            var account = this.dataStore.GetResource <IAccount>("/accounts/foobarAccount?expand=customData");

            account.CustomData.Put("isAdmin", true);
            account.CustomData.Put("writeAccess", "yes");
            account.Save();

            var customData = account.GetCustomData();

            customData["isAdmin"].ShouldBe(true);
            customData["writeAccess"].ShouldBe("yes");

            this.dataStore.RequestExecutor.Received(1).Execute(
                Arg.Is <IHttpRequest>(x => x.Method == HttpMethod.Get));
        }
Esempio n. 3
0
        public async Task When_saving_returns_empty_response_without_status_202_throws_error()
        {
            // Expected behavior: Saving should always return the updated data unless we get back HTTP 202 (Accepted for Processing).
            var dataStore = TestDataStore.Create(new StubRequestExecutor(FakeJson.Account).Object) as IInternalAsyncDataStore;

            dataStore.RequestExecutor
            .ExecuteAsync(Arg.Any <IHttpRequest>(), Arg.Any <CancellationToken>())
            .Returns(Task.FromResult <IHttpResponse>(new DefaultHttpResponse(200, "OK", null, null, null, transportError: false)));

            var account = dataStore.Instantiate <IAccount>();

            account.SetMiddleName("Test");
            account.SetUsername("newusername");

            bool erroredAsExpected = false;

            try
            {
                await dataStore.CreateAsync("http://api.foo.bar/accounts", account, CancellationToken.None);
            }
            catch (ResourceException rex)
            {
                rex.DeveloperMessage.ShouldBe("Unable to obtain resource data from the API server.");
                erroredAsExpected = true;
            }

            erroredAsExpected.ShouldBeTrue();
        }
Esempio n. 4
0
        public void Does_not_cache_password_reset_tokens()
        {
            var cacheProvider   = Caches.NewInMemoryCacheProvider().Build();
            var requestExecutor = Substitute.For <IRequestExecutor>();

            this.dataStore = TestDataStore.Create(requestExecutor, cacheProvider);

            var passwordResetTokenResponse = @"
{
    ""href"": ""https://api.stormpath.com/v1/applications/foo/passwordResetTokens/bar"",
    ""email"": ""*****@*****.**"",
    ""account"": {
        ""href"": ""https://api.stormpath.com/v1/accounts/cJoiwcorTTmkDDBsf02bAb""
    }
}
";

            // POST returns token response
            requestExecutor
            .Execute(Arg.Is <IHttpRequest>(req => req.Method == HttpMethod.Post))
            .Returns(new DefaultHttpResponse(200, "OK", new HttpHeaders(), passwordResetTokenResponse, "application/json", transportError: false));

            // GET also returns token response
            requestExecutor
            .Execute(Arg.Is <IHttpRequest>(req => req.Method == HttpMethod.Get))
            .Returns(new DefaultHttpResponse(200, "OK", new HttpHeaders(), passwordResetTokenResponse, "application/json", transportError: false));

            this.dataStore.GetResource <IPasswordResetToken>("https://api.stormpath.com/v1/applications/foo/passwordResetTokens/bar");
            this.dataStore.GetResource <IPasswordResetToken>("https://api.stormpath.com/v1/applications/foo/passwordResetTokens/bar");

            // Not cached
            this.dataStore.RequestExecutor.Received(2).Execute(
                Arg.Any <IHttpRequest>());
        }
        public async Task Updating_resource_updates_cache()
        {
            var cacheProvider   = Caches.NewInMemoryCacheProvider().Build();
            var requestExecutor = Substitute.For <IRequestExecutor>();

            this.dataStore = TestDataStore.Create(requestExecutor, cacheProvider);

            // GET returns original
            requestExecutor
            .ExecuteAsync(Arg.Is <IHttpRequest>(req => req.Method == HttpMethod.Get), Arg.Any <CancellationToken>())
            .Returns(Task.FromResult(new DefaultHttpResponse(200, "OK", new HttpHeaders(), FakeJson.Account, "application/json", transportError: false) as IHttpResponse));

            // Save returns update data
            requestExecutor
            .ExecuteAsync(Arg.Is <IHttpRequest>(req => req.Method == HttpMethod.Post), Arg.Any <CancellationToken>())
            .Returns(Task.FromResult(new DefaultHttpResponse(201, "Created", new HttpHeaders(), FakeJson.Account.Replace("*****@*****.**", "*****@*****.**"), "application/json", transportError: false) as IHttpResponse));

            var account1 = await this.dataStore.GetResourceAsync <IAccount>("/accounts/foobarAccount");

            account1.Email.ShouldBe("*****@*****.**");

            account1.SetEmail("*****@*****.**");
            await account1.SaveAsync();

            account1.Email.ShouldBe("*****@*****.**");

            var account2 = await this.dataStore.GetResourceAsync <IAccount>("/accounts/foobarAccount");

            account2.Email.ShouldBe("*****@*****.**");

            // Only one GET; second is intercepted by the cache (but the updated data is returned!) #magic
            await this.dataStore.RequestExecutor.Received(1).ExecuteAsync(
                Arg.Is <IHttpRequest>(x => x.Method == HttpMethod.Get),
                Arg.Any <CancellationToken>());
        }
        public async Task Does_not_cache_email_verification_tokens()
        {
            var cacheProvider   = Caches.NewInMemoryCacheProvider().Build();
            var requestExecutor = Substitute.For <IRequestExecutor>();

            this.dataStore = TestDataStore.Create(requestExecutor, cacheProvider);

            var emailVerificationTokenResponse = @"
{
    ""href"": ""https://api.stormpath.com/v1/accounts/foobarAccount""
}
";

            // POST returns email verification token response
            requestExecutor
            .ExecuteAsync(Arg.Is <IHttpRequest>(req => req.Method == HttpMethod.Post), Arg.Any <CancellationToken>())
            .Returns(Task.FromResult(new DefaultHttpResponse(200, "OK", new HttpHeaders(), emailVerificationTokenResponse, "application/json", transportError: false) as IHttpResponse));

            var href = $"/accounts/emailVerificationTokens/fooToken";

            await(this.dataStore as IInternalAsyncDataStore).CreateAsync <IResource, IEmailVerificationToken>(href, null, CancellationToken.None);
            await(this.dataStore as IInternalAsyncDataStore).CreateAsync <IResource, IEmailVerificationToken>(href, null, CancellationToken.None);

            // Not cached
            await this.dataStore.RequestExecutor.Received(2).ExecuteAsync(
                Arg.Any <IHttpRequest>(),
                Arg.Any <CancellationToken>());
        }
Esempio n. 7
0
        public void GetTest()
        {
            ISponsor Expected = new TestSponsor {
                Id          = 1,
                DisplayName = "Test Sponsor",
                LogoLarge   = "Logo Large",
                LogoSmall   = "Logo Small",
                Website     = "Test Website",
                Level       = new TestSponsorLevel {
                    Id               = 1,
                    DisplayName      = "Test Sponsor Level",
                    DisplayOrder     = 1,
                    DisplayInEmails  = false,
                    DisplayInSidebar = false
                }
            };

            TestDataStore testDataStore = new TestDataStore();

            testDataStore.GetFunction = (id) => {
                return(Task.FromResult <ISponsor>(Expected));
            };

            SponsorController   ControllerToTest = new SponsorController(testDataStore);
            HttpResponseMessage Actual           = ControllerToTest.Get(1).Result;

            Assert.IsNotNull(Actual);
            Assert.AreEqual(HttpStatusCode.OK, Actual.StatusCode);
            AssertSponorsAreEqual(Expected, Newtonsoft.Json.JsonConvert.DeserializeObject <Common.Sponsor>(Actual.Content.ReadAsStringAsync().Result));
        }
        public async Task Does_not_cache_login_attempts()
        {
            var cacheProvider   = Caches.NewInMemoryCacheProvider().Build();
            var requestExecutor = Substitute.For <IRequestExecutor>();

            this.dataStore = TestDataStore.Create(requestExecutor, cacheProvider);

            var authResponse = @"
{
  ""account"": {
    ""href"" : ""https://api.stormpath.com/v1/accounts/5BedLIvyfLjdKKEEXAMPLE""
  }
}";

            // POST returns auth response
            requestExecutor
            .ExecuteAsync(Arg.Is <IHttpRequest>(req => req.Method == HttpMethod.Post), Arg.Any <CancellationToken>())
            .Returns(Task.FromResult(new DefaultHttpResponse(200, "OK", new HttpHeaders(), authResponse, "application/json", transportError: false) as IHttpResponse));

            var request       = new UsernamePasswordRequest("foo", "bar", null, null) as IAuthenticationRequest;
            var authenticator = new BasicAuthenticator(this.dataStore);

            var result1 = await authenticator.AuthenticateAsync("/loginAttempts", request, null, CancellationToken.None);

            var result2 = await authenticator.AuthenticateAsync("/loginAttempts", request, null, CancellationToken.None);

            // Not cached
            await this.dataStore.RequestExecutor.Received(2).ExecuteAsync(
                Arg.Any <IHttpRequest>(),
                Arg.Any <CancellationToken>());
        }
Esempio n. 9
0
 public EmployerIncentivesHubSteps(TestContext testContext) : base(testContext)
 {
     _testContext   = testContext;
     _testDataStore = testContext.TestDataStore;
     _fixture       = new Fixture();
     _applicationId = Guid.NewGuid();
 }
        public async Task Handle_error(string id_, string jwtResponse, Type expectedExceptionType, int expectedCode, int expectedStatus, string expectedMessage, string expectedDeveloperMessage)
        {
            var testApiKey = ClientApiKeys.Builder()
                             .SetId("2EV70AHRTYF0JOA7OEFO3SM29")
                             .SetSecret("goPUHQMkS4dlKwl5wtbNd91I+UrRehCsEDJrIrMruK8")
                             .Build();
            var fakeRequestExecutor = Substitute.For <IRequestExecutor>();

            fakeRequestExecutor.ApiKey.Returns(testApiKey);

            this.dataStore = TestDataStore.Create(fakeRequestExecutor, Caches.NewInMemoryCacheProvider().Build());

            var request = new DefaultHttpRequest(HttpMethod.Get, new CanonicalUri($"https://foo.bar?{IdSiteClaims.JwtResponse}={jwtResponse}"));

            IIdSiteAsyncCallbackHandler callbackHandler = new DefaultIdSiteAsyncCallbackHandler(this.dataStore, request);

            try
            {
                var accountResult = await callbackHandler.GetAccountResultAsync(CancellationToken.None);

                throw new Exception("Should not reach here. Proper exception was not thrown.");
            }
            catch (IdSiteRuntimeException e) when(expectedExceptionType.IsAssignableFrom(e.GetType()))
            {
                e.Code.ShouldBe(expectedCode);
                e.HttpStatus.ShouldBe(expectedStatus);
                e.Message.ShouldBe(expectedMessage);
                e.DeveloperMessage.ShouldBe(expectedDeveloperMessage);
            }
            catch (Exception e) when(expectedExceptionType.IsAssignableFrom(e.GetType()))
            {
                e.Message.ShouldStartWith(expectedMessage);
            }
        }
Esempio n. 11
0
        public async Task Saving_resource_posts_changed_values_only()
        {
            string savedHref = null;
            string savedJson = null;

            var dataStore = TestDataStore.Create(new StubRequestExecutor(FakeJson.Account).Object);

            dataStore.RequestExecutor
            .When(x => x.ExecuteAsync(Arg.Any <IHttpRequest>(), Arg.Any <CancellationToken>()))
            .Do(call =>
            {
                savedHref = call.Arg <IHttpRequest>().CanonicalUri.ToString();
                savedJson = call.Arg <IHttpRequest>().Body;
            });

            var account = await dataStore.GetResourceAsync <IAccount>("/account", CancellationToken.None);

            account.Href.ShouldBe("https://api.stormpath.com/v1/accounts/foobarAccount");

            account.SetMiddleName("Test");
            account.SetUsername("newusername");

            await account.SaveAsync();

            savedHref.ShouldBe("https://api.stormpath.com/v1/accounts/foobarAccount");

            var savedMap = Newtonsoft.Json.JsonConvert.DeserializeObject <Dictionary <string, string> >(savedJson);

            savedMap.Count.ShouldBe(2);
            savedMap["middleName"].ShouldBe("Test");
            savedMap["username"].ShouldBe("newusername");
        }
Esempio n. 12
0
        async Task ExecuteLoadItemsCommand()
        {
            if (IsBusy)
            {
                return;
            }

            IsBusy = true;

            try
            {
                Notes.Clear();
                var notes = await TestDataStore.GetNotesAsync();

                foreach (var note in notes)
                {
                    Notes.Add(note);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }
        public async Task Embedded_custom_data_is_cleared_for_all_instances_after_save()
        {
            var dataStore = TestDataStore.Create(new StubRequestExecutor(FakeJson.Account).Object);

            var account = await dataStore.GetResourceAsync <IAccount>("/account", CancellationToken.None);

            var account2 = await dataStore.GetResourceAsync <IAccount>("/account", CancellationToken.None);

            account.CustomData.Put("foo", 123);

            await account.SaveAsync();

            var expectedBody = @"{""customData"":{""foo"":123}}";
            var body         = dataStore.RequestExecutor
                               .ReceivedCalls()
                               .Last()
                               .GetArguments()
                               .OfType <IHttpRequest>()
                               .First()
                               .Body;

            body.ShouldBe(expectedBody);

            dataStore.RequestExecutor.ClearReceivedCalls();
            await account2.SaveAsync();

            // Empty save, should not POST anything
            await dataStore.RequestExecutor.DidNotReceive().ExecuteAsync(
                Arg.Is <IHttpRequest>(req =>
                                      req.Method == HttpMethod.Post),
                Arg.Any <CancellationToken>());
        }
        public DefaultResourceFactory_tests()
        {
            var dataStore   = TestDataStore.Create();
            var identityMap = new MemoryCacheIdentityMap <ResourceData>(TimeSpan.FromSeconds(10), Substitute.For <ILogger>()); // arbitrary expiration time

            this.factory = new DefaultResourceFactory(dataStore, identityMap);
        }
Esempio n. 15
0
        public async Task Cancellation_token_is_passed_down_to_low_level_operations()
        {
            var dataStore = TestDataStore.Create(new StubRequestExecutor(FakeJson.Account).Object) as IInternalAsyncDataStore;

            dataStore.RequestExecutor
            .ExecuteAsync(Arg.Any <IHttpRequest>(), Arg.Any <CancellationToken>())
            .Returns(async callInfo =>
            {
                // Will pause for 1 second, unless CancellationToken has been passed through to us
                await Task.Delay(1000, callInfo.Arg <CancellationToken>());
                return(new DefaultHttpResponse(204, "No Content", new HttpHeaders(), null, null, transportError: false) as IHttpResponse);
            });

            var fakeAccount = dataStore.InstantiateWithHref <IAccount>("http://api.foo.bar/accounts/1");

            var alreadyCanceledSource = new CancellationTokenSource();

            alreadyCanceledSource.Cancel();

            var stopwatch = Stopwatch.StartNew();
            var deleted   = false;

            try
            {
                await dataStore.DeleteAsync(fakeAccount, alreadyCanceledSource.Token);
            }
            catch (TaskCanceledException)
            {
                deleted = true;
            }

            stopwatch.Stop();
            stopwatch.ElapsedMilliseconds.ShouldBeLessThan(1000);
            deleted.ShouldBeTrue();
        }
        public void Post_Update()
        {
            try {
                TestUser testUser = new TestUser {
                    Id           = 1,
                    EmailAddress = "*****@*****.**",
                    DisplayName  = "Test Display Name",
                    PasswordHash = "TestPassword"
                };

                TestDataStore testDataStore = new TestDataStore();
                testDataStore.data.Add(1, testUser);

                Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("*****@*****.**"), null);

                UserController      objectUnderTest = new UserController(testDataStore);
                HttpResponseMessage actual          = objectUnderTest.Post(testUser).Result;

                Assert.AreEqual(HttpStatusCode.OK, actual.StatusCode);

                IUser savedUser = testDataStore.data.Values.FirstOrDefault();
                Assert.IsNotNull(savedUser);

                Assert.AreEqual(testUser.EmailAddress, savedUser.EmailAddress);
                Assert.AreEqual(testUser.DisplayName, savedUser.DisplayName);
                Assert.AreNotEqual("TestPassword", savedUser.PasswordHash);
                Assert.AreNotEqual(0, savedUser.Id);
            } finally {
                Thread.CurrentPrincipal = null;
            }
        }
        public async Task Deleting_custom_data_with_proxy_updates_cache()
        {
            var cacheProvider = Caches.NewInMemoryCacheProvider().Build();

            var requestExecutor = Substitute.For <IRequestExecutor>();

            this.dataStore = TestDataStore.Create(requestExecutor, cacheProvider);

            // GET returns expanded request
            requestExecutor
            .ExecuteAsync(Arg.Is <IHttpRequest>(req => req.Method == HttpMethod.Get), Arg.Any <CancellationToken>())
            .Returns(Task.FromResult(new DefaultHttpResponse(200, "OK", new HttpHeaders(), FakeJson.AccountWithExpandedCustomData, "application/json", transportError: false) as IHttpResponse));

            // Save is not an expanded request
            requestExecutor
            .ExecuteAsync(Arg.Is <IHttpRequest>(req => req.Method == HttpMethod.Post), Arg.Any <CancellationToken>())
            .Returns(Task.FromResult(new DefaultHttpResponse(201, "Created", new HttpHeaders(), FakeJson.Account, "application/json", transportError: false) as IHttpResponse));

            var account = await this.dataStore.GetResourceAsync <IAccount>("/accounts/foobarAccount?expand=customData");

            account.CustomData.Remove("isAdmin");
            await account.SaveAsync();

            var customData = await account.GetCustomDataAsync();

            customData["isAdmin"].ShouldBe(null);

            await this.dataStore.RequestExecutor.Received(1).ExecuteAsync(
                Arg.Is <IHttpRequest>(x => x.Method == HttpMethod.Get),
                Arg.Any <CancellationToken>());
        }
 public CancelApprenticeshipSteps(TestContext testContext) : base(testContext)
 {
     _testContext    = testContext;
     _testData       = _testContext.TestDataStore;
     _hashingService = _testContext.HashingService;
     _data           = new TestData.Account.WithPreviousApprenticeshipIncentiveForFirstLegalEntity();
 }
Esempio n. 19
0
        public void Instantiated_resources_contain_reference_to_client()
        {
            var fakeClient = Substitute.For <IClient>();
            var dataStore  = TestDataStore.Create(client: fakeClient);

            var account = dataStore.Instantiate <IAccount>();

            account.Client.ShouldBe(fakeClient);
        }
        public void GetValue_returns_token_value()
        {
            var dataStore = TestDataStore.Create();

            var href = "https://api.foobar.com/v1/applications/WpM9nyZ2TbaEzfbRvLk9KA/passwordResetTokens/my-token-value-here";

            var passwordResetToken = dataStore.InstantiateWithHref <IPasswordResetToken>(href);

            passwordResetToken.GetValue().ShouldBe("my-token-value-here");
        }
Esempio n. 21
0
        public void SetupData()
        {
            ObjectFactory.Initialize(x =>
            {
                x.For <ILogging>().Use <TraceLogger>();
                x.For <IConfiguration>().Use <MockConfig>();
                x.For <IDataStore>().Use <TestDataStore>();
            });

            TestDataStore.Reset();
        }
Esempio n. 22
0
        public async Task Default_headers_are_applied_to_all_requests()
        {
            var dataStore = TestDataStore.Create(new StubRequestExecutor(FakeJson.Account).Object);

            var account = await dataStore.GetResourceAsync <IAccount>("/account", CancellationToken.None);

            // Verify the default headers
            await dataStore.RequestExecutor.Received().ExecuteAsync(
                Arg.Is <IHttpRequest>(request =>
                                      request.Headers.Accept == "application/json"),
                Arg.Any <CancellationToken>());
        }
 public AuthenticationSteps(TestContext testContext) : base(testContext)
 {
     _testContext = testContext;
     _testDataStore = _testContext.TestDataStore;
     var hook = _testContext.Hooks.SingleOrDefault(h => h is Hook<AuthorizationHandlerContext>) as Hook<AuthorizationHandlerContext>;
     hook.OnProcessed = (c) => {
         if (_authContext == null)
         {
             _authContext = c;
         }
     };
 }
Esempio n. 24
0
        public void GetTest_NotFound()
        {
            TestDataStore testDataStore = new TestDataStore();

            testDataStore.GetFunction = (id) => {
                return(Task.FromResult <ISponsor>(null));
            };

            SponsorController   ControllerToTest = new SponsorController(testDataStore);
            HttpResponseMessage Actual           = ControllerToTest.Get(1).Result;

            Assert.IsNotNull(Actual);
            Assert.AreEqual(HttpStatusCode.NotFound, Actual.StatusCode);
        }
Esempio n. 25
0
        public void GetAllTest()
        {
            IList <ISponsor> Expected = new List <ISponsor>(2);

            Expected.Add(new TestSponsor {
                Id          = 1,
                DisplayName = "Test Sponsor",
                LogoLarge   = "Logo Large",
                LogoSmall   = "Logo Small",
                Website     = "Test Website",
                Level       = new TestSponsorLevel {
                    Id               = 1,
                    DisplayName      = "Test Sponsor Level",
                    DisplayOrder     = 1,
                    DisplayInEmails  = false,
                    DisplayInSidebar = false
                },
                EventId = DateTime.Now.Year
            });
            Expected.Add(new TestSponsor {
                Id          = 2,
                DisplayName = "Test Sponsor 2",
                LogoLarge   = "Logo Large 2",
                LogoSmall   = "Logo Small 2",
                Website     = "Test Website 2",
                Level       = new TestSponsorLevel {
                    Id               = 1,
                    DisplayName      = "Test Sponsor Level",
                    DisplayOrder     = 1,
                    DisplayInEmails  = false,
                    DisplayInSidebar = false
                },
                EventId = DateTime.Now.Year
            });

            TestDataStore testDataStore = new TestDataStore();

            testDataStore.GetAllFunction = () => {
                return(Task.FromResult <IList <ISponsor> >(Expected));
            };

            SponsorController   ControllerToTest = new SponsorController(testDataStore);
            HttpResponseMessage Actual           = ControllerToTest.Get().Result;

            Assert.IsNotNull(Actual);
            Assert.AreEqual(HttpStatusCode.OK, Actual.StatusCode);
            AssertSponorsAreEqual(Expected[0], Newtonsoft.Json.JsonConvert.DeserializeObject <List <Common.Sponsor> >(Actual.Content.ReadAsStringAsync().Result)[0]);
            AssertSponorsAreEqual(Expected[1], Newtonsoft.Json.JsonConvert.DeserializeObject <List <Common.Sponsor> >(Actual.Content.ReadAsStringAsync().Result)[1]);
        }
        private static IInternalDataStore GetFakeDataStore()
        {
            var fakeApiKey = ClientApiKeys.Builder()
                             .SetId("fake_api_key")
                             .SetSecret("fake_secret")
                             .Build();

            var stubClient = Clients.Builder()
                             .SetApiKey(fakeApiKey)
                             .Build();

            var fakeDataStore = TestDataStore.Create(
                requestExecutor: new StubRequestExecutor(FakeJson.Application, fakeApiKey).Object,
                client: stubClient);

            return(fakeDataStore);
        }
Esempio n. 27
0
        public void Init()
        {
            //manually set up the dataStore
            dataStore = new TestDataStore();

            tokenInfoObj = new OAuth2TokenInfo()
            {
                token       = tokenResponseObj,
                tokenString = tokenStringString
            };

            tokenResponseObj = new TokenResponse()
            {
                AccessToken = accessTokenString
            };

            clientSecretsObj = new ClientSecrets()
            {
                ClientId = clientIdString, ClientSecret = clientSecretString
            };

            domainUserObj = new OAuth2DomainUser()
            {
                clientSecrets = clientSecretsObj, domain = domainNameString, userName = userNameString
            };

            domainUserObj.tokenAndScopesByApi.Add(apiString, tokenInfoObj);

            domainObj = new OAuth2Domain()
            {
                defaultUser = userNameString
            };

            domainObj.users.Add(userNameString, domainUserObj);

            var internalInfo = new OAuth2Info()
            {
                defaultDomain = domainNameString, defaultClientSecrets = clientSecretsObj
            };

            internalInfo.domains.Add(domainNameString, domainObj);

            dataStore.internalInfo = internalInfo;

            consumer = new OAuth2InfoConsumer(dataStore);
        }
Esempio n. 28
0
        public async Task Trace_log_is_sent_to_logger()
        {
            var fakeLog    = new List <LogEntry>();
            var stubLogger = Substitute.For <ILogger>();

            stubLogger.When(x => x.Log(Arg.Any <LogEntry>())).Do(call =>
            {
                fakeLog.Add(call.Arg <LogEntry>());
            });

            var dataStore = TestDataStore.Create(new StubRequestExecutor(FakeJson.Account).Object, logger: stubLogger);

            var account = await dataStore.GetResourceAsync <IAccount>("account", CancellationToken.None);

            await account.DeleteAsync();

            fakeLog.Count.ShouldBeGreaterThanOrEqualTo(2);
        }
        public async Task When_getting_account()
        {
            var dataStore = TestDataStore.Create(new StubRequestExecutor(FakeJson.Account).Object);

            var accountResult = dataStore.InstantiateWithData <IAccountResult>(
                new Dictionary <string, object>()
            {
                ["account"] = new LinkProperty("https://foo.bar/account1")
            });

            var account = await accountResult.GetAccountAsync();

            account.FullName.ShouldBe("Han Solo");

            await dataStore.RequestExecutor.Received().ExecuteAsync(
                Arg.Is <IHttpRequest>(x => x.CanonicalUri.ToString() == "https://foo.bar/account1"),
                Arg.Any <CancellationToken>());
        }
Esempio n. 30
0
        public void GetAllTest_NotFound()
        {
            TestDataStore testDataStore = new TestDataStore();

            testDataStore.GetAllFunction = () => {
                return(Task.FromResult <IList <ISponsor> >(new List <ISponsor>()));
            };

            SponsorController   ControllerToTest = new SponsorController(testDataStore);
            HttpResponseMessage Actual           = ControllerToTest.Get().Result;

            Assert.IsNotNull(Actual);
            Assert.AreEqual(HttpStatusCode.OK, Actual.StatusCode);

            IList <Common.Sponsor> ReturnedList = Newtonsoft.Json.JsonConvert.DeserializeObject <List <Common.Sponsor> >(Actual.Content.ReadAsStringAsync().Result);

            Assert.AreEqual(0, ReturnedList.Count);
        }