public void GetInstance_WhenDynamic_ReadsSchemaFromDisk()
        {
            AsyncContext.Run(async() =>
            {
                var config           = await SyncTestHelpers.GetFakeConfigAsync();
                config.ObjectClasses = new[] { typeof(AllTypesObject) };

                // Create the realm and add some objects
                using (var realm = GetRealm(config))
                {
                    realm.Write(() => realm.Add(new AllTypesObject
                    {
                        Int32Property          = 42,
                        RequiredStringProperty = "This is required!"
                    }));
                }

                config.IsDynamic = true;

                using (var dynamicRealm = GetRealm(config))
                {
                    Assert.That(dynamicRealm.Schema.Count == 1);

                    var objectSchema = dynamicRealm.Schema.Find(nameof(AllTypesObject));
                    Assert.That(objectSchema, Is.Not.Null);

                    var hasExpectedProp = objectSchema.TryFindProperty(nameof(AllTypesObject.RequiredStringProperty), out var requiredStringProp);
                    Assert.That(hasExpectedProp);
                    Assert.That(requiredStringProp.Type, Is.EqualTo(PropertyType.String));

                    var ato = dynamicRealm.All(nameof(AllTypesObject)).Single();
                    Assert.That(ato.RequiredStringProperty, Is.EqualTo("This is required!"));
                }
            });
        }
Esempio n. 2
0
        public void Session_ProgressObservable_WhenModeIsForOutstandingWork_CallsOnCompleted()
        {
            AsyncContext.Run(async() =>
            {
                var config  = await SyncTestHelpers.GetFakeConfigAsync();
                var realm   = GetRealm(config);
                var session = GetSession(realm);

                session.SimulateProgress(0, 100, 0, 0);

                var observable = session.GetProgressObservable(ProgressDirection.Download, ProgressMode.ForCurrentlyOutstandingWork);

                var task = Task.Run(() =>
                {
                    return(observable.Wait());
                });

                session.SimulateProgress(50, 100, 0, 0);

                await Task.Delay(50);

                session.SimulateProgress(100, 100, 0, 0);

                var progress = await task.Timeout(500);

                Assert.That(progress.TransferredBytes, Is.EqualTo(100));
                Assert.That(progress.TransferableBytes, Is.EqualTo(100));
            });
        }
Esempio n. 3
0
        public void Session_Error_WhenInvalidAccessToken()
        {
            AsyncContext.Run(async() =>
            {
                var errors = new List <Exception>();
                var config = await SyncTestHelpers.GetFakeConfigAsync();
                using (var realm = GetRealm(config))
                {
                    EventHandler <Realms.ErrorEventArgs> handler = null;
                    handler = new EventHandler <Realms.ErrorEventArgs>((sender, e) =>
                    {
                        errors.Add(e.Exception);
                        CleanupOnTearDown((Session)sender);
                    });

                    Session.Error += handler;

                    while (!errors.Any())
                    {
                        await Task.Yield();
                    }

                    Session.Error -= handler;

                    var sessionErrors = errors.OfType <SessionException>().ToArray();
                    Assert.That(sessionErrors.Count, Is.EqualTo(1));
                    Assert.That(sessionErrors[0].ErrorCode, Is.EqualTo(ErrorCode.BadUserAuthentication));
                }
            });
        }
Esempio n. 4
0
        public void Session_DivergingHistories_ShouldRaiseClientResetException()
        {
            AsyncContext.Run(async() =>
            {
                var config = await SyncTestHelpers.GetFakeConfigAsync();
                ClientResetException error = null;
                using (var realm = GetRealm(config))
                {
                    var session = GetSession(realm);

                    var result = await SyncTestHelpers.SimulateSessionErrorAsync <ClientResetException>(session,
                                                                                                        ErrorCode.DivergingHistories,
                                                                                                        "Fake client reset is required");
                    CleanupOnTearDown(result.Item1);

                    error = result.Item2;
                }

                Assert.That(error.BackupFilePath, Is.Not.Null);
                Assert.That(error.BackupFilePath, Does.Contain(Path.Combine("io.realm.object-server-recovered-realms", "recovered_realm")));
                Assert.That(File.Exists(error.BackupFilePath), Is.False);

                var clientResetSuccess = error.InitiateClientReset();

                Assert.That(clientResetSuccess, Is.True);
                Assert.That(File.Exists(error.BackupFilePath), Is.True);
            });
        }
Esempio n. 5
0
        public void Session_RXThrottleTests()
        {
            AsyncContext.Run(async() =>
            {
                const int ThrottleInterval = 100; // In ms
                const int SafeDelay        = 2 * ThrottleInterval;

                var config  = await SyncTestHelpers.GetFakeConfigAsync();
                var realm   = GetRealm(config);
                var session = GetSession(realm);

                var callbacksInvoked = 0;

                var uploadProgress = session.GetProgressObservable(ProgressDirection.Download, ProgressMode.ReportIndefinitely);

                session.SimulateProgress(0, 100, 0, 0);

                var token = uploadProgress.Throttle(TimeSpan.FromMilliseconds(ThrottleInterval))
                            .Subscribe(p =>
                {
                    callbacksInvoked++;
                });

                using (token)
                {
                    await Task.Delay(SafeDelay);
                    Assert.That(callbacksInvoked, Is.EqualTo(1));

                    for (ulong i = 0; i < 10; i++)
                    {
                        session.SimulateProgress(i, 100, 0, 0);
                    }

                    await Task.Delay(SafeDelay);
                    Assert.That(callbacksInvoked, Is.EqualTo(2));

                    for (ulong i = 10; i < 20; i++)
                    {
                        session.SimulateProgress(i, 100, 0, 0);
                        await Task.Delay(ThrottleInterval / 10);
                    }

                    Assert.That(callbacksInvoked, Is.EqualTo(2));
                    await Task.Delay(SafeDelay);
                    Assert.That(callbacksInvoked, Is.EqualTo(3));

                    for (ulong i = 20; i < 25; i++)
                    {
                        session.SimulateProgress(i, 100, 0, 0);
                        await Task.Delay(SafeDelay);
                    }

                    Assert.That(callbacksInvoked, Is.EqualTo(8));
                }
            });
        }
Esempio n. 6
0
        public void Session_RXCombineLatestTests()
        {
            AsyncContext.Run(async() =>
            {
                var config  = await SyncTestHelpers.GetFakeConfigAsync();
                var realm   = GetRealm(config);
                var session = GetSession(realm);

                var callbacksInvoked = 0;
                var completionTCS    = new TaskCompletionSource <ulong>();

                var uploadProgress   = session.GetProgressObservable(ProgressDirection.Upload, ProgressMode.ReportIndefinitely);
                var downloadProgress = session.GetProgressObservable(ProgressDirection.Download, ProgressMode.ReportIndefinitely);

                session.SimulateProgress(0, 100, 0, 100);
                var token = uploadProgress.CombineLatest(downloadProgress, (upload, download) =>
                {
                    return(new
                    {
                        TotalTransferred = upload.TransferredBytes + download.TransferredBytes,
                        TotalTransferable = upload.TransferableBytes + download.TransferableBytes
                    });
                })
                            .Subscribe(progress =>
                {
                    callbacksInvoked++;
                    if (progress.TotalTransferred == progress.TotalTransferable)
                    {
                        completionTCS.TrySetResult(progress.TotalTransferred);
                    }
                });

                using (token)
                {
                    await Task.Delay(50);
                    session.SimulateProgress(50, 100, 0, 100);

                    await Task.Delay(50);
                    session.SimulateProgress(100, 100, 0, 100);

                    await Task.Delay(50);
                    session.SimulateProgress(100, 150, 0, 100);

                    await Task.Delay(50);
                    session.SimulateProgress(100, 150, 100, 100);

                    await Task.Delay(50);
                    session.SimulateProgress(150, 150, 100, 100);

                    var totalTransferred = await completionTCS.Task;

                    Assert.That(callbacksInvoked, Is.GreaterThanOrEqualTo(6));
                    Assert.That(totalTransferred, Is.EqualTo(250));
                }
            });
        }
        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
                                });
                            });
                        }
                }
            });
        }
        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);
                }
            });
        }
Esempio n. 9
0
        /// <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);
        }
Esempio n. 10
0
        public void Realm_GetSession_ShouldReturnSameObject()
        {
            AsyncContext.Run(async() =>
            {
                var config = await SyncTestHelpers.GetFakeConfigAsync();
                using (var realm = GetRealm(config))
                {
                    var session1 = GetSession(realm);
                    var session2 = GetSession(realm);

                    Assert.That(session1, Is.EqualTo(session2));
                    Assert.That(session1.GetHashCode(), Is.EqualTo(session2.GetHashCode()));
                }
            });
        }
Esempio n. 11
0
        public void Session_GetUser_WhenInvalidSession_ShouldNotThrow()
        {
            AsyncContext.Run(async() =>
            {
                var config = await SyncTestHelpers.GetFakeConfigAsync();
                using (var realm = GetRealm(config))
                {
                    var session = GetSession(realm);

                    session.SimulateError(ErrorCode.BadUserAuthentication, "some error", isFatal: true);

                    var counter = 0;
                    while (session.State != SessionState.Invalid)
                    {
                        await Task.Delay(100);
                        Assert.That(counter++ < 5);
                    }

                    Assert.That(() => session.User, Is.Null);
                }
            });
        }
Esempio n. 12
0
        public void Session_Error_ShouldPassCorrectSession()
        {
            AsyncContext.Run(async() =>
            {
                var config = await SyncTestHelpers.GetFakeConfigAsync();
                using (var realm = GetRealm(config))
                {
                    var session = GetSession(realm);

                    const ErrorCode code = (ErrorCode)102;
                    const string message = "Some fake error has occurred";

                    var result = await SyncTestHelpers.SimulateSessionErrorAsync <SessionException>(session, code, message);
                    CleanupOnTearDown(result.Item1);

                    var error = result.Item2;
                    Assert.That(error.Message, Is.EqualTo(message));
                    Assert.That(error.ErrorCode, Is.EqualTo(code));

                    var errorSession = result.Item1;
                    Assert.That(errorSession.ServerUri, Is.EqualTo(((SyncConfigurationBase)realm.Config).ServerUri));
                }
            });
        }
Esempio n. 13
0
        public void Session_ProgressObservable_UnitTests(ProgressDirection direction, ProgressMode mode)
        {
            AsyncContext.Run(async() =>
            {
                var callbacksInvoked = 0;
                var completionTCS    = new TaskCompletionSource <ulong>();

                var config  = await SyncTestHelpers.GetFakeConfigAsync();
                var realm   = GetRealm(config);
                var session = GetSession(realm);

                session.SimulateProgress(0, 100, 0, 100);

                var observable = session.GetProgressObservable(direction, mode);
                var token      = observable.Subscribe(p =>
                {
                    try
                    {
                        callbacksInvoked++;

                        // .NET Core dislikes asserts in the callback so much it crashes.
                        if (p.TransferredBytes > p.TransferableBytes)
                        {
                            throw new Exception("TransferredBytes must be less than or equal to TransferableBytes");
                        }

                        if (mode == ProgressMode.ForCurrentlyOutstandingWork)
                        {
                            if (p.TransferableBytes != 100)
                            {
                                throw new Exception("TransferableBytes must be equal to 100");
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        completionTCS.TrySetException(e);
                    }

                    if (p.TransferredBytes == p.TransferableBytes)
                    {
                        completionTCS.TrySetResult(p.TransferredBytes);
                    }
                });

                using (token)
                {
                    session.SimulateProgress(50, 150, 50, 150);
                    await Task.Delay(50);

                    session.SimulateProgress(100, 200, 100, 200);
                    await Task.Delay(50);

                    session.SimulateProgress(150, 200, 150, 200);
                    await Task.Delay(50);

                    session.SimulateProgress(200, 200, 200, 200);
                    await Task.Delay(50);

                    var totalTransferred = await completionTCS.Task;

                    if (mode == ProgressMode.ForCurrentlyOutstandingWork)
                    {
                        Assert.That(totalTransferred, Is.EqualTo(100));
                        Assert.That(callbacksInvoked, Is.EqualTo(3));
                    }
                    else
                    {
                        Assert.That(totalTransferred, Is.EqualTo(200));
                        Assert.That(callbacksInvoked, Is.EqualTo(5));
                    }
                }
            });
        }