コード例 #1
0
 public void PermissionOffer_WhenValid_TokenIsSet()
 {
     AsyncContext.Run(async() =>
     {
         var user            = await SyncTestHelpers.GetUser();
         var permissionOffer = await CreateOffer(user);
         Assert.That(permissionOffer.Status, Is.EqualTo(ManagementObjectStatus.Success));
         Assert.That(permissionOffer.Token, Is.Not.Null);
     });
 }
コード例 #2
0
        public void User_ApplyPermissions_WithUserId_GrantsAndRevokesPermissions()
        {
            AsyncContext.Run(async() =>
            {
                var alice = await SyncTestHelpers.GetUserAsync();
                var bob   = await SyncTestHelpers.GetUserAsync();

                await TestApplyPermissions(alice, bob, PermissionCondition.UserId(bob.Identity));
            });
        }
コード例 #3
0
        public void UserCurrent_WhenThereIsMoreThanOneUser_ShouldThrow()
        {
            AsyncContext.Run(async() =>
            {
                await SyncTestHelpers.GetFakeUserAsync();
                await SyncTestHelpers.GetFakeUserAsync();

                Assert.That(() => User.Current, Throws.TypeOf <RealmException>());
            });
        }
コード例 #4
0
        public void UserCurrent_WhenThereIsOneUser_ShouldReturnThatUser()
        {
            AsyncContext.Run(async() =>
            {
                var user        = await SyncTestHelpers.GetFakeUserAsync();
                var currentUser = User.Current;

                Assert.That(currentUser, Is.EqualTo(user));
            });
        }
コード例 #5
0
        public void UserLookup_WhenTargetUserDoesNotExist_ShouldReturnNull()
        {
            AsyncContext.Run(async() =>
            {
                var admin = await User.LoginAsync(SyncTestHelpers.AdminCredentials(), SyncTestHelpers.AuthServerUri);

                var lookupResponse = await admin.RetrieveInfoForUserAsync(Credentials.Provider.UsernamePassword, "something");
                Assert.That(lookupResponse, Is.Null);
            });
        }
コード例 #6
0
        public void DefaultConfiguration_WhenMoreThanOneUserLoggedIn_ShouldThrow()
        {
            AsyncContext.Run(async() =>
            {
                await SyncTestHelpers.GetFakeUserAsync();
                await SyncTestHelpers.GetFakeUserAsync();

                Assert.That(() => new QueryBasedSyncConfiguration(), Throws.TypeOf <ArgumentException>().And.Message.Contains("The user must be explicitly specified when the number of logged-in users is not 1."));
            });
        }
コード例 #7
0
        public void PermissionChange_IsProcessedByServer()
        {
            SyncTestHelpers.RequiresRos();

            AsyncContext.Run(async () =>
            {
                var user = await SyncTestHelpers.GetUserAsync();
                var permissionChange = await CreateChange(user, "*");
                Assert.That(permissionChange.Status, Is.EqualTo(ManagementObjectStatus.Success));
            });
        }
コード例 #8
0
 public void PermissionResponse_WhenTokenIsInvalid_ShouldGetError()
 {
     AsyncContext.Run(async() =>
     {
         var user = await SyncTestHelpers.GetUser();
         var permissionResponse = await CreateResponse(user, "Some string");
         Assert.That(permissionResponse.Status, Is.EqualTo(ManagementObjectStatus.Error));
         Assert.That(permissionResponse.ErrorCode, Is.EqualTo(ErrorCode.InvalidParameters));
         Assert.That(permissionResponse.StatusMessage, Is.Not.Null);
     });
 }
コード例 #9
0
        public void Test_RealmUpdate()
        {
            SyncTestHelpers.RequiresRos();

            AsyncContext.Run(async() =>
            {
                var userA = await SyncTestHelpers.GetUserAsync();
                var userB = await SyncTestHelpers.GetUserAsync();

                var realmUri = await CreateRealm(r =>
                {
                    CreatePermissions(RealmPermission.Get(r).Permissions);
                    var reader = PermissionRole.Get(r, "reader");
                    reader.Users.Add(userA);
                    reader.Users.Add(userB);

                    var writer = PermissionRole.Get(r, "writer");
                    writer.Users.Add(userA);
                });

                using (var realm = GetRealm(userA, realmUri))
                {
                    var subscription = await SubscribeToObjectsAsync(realm);
                    AssertRealmPrivileges(realm, RealmPrivileges.Read | RealmPrivileges.Update);
                    AssertClassPrivileges(realm, ClassPrivileges.Read | ClassPrivileges.Subscribe | ClassPrivileges.Create | ClassPrivileges.SetPermissions | ClassPrivileges.Update);
                    AssertObjectPrivileges(realm, ObjectPrivileges.Read | ObjectPrivileges.Delete | ObjectPrivileges.SetPermissions | ObjectPrivileges.Update);

                    Assert.That(subscription.Results.Count(), Is.EqualTo(3));
                    AddObjectsToRealm(realm, new[] { 4, 5, 6 });

                    Assert.That(subscription.Results.Count(), Is.EqualTo(6));

                    await WaitForSyncAsync(realm);
                    Assert.That(subscription.Results.Count(), Is.EqualTo(6));
                }

                using (var realm = GetRealm(userB, realmUri))
                {
                    var subscription = await SubscribeToObjectsAsync(realm);

                    AssertRealmPrivileges(realm, RealmPrivileges.Read);
                    AssertClassPrivileges(realm, ClassPrivileges.Read | ClassPrivileges.Subscribe);
                    AssertObjectPrivileges(realm, ObjectPrivileges.Read);

                    Assert.That(subscription.Results.Count(), Is.EqualTo(6));
                    AddObjectsToRealm(realm, new[] { 7, 8, 9 });

                    Assert.That(subscription.Results.Count(), Is.EqualTo(9));

                    await WaitForSyncAsync(realm);
                    Assert.That(subscription.Results.Count(), Is.EqualTo(6));
                }
            });
        }
コード例 #10
0
        public void User_AcceptPermissionOffer_WhenTokenIsInvalid_ShouldGetError()
        {
            AsyncContext.Run(async() =>
            {
                var user = await SyncTestHelpers.GetUserAsync();

                await AssertThrows <PermissionException>(() => user.AcceptPermissionOfferAsync("some string"), ex =>
                {
                    Assert.That(ex.ErrorCode, Is.EqualTo(ErrorCode.InvalidParameters));
                });
            });
        }
コード例 #11
0
        public void User_OfferPermissions_WhenExpired_ShouldThrow()
        {
            AsyncContext.Run(async() =>
            {
                var alice = await SyncTestHelpers.GetUserAsync();

                var realmUrl = SyncTestHelpers.RealmUri($"{alice.Identity}/testPermission").AbsoluteUri;
                EnsureRealmExists(alice, realmUrl);

                await AssertThrows <ArgumentException>(() => alice.OfferPermissionsAsync(realmUrl, AccessLevel.Write, DateTimeOffset.UtcNow.AddDays(-1)));
            });
        }
コード例 #12
0
        public void User_ApplyPermissions_WithEmail_GrantsAndRevokesPermissions()
        {
            AsyncContext.Run(async() =>
            {
                var alice          = await SyncTestHelpers.GetUserAsync();
                var bobEmail       = $"{Guid.NewGuid()}@foo.bar";
                var bobCredentials = Credentials.UsernamePassword(bobEmail, "a", createUser: true);
                var bob            = await User.LoginAsync(bobCredentials, SyncTestHelpers.AuthServerUri);

                await TestApplyPermissions(alice, bob, PermissionCondition.Email(bobEmail)).Timeout(10000);
            });
        }
コード例 #13
0
 public void TrustedCA_WhenFileDoesntExist_Throws()
 {
     AsyncContext.Run(async() =>
     {
         var user   = await SyncTestHelpers.GetUserAsync();
         var config = new SyncConfiguration(user, SyncTestHelpers.RealmUri("~/TrustedCA_WhenFileDoesntExist_Throws"))
         {
             TrustedCAPath = "something.pem"
         };
         Assert.That(() => GetRealm(config), Throws.TypeOf <FileNotFoundException>());
     });
 }
コード例 #14
0
        public void User_OfferPermissions_WhenNoAccess_ShouldThrow()
        {
            AsyncContext.Run(async() =>
            {
                var alice = await SyncTestHelpers.GetUser();

                var realmUrl = $"realm://{Constants.ServerUrl}/{alice.Identity}/testPermission";
                EnsureRealmExists(alice, realmUrl);

                await AssertThrows <ArgumentException>(() => alice.OfferPermissionsAsync(realmUrl, AccessLevel.None));
            });
        }
コード例 #15
0
 public void PermissionOffer_WhenExpired_ShouldGetError()
 {
     AsyncContext.Run(async() =>
     {
         var user            = await SyncTestHelpers.GetUser();
         var permissionOffer = await CreateOffer(user, expiresAt: DateTimeOffset.UtcNow.AddDays(-1));
         Assert.That(permissionOffer.Status, Is.EqualTo(ManagementObjectStatus.Error));
         Assert.That(permissionOffer.Token, Is.Null);
         Assert.That(permissionOffer.ErrorCode, Is.EqualTo(ErrorCode.ExpiredPermissionOffer));
         Assert.That(permissionOffer.StatusMessage, Is.Not.Null);
     });
 }
コード例 #16
0
        public void User_OfferPermissions_WhenNoAccess_ShouldThrow()
        {
            AsyncContext.Run(async() =>
            {
                var alice = await SyncTestHelpers.GetUserAsync();

                var realmUrl = SyncTestHelpers.RealmUri($"{alice.Identity}/testPermission").AbsoluteUri;
                EnsureRealmExists(alice, realmUrl);

                await AssertThrows <ArgumentException>(() => alice.OfferPermissionsAsync(realmUrl, AccessLevel.None));
            });
        }
コード例 #17
0
        public void DefaultConfiguration_WhenOneUserLoggedIn_ShouldWork(string userScheme, string realmScheme)
        {
            AsyncContext.Run(async() =>
            {
                await SyncTestHelpers.GetFakeUserAsync(scheme: userScheme);

                var config = new SyncConfiguration();
                Assert.That(config.IsPartial);
                Assert.That(config.ServerUri.Scheme, Is.EqualTo(realmScheme));
                Assert.That(config.ServerUri.Segments, Is.EqualTo(new[] { "/", "default" }));
            });
        }
コード例 #18
0
        public void Permission_ValidateWrite()
        {
            AsyncContext.Run(async() =>
            {
                var alice = await SyncTestHelpers.GetUser();
                var bob   = await SyncTestHelpers.GetUser();

                var realmUrl = await GrantPermissions(alice, bob);

                await ValidateWriteAndSync(realmUrl, alice, bob, 1, 2);
            });
        }
コード例 #19
0
        public void UserAllLoggedIn_WhenThereIsOneUser_ShouldReturnThatUser()
        {
            AsyncContext.Run(async() =>
            {
                var user = await SyncTestHelpers.GetFakeUserAsync();

                var users = User.AllLoggedIn;

                Assert.That(users.Length, Is.EqualTo(1));
                Assert.That(users[0], Is.EqualTo(user));
            });
        }
コード例 #20
0
        public void Realm_WhenCreatedWithSync1_ThrowsIncompatibleSyncedFileException(bool async, bool encrypt)
        {
            AsyncContext.Run(async() =>
            {
                var legacyRealmName = $"sync-1.x{(encrypt ? "-encrypted" : string.Empty)}.realm";
                var legacyRealmPath = TestHelpers.CopyBundledDatabaseToDocuments(legacyRealmName, Guid.NewGuid().ToString());
                var config          = await SyncTestHelpers.GetFakeConfigAsync("a@a", legacyRealmPath);
                if (encrypt)
                {
                    config.EncryptionKey = _sync1xEncryptionKey;
                }

                try
                {
                    if (async)
                    {
                        await GetRealmAsync(config);
                    }
                    else
                    {
                        GetRealm(config);
                    }

                    Assert.Fail("Expected IncompatibleSyncedFileException");
                }
                catch (IncompatibleSyncedFileException ex)
                {
                    var backupConfig = ex.GetBackupRealmConfig(encrypt ? _sync1xEncryptionKey : null);
                    using (var backupRealm = Realm.GetInstance(backupConfig))
                        using (var newRealm = GetRealm(config))
                        {
                            Assert.That(newRealm.All <Person>(), Is.Empty);

                            var backupPeopleQuery = backupRealm.All(nameof(Person));
                            Assert.That(backupPeopleQuery, Is.Not.Empty);

                            var backupPerson = backupPeopleQuery.First();
                            Assert.That(backupPerson.FirstName, Is.EqualTo("John"));
                            Assert.That(backupPerson.LastName, Is.EqualTo("Smith"));

                            newRealm.Write(() =>
                            {
                                newRealm.Add(new Person
                                {
                                    FirstName = backupPerson.FirstName,
                                    LastName  = backupPerson.LastName
                                });
                            });
                        }
                }
            });
        }
コード例 #21
0
        public void UserLogin_WhenAnonymous_LogsUserIn()
        {
            SyncTestHelpers.RequiresRos();

            AsyncContext.Run(async() =>
            {
                var credentials = Credentials.Anonymous();
                var user        = await User.LoginAsync(credentials, SyncTestHelpers.AuthServerUri);

                Assert.That(user, Is.Not.Null);
                Assert.That(user.Identity, Is.Not.Null);
            });
        }
コード例 #22
0
        private async Task<string> GrantPermissions(User granter, User receiver, bool mayRead = true, bool mayWrite = true, bool mayManage = false, string realmUrl = null)
        {
            var permissionOffer = await CreateOffer(granter, mayRead, mayWrite, mayManage, realmUrl: realmUrl);

            Assert.That(permissionOffer.Status, Is.EqualTo(ManagementObjectStatus.Success));
            Assert.That(permissionOffer.Token, Is.Not.Null);

            var permissionResponse = await CreateResponse(receiver, permissionOffer.Token);
            Assert.That(permissionResponse.Status, Is.EqualTo(ManagementObjectStatus.Success));
            Assert.That(permissionResponse.RealmUrl, Is.Not.Null);

            return SyncTestHelpers.RealmUri(permissionResponse.RealmUrl).AbsoluteUri;
        }
コード例 #23
0
        public void UserLogin_WhenAnonymousAndDifferentCredentials_ShouldLoginDifferentUser()
        {
            SyncTestHelpers.RequiresRos();

            AsyncContext.Run(async() =>
            {
                var first  = await User.LoginAsync(Credentials.Anonymous(), SyncTestHelpers.AuthServerUri);
                var second = await User.LoginAsync(Credentials.Anonymous(), SyncTestHelpers.AuthServerUri);

                Assert.That(first.Identity, Is.Not.EqualTo(second.Identity));
                Assert.That(User.AllLoggedIn.Length, Is.EqualTo(2));
            });
        }
コード例 #24
0
 public void Realm_GetSession_ShouldReturnSameObject()
 {
     AsyncContext.Run(async() =>
     {
         using (var realm = await SyncTestHelpers.GetFakeRealm(isUserAdmin: true))
         {
             var session1 = realm.GetSession();
             var session2 = realm.GetSession();
             Assert.That(session1, Is.EqualTo(session2));
             Assert.That(session1.GetHashCode(), Is.EqualTo(session2.GetHashCode()));
         }
     });
 }
コード例 #25
0
        public void UserLogin_WhenNickname_LogsUserIn()
        {
            SyncTestHelpers.RequiresRos();

            AsyncContext.Run(async() =>
            {
                var credentials = Credentials.Nickname(Guid.NewGuid().ToString());
                var user        = await User.LoginAsync(credentials, SyncTestHelpers.AuthServerUri);

                Assert.That(user, Is.Not.Null);
                Assert.That(user.Identity, Is.Not.Null);
            });
        }
コード例 #26
0
        public void GetInstance_WhenDynamicAndDoesntExist_ReturnsEmptySchema()
        {
            AsyncContext.Run(async() =>
            {
                var config       = await SyncTestHelpers.GetFakeConfigAsync();
                config.IsDynamic = true;

                using (var realm = GetRealm(config))
                {
                    Assert.That(realm.Schema, Is.Empty);
                }
            });
        }
コード例 #27
0
        public void UserLookup_WhenTargetUserIsSelf_ShouldReturnResponse()
        {
            AsyncContext.Run(async() =>
            {
                var admin = await User.LoginAsync(SyncTestHelpers.AdminCredentials(), SyncTestHelpers.AuthServerUri);

                var lookupResponse = await admin.RetrieveInfoForUserAsync(Credentials.Provider.UsernamePassword, Constants.AdminUsername);

                Assert.That(lookupResponse.Identity, Is.EqualTo(admin.Identity));
                Assert.That(lookupResponse.IsAdmin, Is.True);
                Assert.That(lookupResponse.Provider, Is.EqualTo(Credentials.Provider.UsernamePassword));
                Assert.That(lookupResponse.ProviderUserIdentity, Is.EqualTo(Constants.AdminUsername));
            });
        }
コード例 #28
0
ファイル: SessionTests.cs プロジェクト: vitors/realm-dotnet
        /// <summary>
        /// Opens a random realm and calls session.Stop(). It will assert state changes
        /// to Inactive.
        /// </summary>
        /// <returns>The stopped session.</returns>
        private async Task <Session> OpenRealmAndStopSession()
        {
            var config = await SyncTestHelpers.GetFakeConfigAsync();

            var realm   = GetRealm(config);
            var session = GetSession(realm);

            Assert.That(session.State, Is.EqualTo(SessionState.Active));

            session.Stop();
            Assert.That(session.State, Is.EqualTo(SessionState.Inactive));

            return(session);
        }
コード例 #29
0
        private async Task <Realm> GetSyncedRealm(Type objectType)
        {
            var credentials = Credentials.UsernamePassword(Constants.AdminUsername, Constants.AdminPassword, false);
            var user        = await User.LoginAsync(credentials, SyncTestHelpers.AuthServerUri);

            var configuration = new SyncConfiguration(user, SyncTestHelpers.RealmUri($"~/merge_by_pk_{objectType.Name}"), Guid.NewGuid().ToString())
            {
                ObjectClasses = new[] { objectType }
            };

            Realm.DeleteRealm(configuration);

            return(GetRealm(configuration));
        }
コード例 #30
0
        private async Task <Realm> GetPartialRealm(Action <SyncConfiguration> setupConfig = null, [CallerMemberName] string realmPath = null)
        {
            var user = await SyncTestHelpers.GetUserAsync();

            var config = new SyncConfiguration(user, SyncTestHelpers.RealmUri($"~/{realmPath}"), Guid.NewGuid().ToString())
            {
                ObjectClasses = new[] { typeof(ObjectA), typeof(ObjectB) }
            };

            setupConfig?.Invoke(config);

            using (var original = GetRealm(config))
            {
                original.Write(() =>
                {
                    for (var i = 0; i < 10; i++)
                    {
                        original.Add(new ObjectA
                        {
                            StringValue = "A #" + i,
                            IntValue    = i,
                            B           = new ObjectB
                            {
                                StringValue = "B #" + i,
                                BoolValue   = i % 2 == 0,
                            }
                        });
                    }
                });

                await GetSession(original).WaitForUploadAsync();
            }

            try
            {
                Realm.DeleteRealm(config);
            }
            catch
            {
            }

            config = new SyncConfiguration(config.User, config.ServerUri, config.DatabasePath + "_partial")
            {
                ObjectClasses = config.ObjectClasses,
                IsPartial     = true
            };

            return(GetRealm(config));
        }