public void NItemFeed(int N)
        {
            var feed = Feed();

            AddItemRange(feed, 1, N, 1);

            Instant retrieveTime = Instant.FromUnixTimeSeconds(12345678);

            system.ProcessRawContent(ToContent(feed, retrieveTime));

            for (int i = 1; i <= N; ++i)
            {
                var doc = system.UnprocessedDocumentRepository.GetBySourceId(ItemId(i)).First();
                AssertDocumentIsCorrect(doc, i, 1, retrieveTime);
            }
        }
        /// <summary>
        /// Converts a Noda Time <see cref="Instant"/> to a Protobuf <see cref="Timestamp"/>.
        /// </summary>
        /// <remarks>
        /// Noda Time has a wider range of valid instants than Protobuf timestamps; instants before 0001-01-01 CE
        /// are out of range.
        /// </remarks>
        /// <param name="instant">The instant to convert.</param>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="instant"/> represents an instant
        /// which is invalid in <see cref="Timestamp"/>.</exception>
        /// <returns>The Protobuf representation.</returns>
        public static Timestamp ToTimestamp(this Instant instant)
        {
            if (instant < NodaConstants.BclEpoch)
            {
                throw new ArgumentOutOfRangeException(nameof(instant), "Instant is outside the range of Valid Protobuf timestamps");
            }
            // Truncated towards the start of time, which is what we want...
            var seconds   = instant.ToUnixTimeSeconds();
            var remainder = instant - Instant.FromUnixTimeSeconds(seconds);

            // NanosecondOfDay is probably the most efficient way of turning a small, subsecond, non-negative duration
            // into a number of nanoseconds...
            return(new Timestamp {
                Seconds = seconds, Nanos = (int)remainder.NanosecondOfDay
            });
        }
Example #3
0
        public void TestLogging()
        {
            EventHandlers eventHandlers =
                EventHandlers.CreateBuilder().Add <TimerEvent>(timerEventQueue.Enqueue).Build();

            Mock.Get(mockClock).Setup(m => m.GetCurrentInstant()).Returns(Instant.FromUnixTimeSeconds(0));

            using (TimerEventDispatcher parentTimerEventDispatcher =
                       new TimerEventDispatcher(eventHandlers, "description", mockClock, null))
            {
                Mock.Get(mockClock).Setup(m => m.GetCurrentInstant()).Returns(Instant.FromUnixTimeSeconds(0) + Duration.FromMilliseconds(1));

                parentTimerEventDispatcher.Lap();
                Mock.Get(mockClock).Setup(m => m.GetCurrentInstant()).Returns((Instant.FromUnixTimeSeconds(0) + Duration.FromMilliseconds(1)).PlusNanoseconds(1));

                using (TimerEventDispatcher ignored =
                           parentTimerEventDispatcher.SubTimer("child description"))
                {
                    Mock.Get(mockClock).Setup(m => m.GetCurrentInstant()).Returns(Instant.FromUnixTimeSeconds(0) + Duration.FromMilliseconds(2));

                    // Laps on close.
                }
            }

            TimerEvent timerEvent = GetNextTimerEvent();

            VerifyStartState(timerEvent);
            VerifyDescription(timerEvent, "description");

            timerEvent = GetNextTimerEvent();
            VerifyStateFirstLap(timerEvent, State.LAP);
            VerifyDescription(timerEvent, "description");

            timerEvent = GetNextTimerEvent();
            VerifyStartState(timerEvent);
            VerifyDescription(timerEvent, "child description");

            timerEvent = GetNextTimerEvent();
            VerifyStateFirstLap(timerEvent, State.FINISHED);
            VerifyDescription(timerEvent, "child description");

            timerEvent = GetNextTimerEvent();
            VerifyStateNotFirstLap(timerEvent, State.FINISHED);
            VerifyDescription(timerEvent, "description");

            Assert.IsTrue(timerEventQueue.Count == 0);
        }
        private void Should_enrich_with_default_values()
        {
            var now = Instant.FromUnixTimeSeconds(SystemClock.Instance.GetCurrentInstant().ToUnixTimeSeconds());

            var schema =
                Schema.Create("my-schema", new SchemaProperties())
                .AddOrUpdateField(new JsonField(1, "my-json",
                                                new JsonFieldProperties()))
                .AddOrUpdateField(new StringField(2, "my-string",
                                                  new StringFieldProperties {
                DefaultValue = "EN-String", IsLocalizable = true
            }))
                .AddOrUpdateField(new NumberField(3, "my-number",
                                                  new NumberFieldProperties {
                DefaultValue = 123
            }))
                .AddOrUpdateField(new BooleanField(4, "my-boolean",
                                                   new BooleanFieldProperties {
                DefaultValue = true
            }))
                .AddOrUpdateField(new DateTimeField(5, "my-datetime",
                                                    new DateTimeFieldProperties {
                DefaultValue = now
            }))
                .AddOrUpdateField(new GeolocationField(6, "my-geolocation",
                                                       new GeolocationFieldProperties()));

            var data =
                new ContentData()
                .AddField("my-string",
                          new ContentFieldData()
                          .AddValue("de", "DE-String"))
                .AddField("my-number",
                          new ContentFieldData()
                          .AddValue("iv", 456));

            data.Enrich(schema, languages);

            Assert.Equal(456, (int)data["my-number"]["iv"]);

            Assert.Equal("DE-String", (string)data["my-string"]["de"]);
            Assert.Equal("EN-String", (string)data["my-string"]["en"]);

            Assert.Equal(now, InstantPattern.General.Parse((string)data["my-datetime"]["iv"]).Value);

            Assert.Equal(true, (bool)data["my-boolean"]["iv"]);
        }
Example #5
0
        public static object UnixSecondsToTime(long unixSeconds, string timezoneName = "")
        {
            if (unixSeconds < 0)
            {
                return("Invalid unixSeconds.");
            }
            Instant      instant = Instant.FromUnixTimeSeconds(unixSeconds); // utc
            DateTimeZone tz      = (string.IsNullOrWhiteSpace(timezoneName)) ? SystemTimeZone : DateTimeZoneProviders.Tzdb.GetZoneOrNull(timezoneName);

            if (tz == null)
            {
                return($"Invalid timezone: {timezoneName}.");
            }
            ZonedDateTime zdt = instant.InZone(tz);

            return(zdt.ToDateTimeUnspecified());
        }
Example #6
0
        public async Task recording_user_updates_last_active_at()
        {
            UserRepo userRepo = CreateUserRepo();
            // given
            Instant t1         = Instant.FromUnixTimeSeconds(0);
            Instant t2         = Instant.FromUnixTimeSeconds(1);
            var     userInfoT1 = new UserInfo("123", "X", "x", null, updatedAt: t1);
            var     userInfoT2 = new UserInfo("123", "X", "x", null, updatedAt: t2);

            // when, then
            User userT1 = await userRepo.RecordUser(userInfoT1);

            Assert.AreEqual(t1, userT1.LastActiveAt);
            User userT2 = await userRepo.RecordUser(userInfoT2);

            Assert.AreEqual(t2, userT2.LastActiveAt);
        }
Example #7
0
 private static User MockUser(
     string name = "user",
     int pokeyen = 0,
     int tokens  = 0,
     string?twitchDisplayName = null,
     int?pokeyenBetRank       = null,
     bool glowColorUnlocked   = false,
     SortedSet <int>?emblems  = null
     ) => new User(
     id: Guid.NewGuid().ToString(),
     name: name, twitchDisplayName: twitchDisplayName ?? "☺" + name, simpleName: name.ToLower(), color: null,
     firstActiveAt: Instant.FromUnixTimeSeconds(0),
     lastActiveAt: Instant.FromUnixTimeSeconds(0),
     lastMessageAt: null,
     pokeyen: pokeyen, tokens: tokens,
     pokeyenBetRank: pokeyenBetRank, glowColorUnlocked: glowColorUnlocked,
     participationEmblems: emblems);
Example #8
0
 private UnprocessedDocument TestDocumentWithUpdateTime(int index, Instant?UpdateTime, Guid?Id = null)
 {
     return(new UnprocessedDocument
            (
                Id: Id != null ? Id.Value : TestId(index),
                Uri: $"http://example.com/{index}",
                SourceId: $"{index}",
                RetrieveTime: Instant.FromUnixTimeSeconds(1000000 + index),
                UpdateTime: UpdateTime,
                PublishTime: Instant.FromUnixTimeSeconds(3000000 + index),
                Content: new UnprocessedAtomContent(Title: new AtomTextConstruct("text", $"Title {index}"), Content: $"Content {index}", Categories: Categories(index), Links: Links(index)),
                Authors: new List <UnprocessedDocumentAuthor> {
         new UnprocessedDocumentAuthor($"Author {index}", $"Context {index}")
     },
                SourceRawContentId: Guid.Parse("00000000-0000-0000-0000-000000001234")
            ));
 }
Example #9
0
        public async Task TestUserParser()
        {
            const string username    = "******";
            const string displayName = "名前";
            var          origUser    = new User(
                id: "1234567890", name: username, twitchDisplayName: displayName, simpleName: username,
                color: null,
                firstActiveAt: Instant.FromUnixTimeSeconds(0), lastActiveAt: Instant.FromUnixTimeSeconds(0),
                lastMessageAt: null, pokeyen: 0, tokens: 0);
            var userRepoMock = new Mock <IUserRepo>();

            userRepoMock
            .Setup(r => r.FindBySimpleName(username))
            .ReturnsAsync(origUser);
            userRepoMock
            .Setup(r => r.FindByDisplayName(displayName))
            .ReturnsAsync(origUser);
            var argsParser = new ArgsParser();

            argsParser.AddArgumentParser(new UserParser(userRepoMock.Object));

            var resultUser = await argsParser.Parse <User>(args : ImmutableList.Create(username));

            Assert.That(resultUser, Is.EqualTo(origUser));
            var resultUserPrefixed = await argsParser.Parse <User>(args : ImmutableList.Create('@' + username));

            Assert.That(resultUserPrefixed, Is.EqualTo(origUser));
            var resultUserDisplayName = await argsParser.Parse <User>(args : ImmutableList.Create(displayName));

            Assert.That(resultUserDisplayName, Is.EqualTo(origUser));

            ArgsParseFailure ex = Assert.ThrowsAsync <ArgsParseFailure>(() => argsParser
                                                                        .Parse <User>(args: ImmutableList.Create("some_unknown_name"))) !;

            Assert.That(ex.Message, Is.EqualTo("did not recognize a user with the name 'some_unknown_name'"));
            ArgsParseFailure exUserPrefixed = Assert.ThrowsAsync <ArgsParseFailure>(() => argsParser
                                                                                    .Parse <User>(args: ImmutableList.Create("@some_unknown_name"))) !;

            Assert.That(exUserPrefixed.Message,
                        Is.EqualTo("did not recognize a user with the name 'some_unknown_name'"));
            ArgsParseFailure exDisplayName = Assert.ThrowsAsync <ArgsParseFailure>(() => argsParser
                                                                                   .Parse <User>(args: ImmutableList.Create("なまえ"))) !;

            Assert.That(exDisplayName.Message, Is.EqualTo("did not recognize a user with the name 'なまえ'"));
        }
        public void StoringRawContentDoesNotTrimWhitespace()
        {
            var content = new RawContent
                          (
                Id: TestId(1),
                RetrieveTime: Instant.FromUnixTimeSeconds(12345678),
                Type: "Type 1",
                Content: "Content with trailing newlines\n\n",
                Context: "Context 1",
                SourceUri: "http://example.com/atom-1.xml"
                          );

            repository.AddRawContent(content);

            var contentInRepository = repository.GetAllRawContent().First();

            AssertRawContentIsIdentical(content, contentInRepository);
        }
        private void Should_also_enrich_with_default_values_when_string_is_empty()
        {
            var now = Instant.FromUnixTimeSeconds(SystemClock.Instance.GetCurrentInstant().ToUnixTimeSeconds());

            var data =
                new NamedContentData()
                .AddField("my-string",
                          new ContentFieldData()
                          .AddValue("de", string.Empty))
                .AddField("my-number",
                          new ContentFieldData()
                          .AddValue("iv", 456));

            data.Enrich(schema, languagesConfig.ToResolver());

            Assert.Equal("en-string", (string)data["my-string"]["de"]);
            Assert.Equal("en-string", (string)data["my-string"]["en"]);
        }
        //[TestCase(1000)]
        public void OverlappingTenItemFeedsUpToItemN(int N)
        {
            Instant retrieveTime = Instant.FromUnixTimeSeconds(12345678);

            for (int max = 10; max <= N; ++max)
            {
                var feed = Feed();
                AddItemRange(feed, max - 10 + 1, max, 1);

                system.ProcessRawContent(ToContent(feed, retrieveTime));
            }

            for (int i = 1; i <= N; ++i)
            {
                var doc = system.UnprocessedDocumentRepository.GetBySourceId(ItemId(i)).First();
                AssertDocumentIsCorrect(doc, i, 1, retrieveTime);
            }
        }
Example #13
0
        public void TestGlobalCooldown()
        {
            Instant t1        = Instant.FromUnixTimeSeconds(1);
            Instant t2        = Instant.FromUnixTimeSeconds(2);
            Instant t3        = Instant.FromUnixTimeSeconds(3);
            var     clockMock = new Mock <IClock>();
            var     cooldown  = new GlobalCooldown(clockMock.Object, Duration.FromSeconds(2));

            clockMock.Setup(clock => clock.GetCurrentInstant()).Returns(t1);
            Assert.IsTrue(cooldown.CheckLapsedThenReset());
            Assert.IsFalse(cooldown.CheckLapsedThenReset());

            clockMock.Setup(clock => clock.GetCurrentInstant()).Returns(t2);
            Assert.IsFalse(cooldown.CheckLapsedThenReset());

            clockMock.Setup(clock => clock.GetCurrentInstant()).Returns(t3);
            Assert.IsTrue(cooldown.CheckLapsedThenReset());
            Assert.IsFalse(cooldown.CheckLapsedThenReset());
        }
        public async Task set_subscription_info()
        {
            IUserRepo userRepo = new UserRepo(CreateTemporaryDatabase(), 0, 0, ImmutableList <string> .Empty);

            User userBeforeUpdate = await userRepo.RecordUser(new UserInfo("123", "X", "x"));

            Assert.That(userBeforeUpdate.MonthsSubscribed, Is.EqualTo(0));
            Assert.IsNull(userBeforeUpdate.SubscriptionTier);
            Assert.That(userBeforeUpdate.LoyaltyLeague, Is.EqualTo(0));
            Assert.IsNull(userBeforeUpdate.SubscriptionUpdatedAt);

            User userAfterUpdate = await userRepo.SetSubscriptionInfo(userBeforeUpdate,
                                                                      42, SubscriptionTier.Tier2, 10, Instant.FromUnixTimeSeconds(123));

            Assert.That(userAfterUpdate.MonthsSubscribed, Is.EqualTo(42));
            Assert.That(userAfterUpdate.SubscriptionTier, Is.EqualTo(SubscriptionTier.Tier2));
            Assert.That(userAfterUpdate.LoyaltyLeague, Is.EqualTo(10));
            Assert.That(userAfterUpdate.SubscriptionUpdatedAt, Is.EqualTo(Instant.FromUnixTimeSeconds(123)));
        }
Example #15
0
        public void Should_serialize_and_deserialize()
        {
            var time = Instant.FromUnixTimeSeconds(SystemClock.Instance.GetCurrentInstant().ToUnixTimeSeconds());

            bag.Set("Key1", time);
            bag.Set("Key2", "MyString");
            bag.Set("Key3", 123L);
            bag.Set("Key4", true);
            bag.Set("Key5", Guid.NewGuid());

            var output = bag.SerializeAndDeserializeAndReturn(new PropertiesBagConverter <PropertiesBag>());

            foreach (var kvp in output.Properties.Take(4))
            {
                Assert.Equal(kvp.Value.RawValue, bag[kvp.Key].RawValue);
            }

            Assert.Equal(bag["Key5"].ToGuid(c), output["Key5"].ToGuid(c));
        }
Example #16
0
            public void ignores_different_messages()
            {
                Mock <IClock> clockMock = new();
                CopypastaRule rule      = new(clockMock.Object, Duration.FromSeconds(10));

                const string copypasta1 =
                    "What the f**k did you just f*****g say about me, you little bitch? I'll have you know I graduated top of my class in the Navy Seals, and I've been involved in numerous secret raids on Al-Quaeda, and I have over 300 confirmed kills.";
                const string copypasta2 =
                    "Welch eynen verschissenen Unfug schicktest du dich zur Hölle nochmal an, über das heilige römische Reych in die Welt herauszuthragen, du Lustknabe? Seyd drumb in Kennthnisz gesetzet, dass min threue Sünderseele meynes Gewalthauvns besther Landsknecht gewesen und an Schwerthzügen gegen holländische Rebellen meynen Theil trug, derer nicht nur zahlreych, sondern auch occulter Natura waren.";

                clockMock.Setup(c => c.GetCurrentInstant()).Returns(Instant.FromUnixTimeSeconds(0));
                RuleResult resultFirstSeen = rule.Check(TextMessage(copypasta1));

                Assert.IsInstanceOf <RuleResult.Nothing>(resultFirstSeen);

                clockMock.Setup(c => c.GetCurrentInstant()).Returns(Instant.FromUnixTimeSeconds(5));
                RuleResult resultSimilarCopypasted = rule.Check(TextMessage(copypasta2));

                Assert.IsInstanceOf <RuleResult.Nothing>(resultSimilarCopypasted);
            }
        public Tuple <string, string, string, string, string, bool> GetZoneDateTime(string timeZone, long currentTime = 0, long sunrise = 0, long sunset = 0)
        {
            var instant = Instant.FromUnixTimeSeconds(currentTime);
            //var now = SystemClock.Instance.GetCurrentInstant();

            var dtzi          = DateTimeZoneProviders.Tzdb;
            var timeZoneToken = dtzi[timeZone];

            var zoneDateTime = new ZonedDateTime(instant, timeZoneToken);

            var displayDay   = zoneDateTime.Date.DayOfWeek.ToString();
            var displayMonth = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(zoneDateTime.LocalDateTime.ToDateTimeUnspecified().Month);
            var displayDate  = zoneDateTime.Date.Day.ToString();
            var displayYear  = zoneDateTime.Date.Year.ToString();
            var displayTime  = zoneDateTime.LocalDateTime.ToDateTimeUnspecified().ToShortTimeString();

            bool isDaytime = currentTime > sunrise && currentTime < sunset;

            return(Tuple.Create(displayDay, displayMonth, displayDate, displayYear, displayTime, isDaytime));
        }
Example #18
0
        /// <summary>
        /// Converts a Protobuf <see cref="Timestamp"/> to a Noda Time <see cref="Instant"/>.
        /// </summary>
        /// <remarks>
        /// Every valid Protobuf timestamp can be represented in Noda Time without loss of information.
        /// </remarks>
        /// <param name="timestamp">The timestamp to convert. Must not be null.</param>
        /// <exception cref="ArgumentException"><paramref name="timestamp"/> represents an invalid timestamp.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="timestamp"/> is null.</exception>
        /// <returns>The Noda Time representation.</returns>
        public static Instant ToInstant(this Timestamp timestamp)
        {
            Preconditions.CheckNotNull(timestamp, nameof(timestamp));
            long seconds = timestamp.Seconds;
            long nanos   = timestamp.Nanos;

            Preconditions.CheckArgument(
                seconds >= MinValidTimestampSeconds &&
                seconds <= MaxValidTimestampSeconds,
                nameof(timestamp),
                "timestamp.Seconds out of range {0}",
                seconds);
            Preconditions.CheckArgument(
                nanos >= 0 &&
                nanos < ProtobufDuration.NanosecondsPerSecond,
                nameof(timestamp),
                "timestamp.Nanos out of range: {0}",
                nanos);
            return(Instant.FromUnixTimeSeconds(seconds).PlusNanoseconds(nanos));
        }
Example #19
0
            public void detects_similar_copypasta()
            {
                Mock <IClock> clockMock = new();
                CopypastaRule rule      = new(clockMock.Object, Duration.FromSeconds(10));

                const string copypasta1 =
                    "What the *** did you just *** type about me, you little bitch? I’ll have you know I graduated top of my class at MIT, and I’ve been involved in numerous secret raids with Anonymous, and I have over 300 confirmed DDoSes.";
                const string copypasta2 =
                    "What the f**k did you just f*****g say about me, you little bitch? I'll have you know I graduated top of my class in the Navy Seals, and I've been involved in numerous secret raids on Al-Quaeda, and I have over 300 confirmed kills.";

                clockMock.Setup(c => c.GetCurrentInstant()).Returns(Instant.FromUnixTimeSeconds(0));
                RuleResult resultFirstSeen = rule.Check(TextMessage(copypasta1));

                Assert.IsInstanceOf <RuleResult.Nothing>(resultFirstSeen);

                clockMock.Setup(c => c.GetCurrentInstant()).Returns(Instant.FromUnixTimeSeconds(5));
                RuleResult resultSimilarCopypasted = rule.Check(TextMessage(copypasta2));

                Assert.IsInstanceOf <RuleResult.GivePoints>(resultSimilarCopypasted);
            }
Example #20
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.UseHiLo();
            modelBuilder.HasPostgresEnum <Summary>();
            modelBuilder.HasPostgresEnum <Context>();
            modelBuilder.Entity <WeatherForecast>()
            .Property(t => t.CreationTime)
            .HasConversion(
                c => c.ToDateTimeOffset(),
                c => Timestamp.FromDateTimeOffset(c)
                )
            ;

            modelBuilder.Entity <WeatherForecast>()
            .Property(t => t.Date)
            .HasConversion(
                c => c.ToInstant().ToUnixTimeSeconds(),
                c => Instant.FromUnixTimeSeconds(c).ToTimestamp()
                )
            ;
        }
        public async Task TestGenerateSelector_fileModifiedAsync()
        {
            SystemPath layerFile = temporaryFolder.NewFolder("testFolder").ToPath().Resolve("file");

            Files.Write(layerFile, Encoding.UTF8.GetBytes("hello"));
            Files.SetLastModifiedTime(layerFile, FileTime.From(Instant.FromUnixTimeSeconds(0)));
            LayerEntry       layerEntry       = DefaultLayerEntry(layerFile, AbsoluteUnixPath.Get("/extraction/path"));
            DescriptorDigest expectedSelector =
                await GenerateSelectorAsync(ImmutableArray.Create(layerEntry)).ConfigureAwait(false);

            // Verify that changing modified time generates a different selector
            Files.SetLastModifiedTime(layerFile, FileTime.From(Instant.FromUnixTimeSeconds(1)));
            Assert.AreNotEqual(
                expectedSelector, await GenerateSelectorAsync(ImmutableArray.Create(layerEntry)).ConfigureAwait(false));

            // Verify that changing modified time back generates same selector
            Files.SetLastModifiedTime(layerFile, FileTime.From(Instant.FromUnixTimeSeconds(0)));
            Assert.AreEqual(
                expectedSelector,
                await GenerateSelectorAsync(ImmutableArray.Create(layerEntry)).ConfigureAwait(false));
        }
Example #22
0
        public void Test_Deserializes_Forecasts(string json)
        {
            var result = Subject.Deserialize(json);

            result.Forecasts.ShouldAllBeEquivalentTo(new[]
            {
                new DarkSkyForecast()
                {
                    Type        = ForecastType.Current,
                    Date        = Instant.FromUnixTimeSeconds(1453402675),
                    High        = 46.93,
                    Low         = 46.93,
                    Description = "Rain"
                },
                new DarkSkyForecast()
                {
                    Type        = ForecastType.Minutely,
                    Date        = Instant.FromUnixTimeSeconds(1453402620),
                    High        = double.NaN,
                    Low         = double.NaN,
                    Description = "Rain for the hour."
                },
                new DarkSkyForecast()
                {
                    Type        = ForecastType.Hourly,
                    Date        = Instant.FromUnixTimeSeconds(1453399200),
                    High        = 46.41,
                    Low         = 46.41,
                    Description = "Rain throughout the day."
                },
                new DarkSkyForecast()
                {
                    Type        = ForecastType.Daily,
                    Date        = Instant.FromUnixTimeSeconds(1453363200),
                    High        = 53.27,
                    Low         = 36.68,
                    Description = "Light rain throughout the week, with temperatures bottoming out at 48°F on Sunday."
                }
            });
        }
Example #23
0
        public async Task recording_user_with_frommessage_flag_updates_last_message_at()
        {
            UserRepo userRepo = CreateUserRepo();
            // given
            Instant t1         = Instant.FromUnixTimeSeconds(0);
            Instant t2         = Instant.FromUnixTimeSeconds(1);
            Instant t3         = Instant.FromUnixTimeSeconds(2);
            var     userInfoT1 = new UserInfo("123", "X", "x", null, updatedAt: t1);
            var     userInfoT2 = new UserInfo("123", "X", "x", null, updatedAt: t2, fromMessage: true);
            var     userInfoT3 = new UserInfo("123", "X", "x", null, updatedAt: t3);

            // when, then
            User userT1 = await userRepo.RecordUser(userInfoT1);

            Assert.AreEqual(null, userT1.LastMessageAt); // fromMessage=false, stayed null
            User userT2 = await userRepo.RecordUser(userInfoT2);

            Assert.AreEqual(t2, userT2.LastMessageAt); // fromMessage=true, got updated
            User userT3 = await userRepo.RecordUser(userInfoT3);

            Assert.AreEqual(t2, userT3.LastMessageAt); // fromMessage=false, didn't get updated
        }
        public void MergeCharts_EmptyCharts_GetsMerged()
        {
            // Arrange
            var target = new Result();

            var source = new Result
            {
                Charts = new Dictionary <string, ChartDefinition>
                {
                    {
                        "chart", new ChartDefinition
                        {
                            Series = new Dictionary <string, SeriesDefinition>
                            {
                                {
                                    "series", new SeriesDefinition
                                    {
                                        Values = new List <InstantChartPoint>
                                        {
                                            new InstantChartPoint
                                            {
                                                X = Instant.FromUnixTimeSeconds(60 * 60 * 24 * 100), // 100 days
                                                Y = 100
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            };

            // Act
            ResultUpdater.Merge(target, source);

            // Assert
            Assert.AreEqual(1, target.Charts["chart"].Series["series"].Values.Count);
        }
        public void NewVersionsOfFeedUpToVersionN(int N)
        {
            Instant retrieveTime = Instant.FromUnixTimeSeconds(12345678);

            for (int version = 1; version <= N; ++version)
            {
                var feed = Feed();
                AddItemRange(feed, 1, 10, version);

                system.ProcessRawContent(ToContent(feed, retrieveTime));
            }

            for (int i = 1; i <= 10; ++i)
            {
                var docs = system.UnprocessedDocumentRepository.GetBySourceId(ItemId(i)).OrderBy(doc => doc.UpdateTime).ToList();

                for (int version = 1; version <= N; ++version)
                {
                    AssertDocumentIsCorrect(docs[version - 1], i, version, retrieveTime);
                }
            }
        }
Example #26
0
        public void TestDelay()
        {
            MemoryStream byteArrayOutputStream = new MemoryStream();

            IList <long> byteCounts = new List <long>();

            Queue <Instant> instantQueue = new Queue <Instant>();

            instantQueue.Enqueue(Instant.FromUnixTimeSeconds(0));

            using (ThrottledAccumulatingConsumer byteCounter =
                       new ThrottledAccumulatingConsumer(
                           byteCounts.Add, Duration.FromSeconds(3), instantQueue.Dequeue))
                using (NotifyingOutputStream notifyingOutputStream =
                           new NotifyingOutputStream(byteArrayOutputStream, byteCounter.Accept))

                {
                    instantQueue.Enqueue(Instant.FromUnixTimeSeconds(0));
                    notifyingOutputStream.WriteByte(100);
                    instantQueue.Enqueue(Instant.FromUnixTimeSeconds(0));
                    notifyingOutputStream.Write(new byte[] { 101, 102, 103 });
                    instantQueue.Enqueue(Instant.FromUnixTimeSeconds(0) + Duration.FromSeconds(4));
                    notifyingOutputStream.Write(new byte[] { 104, 105, 106 });

                    instantQueue.Enqueue(Instant.FromUnixTimeSeconds(0) + Duration.FromSeconds(10));
                    notifyingOutputStream.Write(new byte[] { 107, 108 });

                    instantQueue.Enqueue(Instant.FromUnixTimeSeconds(0) + Duration.FromSeconds(10));
                    notifyingOutputStream.Write(new byte[] { 109 });
                    instantQueue.Enqueue(Instant.FromUnixTimeSeconds(0) + Duration.FromSeconds(13));
                    notifyingOutputStream.Write(new byte[] { 0, 110 }, 1, 1);
                }

            Assert.AreEqual(new[] { 7L, 2L, 2L }, byteCounts);
            CollectionAssert.AreEqual(
                new byte[] { 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110 },
                byteArrayOutputStream.ToArray());
        }
Example #27
0
        private async Task AnnounceElapsedIntervalsAsync()
        {
            var overdueReminders = await GetOverdueRemindersAsync();

            foreach (var reminder in overdueReminders)
            {
                if (await TryAnnounceReminderAsync(reminder))
                {
                    if (reminder.IsPeriodic)
                    {
                        reminder.RemindTime = Instant.FromUnixTimeSeconds(reminder.RemindTime)
                                              .Plus(Duration.FromSeconds(reminder.Interval))
                                              .ToUnixTimeSeconds();

                        await UpdateReminderAsync(reminder);
                    }
                    else
                    {
                        await RemoveReminderAsync(reminder);
                    }
                }
            }
        }
Example #28
0
        public async Task TestBuild_timestampDefaultAsync()
        {
            SystemPath file = CreateFile(temporaryFolder.GetRoot().ToPath(), "fileA", "some content", 54321);

            IBlob blob =
                new ReproducibleLayerBuilder(
                    ImmutableArray.Create(DefaultLayerEntry(file, AbsoluteUnixPath.Get("/fileA"))))
                .Build();

            SystemPath tarFile = temporaryFolder.NewFile().ToPath();

            using (Stream @out = new BufferedStream(Files.NewOutputStream(tarFile)))
            {
                await blob.WriteToAsync(@out).ConfigureAwait(false);
            }

            // Reads the file back.
            using (TarInputStream @in = new TarInputStream(Files.NewInputStream(tarFile)))
            {
                Assert.AreEqual(
                    (Instant.FromUnixTimeSeconds(0) + Duration.FromSeconds(1)).ToDateTimeUtc(), @in.GetNextEntry().TarHeader.ModTime);
            }
        }
        public async Task <GreenButtonData> fetchGreenButtonData()
        {
            XDocument doc = await client.greenButton.fetchGreenButtonData();

            IEnumerable <XElement> intervalReadings = doc.Descendants(XName.Get("IntervalReading", NS));

            return(new GreenButtonData {
                meterReadings = intervalReadings.Select(element => {
                    Instant start =
                        Instant.FromUnixTimeSeconds(long.Parse(element.Descendants(XName.Get("start", NS)).First().Value));
                    Instant end = start.Plus(
                        Duration.FromSeconds(long.Parse(element.Descendants(XName.Get("duration", NS)).First().Value)));

                    return new GreenButtonData.MeterReading {
                        billingInterval = new DateInterval(start.InZone(zone).Date, end.InZone(zone).Date),
                        costCents = int.Parse(element.Element(XName.Get("cost", NS))?.Value ??
                                              throw new OrangeRocklandException("IntervalReading has no cost child element")) /
                                    1000
                    };
                })
                                .OrderBy(reading => reading.billingInterval.End)
                                .ToArray()
            });
Example #30
0
            public void detects_recent_exact_copypasta()
            {
                Mock <IClock> clockMock = new();
                CopypastaRule rule      = new(clockMock.Object, Duration.FromSeconds(10));

                const string copypasta =
                    "Please do not copy and paste this copypasta. It is my original copypasta and is protected by copyright law. If I see anyone pasting my intellectual property without permission, a navy seal trained in gorilla warfare will smite you.";

                clockMock.Setup(c => c.GetCurrentInstant()).Returns(Instant.FromUnixTimeSeconds(0));
                RuleResult resultFirstSeen = rule.Check(TextMessage(copypasta));

                Assert.IsInstanceOf <RuleResult.Nothing>(resultFirstSeen);

                clockMock.Setup(c => c.GetCurrentInstant()).Returns(Instant.FromUnixTimeSeconds(5));
                RuleResult resultCopypasted = rule.Check(TextMessage(copypasta));

                Assert.IsInstanceOf <RuleResult.GivePoints>(resultCopypasted);

                clockMock.Setup(c => c.GetCurrentInstant()).Returns(Instant.FromUnixTimeSeconds(16));
                RuleResult resultLapsed = rule.Check(TextMessage(copypasta));

                Assert.IsInstanceOf <RuleResult.Nothing>(resultLapsed);
            }