public async Task EmptyItemOutIsValid()
        {
            var currentInstant   = Instant.FromUtc(2017, 08, 17, 12, 0, 0);
            var fakeClock        = new FakeClock(currentInstant);
            var headerValidator  = new OrderHeaderValidator(fakeClock) as IMessageValidator <OrderHeader>;
            var itemValidator    = new itemItemValidator() as IMessageValidator <ItemAsset>;
            var itemOutValidator = new ItemOutValidator(itemValidator) as IMessageValidator <LineItem>;
            var validator        = new OrderFulfillmentMessageValidator(headerValidator, itemOutValidator);
            var header           = new OrderHeader {
                OrderId = "ABC123", OrderDate = currentInstant.ToDateTimeUtc()
            };

            var target = new OrderFulfillmentMessage
            {
                OrderRequestHeader = header,
                LineItems          = new List <LineItem>()
            };

            var result = await validator.ValidateAsync(target);

            result.Should().NotBeNull("because a validation result should have been returned");
            result.Should().BeEmpty("because an empty itemout set is allowed");
        }
        public void GetZoneIntervals_Complex()
        {
            var london = DateTimeZoneProviders.Tzdb["Europe/London"];
            // Transitions are always Spring/Autumn, so June and January should be clear.
            var expected = new[] {
                london.GetZoneInterval(Instant.FromUtc(1999, 6, 1, 0, 0)),
                london.GetZoneInterval(Instant.FromUtc(2000, 1, 1, 0, 0)),
                london.GetZoneInterval(Instant.FromUtc(2000, 6, 1, 0, 0)),
                london.GetZoneInterval(Instant.FromUtc(2001, 1, 1, 0, 0)),
                london.GetZoneInterval(Instant.FromUtc(2001, 6, 1, 0, 0)),
                london.GetZoneInterval(Instant.FromUtc(2002, 1, 1, 0, 0)),
            };
            // After the instant we used to fetch the expected zone interval, but that's fine:
            // it'll be the same one, as there's no transition within June.
            var start  = Instant.FromUtc(1999, 6, 19, 0, 0);
            var end    = Instant.FromUtc(2002, 2, 4, 0, 0);
            var actual = london.GetZoneIntervals(start, end);

            CollectionAssert.AreEqual(expected, actual.ToList());
            // Just to exercise the other overload
            actual = london.GetZoneIntervals(new Interval(start, end));
            CollectionAssert.AreEqual(expected, actual.ToList());
        }
        public async Task RequestHeaderIsValidated()
        {
            var currentInstant   = Instant.FromUtc(2017, 08, 17, 12, 0, 0);
            var fakeClock        = new FakeClock(currentInstant);
            var headerValidator  = new OrderHeaderValidator(fakeClock) as IMessageValidator <OrderHeader>;
            var itemValidator    = new itemItemValidator() as IMessageValidator <ItemAsset>;
            var itemOutValidator = new ItemOutValidator(itemValidator) as IMessageValidator <LineItem>;
            var validator        = new OrderFulfillmentMessageValidator(headerValidator, itemOutValidator);
            var header           = new OrderHeader {
                OrderId = null, OrderDate = currentInstant.ToDateTimeUtc()
            };

            var target = new OrderFulfillmentMessage
            {
                OrderRequestHeader = header,
                LineItems          = new List <LineItem>()
            };

            var result = await validator.ValidateAsync(target);

            result.Should().NotBeNull("because a validation result should have been returned");
            result.Should().ContainSingle(error => (error.MemberPath == $"{ nameof(OrderFulfillmentMessage.OrderRequestHeader) }.{ nameof(OrderHeader.OrderId) }"), "because the order id was not provided in the header");
        }
        public async Task ItemOutsAreValidated()
        {
            var currentInstant   = Instant.FromUtc(2017, 08, 17, 12, 0, 0);
            var fakeClock        = new FakeClock(currentInstant);
            var headerValidator  = new OrderHeaderValidator(fakeClock) as IMessageValidator <OrderHeader>;
            var itemValidator    = new itemItemValidator() as IMessageValidator <ItemAsset>;
            var itemOutValidator = new ItemOutValidator(itemValidator) as IMessageValidator <LineItem>;
            var validator        = new OrderFulfillmentMessageValidator(headerValidator, itemOutValidator);
            var header           = new OrderHeader {
                OrderId = "ABC123", OrderDate = currentInstant.ToDateTimeUtc()
            };

            var itemOuts = new List <LineItem>
            {
                new LineItem
                {
                    Assets = new List <ItemAsset>
                    {
                        new ItemAsset(),
                        new ItemAsset()
                    }
                }
            };

            var target = new OrderFulfillmentMessage
            {
                OrderRequestHeader = header,
                LineItems          = itemOuts
            };

            var result = await validator.ValidateAsync(target);

            var failurePath = $"{ nameof(OrderFulfillmentMessage.LineItems) }[0].{ nameof(LineItem.Assets) }";

            result.Should().NotBeNull("because a validation result should have been returned");
            result.Should().ContainSingle(error => error.MemberPath == failurePath, "because the itemout violated a rule");
        }
Example #5
0
        public async Task Parser_should_fill_header()
        {
            await using var fs = File.OpenRead("Assets/Rsm001CPR.xml");

            var     sut    = new RsmValidationParser();
            Context actual = await sut.ParseAsync(fs).ConfigureAwait(false);

            Assert.NotNull(actual);

            var expected = new RsmHeader
            {
                Creation                     = Instant.FromUtc(2020, 02, 20, 10, 56, 46),
                Identification               = "MsgId-0.58755000-1582196206",
                DocumentType                 = "392",
                RecipientIdentification      = "5790001330552",
                SenderIdentification         = "5790002263057",
                EnergyBusinessProcess        = "E03",
                EnergyIndustryClassification = "23",
                EnergyBusinessProcessRole    = "DDQ",
                MessageReference             = null,
            };

            Assert.Equal(expected, actual.RsmHeader);
        }
Example #6
0
        public void GetJwtPublicKeyThrowsOnInvalidJson()
        {
            var localHandler = A.Fake <MockHandler>(opt => opt.CallsBaseMethods());

            A.CallTo(() => localHandler.SendAsync(HttpMethod.Get, "https://cdn.actionstep.com/jwt-discovery-public.json"))
            .ReturnsLazily(() => Success("Not a JSON string. This is invalid JSON."));

            using (var authDelegatingHandler = new AuthDelegatingHandler()
            {
                InnerHandler = localHandler
            })
                using (var httpClient = new HttpClient(authDelegatingHandler))
                    using (var memoryCache = new MemoryCache(new MemoryCacheOptions()))
                    {
                        var fakeClock          = new FakeClock(Instant.FromUtc(2019, 05, 07, 2, 3));
                        var options            = new ActionstepServiceConfigurationOptions("clientId", "clientSecret");
                        var tokenSetRepository = new TestTokenSetRepository();
                        IActionstepService actionstepService = new ActionstepService(new NullLogger <ActionstepService>(), httpClient, options, tokenSetRepository, fakeClock, memoryCache);

                        var ex = Assert.Throws <InvalidJwtDiscoveryResponseException>(() => { actionstepService.GetJwtPublicKeyData(); });

                        Assert.Equal("There was a problem parsing the JWT Discovery public key response.", ex.Message);
                    }
        }
Example #7
0
        public void Should_get_activity_for_a_specific_date()
        {
            DateTimeZone zone      = DateTimeZoneProviders.Tzdb["Europe/Berlin"];
            var          begin     = new ZonedDateTime(Instant.FromUtc(2019, 5, 1, 14, 00), zone);
            var          activity1 = new Activity(begin);

            begin = new ZonedDateTime(Instant.FromUtc(2019, 5, 2, 15, 00), zone);
            var activity2 = new Activity(begin);

            begin = new ZonedDateTime(Instant.FromUtc(2019, 5, 1, 15, 00), zone);
            var activity3 = new Activity(begin);

            var subject = new Person();

            subject.AddActivity(activity1);
            subject.AddActivity(activity2);
            subject.AddActivity(activity3);

            var result = subject.GetActivitiesForDate(new LocalDate(2019, 5, 1), zone);

            result.Count.Should().Be(2);

            result.Should().Contain(new[] { activity1, activity3 });
        }
Example #8
0
        public static Variable TimeVal(string input)
        {
            if (input.Contains('@'))
            {
                var zoneDt = _zoneTmPattern.WithTemplateValue(Instant.FromUtc(1970, 1, 1, 11, 30).InZone(DateTimeZone.Utc)).Parse(input).Value;
                return(Variable.Time(zoneDt));
            }

            var ofstTm = OffsetTimePattern.Rfc3339.Parse(input);

            if (ofstTm.Success)
            {
                return(ofstTm.Value);
            }

            var localTm = LocalTimePattern.ExtendedIso.Parse(input);

            if (localTm.Success)
            {
                return(localTm.Value);
            }

            return(new Variable());
        }
        public void DateTimeMinValueStartRuleExtendsToBeginningOfTime()
        {
            var rules = new[]
            {
                // Rule for the whole of time, with DST of 1 hour commencing on March 1st
                // and ending on September 1st.
                TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(
                    DateTime.MinValue, DateTime.MaxValue.Date, TimeSpan.FromHours(1),
                    TimeZoneInfo.TransitionTime.CreateFixedDateRule(DateTime.MinValue, 3, 1),
                    TimeZoneInfo.TransitionTime.CreateFixedDateRule(DateTime.MinValue, 9, 1))
            };
            var bclZone = TimeZoneInfo.CreateCustomTimeZone("custom", baseUtcOffset: TimeSpan.Zero,
                                                            displayName: "DisplayName", standardDisplayName: "Standard",
                                                            daylightDisplayName: "Daylight",
                                                            adjustmentRules: rules);
            var nodaZone = BclDateTimeZone.FromTimeZoneInfo(bclZone);

            // Standard time in February BC 101
            Assert.AreEqual(Offset.Zero, nodaZone.GetUtcOffset(Instant.FromUtc(-100, 2, 1, 0, 0)));
            // Daylight time in July BC 101
            Assert.AreEqual(Offset.FromHours(1), nodaZone.GetUtcOffset(Instant.FromUtc(-100, 7, 1, 0, 0)));
            // Standard time in October BC 101
            Assert.AreEqual(Offset.Zero, nodaZone.GetUtcOffset(Instant.FromUtc(-100, 10, 1, 0, 0)));
        }
Example #10
0
 /// <summary>
 /// Returns a fake clock initially set to midnight of the given year/month/day in UTC in the ISO calendar.
 /// The value of the <see cref="AutoAdvance"/> property will be initialised to zero.
 /// </summary>
 /// <param name="year">The year. This is the "absolute year",
 /// so a value of 0 means 1 BC, for example.</param>
 /// <param name="monthOfYear">The month of year.</param>
 /// <param name="dayOfMonth">The day of month.</param>
 /// <returns>A <see cref="FakeClock"/> initialised to the given instant, with no auto-advance.</returns>
 public static FakeClock FromUtc(int year, int monthOfYear, int dayOfMonth)
 {
     return(new FakeClock(Instant.FromUtc(year, monthOfYear, dayOfMonth, 0, 0)));
 }
Example #11
0
        public void Timestamp(LocalDateTime localDateTime)
        {
            using (var conn = OpenConnection())
            {
                var instant = localDateTime.InUtc().ToInstant();
                var minTimestampPostgres = Instant.FromUtc(-4713, 12, 31, 00, 00, 00);
                var maxTimestampPostgres = Instant.MaxValue;

                conn.ExecuteNonQuery("CREATE TEMP TABLE data (d1 TIMESTAMP, d2 TIMESTAMP, d3 TIMESTAMP, d4 TIMESTAMP, d5 TIMESTAMP, d6 TIMESTAMP, d7 TIMESTAMP)");

                using (var cmd = new NpgsqlCommand("INSERT INTO data VALUES (@p1, @p2, @p3, @p4, @p5, @p6, @p7)", conn))
                {
                    cmd.Parameters.Add(new NpgsqlParameter("p1", NpgsqlDbType.Timestamp)
                    {
                        Value = instant
                    });
                    cmd.Parameters.Add(new NpgsqlParameter("p2", DbType.DateTime)
                    {
                        Value = instant
                    });
                    cmd.Parameters.Add(new NpgsqlParameter("p3", DbType.DateTime2)
                    {
                        Value = instant
                    });
                    cmd.Parameters.Add(new NpgsqlParameter {
                        ParameterName = "p4", Value = instant
                    });
                    cmd.Parameters.Add(new NpgsqlParameter {
                        ParameterName = "p5", Value = localDateTime
                    });
                    cmd.Parameters.Add(new NpgsqlParameter {
                        ParameterName = "p6", Value = minTimestampPostgres
                    });
                    cmd.Parameters.Add(new NpgsqlParameter {
                        ParameterName = "p7", Value = maxTimestampPostgres
                    });
                    cmd.ExecuteNonQuery();
                }

                // Make sure the values inserted are the good ones, textually
                using (var cmd = new NpgsqlCommand("SELECT d1::TEXT, d2::TEXT, d3::TEXT, d4::TEXT, d5::TEXT FROM data", conn))
                    using (var reader = cmd.ExecuteReader())
                    {
                        reader.Read();
                        for (var i = 0; i < reader.FieldCount; i++)
                        {
                            Assert.That(reader.GetValue(i), Is.EqualTo(instant.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ss'.'FFFFFF", CultureInfo.InvariantCulture)));
                        }
                    }

                using (var cmd = new NpgsqlCommand("SELECT d6::TEXT, d7::TEXT FROM data", conn))
                    using (var reader = cmd.ExecuteReader())
                    {
                        reader.Read();
                        Assert.That(reader.GetValue(0), Is.EqualTo("4714-12-31 00:00:00 BC"));
                        Assert.That(reader.GetValue(1), Is.EqualTo(maxTimestampPostgres.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ss'.'FFFFFF", CultureInfo.InvariantCulture)));
                    }

                using (var cmd = new NpgsqlCommand("SELECT d1, d2, d3, d4, d5 FROM data", conn))
                    using (var reader = cmd.ExecuteReader())
                    {
                        reader.Read();

                        for (var i = 0; i < reader.FieldCount; i++)
                        {
                            Assert.That(reader.GetFieldType(i), Is.EqualTo(typeof(Instant)));
                            Assert.That(reader.GetFieldValue <Instant>(i), Is.EqualTo(instant));
                            Assert.That(reader.GetValue(i), Is.EqualTo(instant));
                            Assert.That(reader.GetFieldValue <LocalDateTime>(i), Is.EqualTo(localDateTime));
                            Assert.That(() => reader.GetFieldValue <ZonedDateTime>(i), Throws.TypeOf <InvalidCastException>());
                            Assert.That(() => reader.GetDateTime(i), Throws.TypeOf <InvalidCastException>());
                            Assert.That(() => reader.GetDate(i), Throws.TypeOf <InvalidCastException>());
                        }
                    }
            }
        }
Example #12
0
        public void TimestampTz()
        {
            using (var conn = OpenConnection())
            {
                var timezone = "America/New_York";
                conn.ExecuteNonQuery($"SET TIMEZONE TO '{timezone}'");
                Assert.That(conn.Timezone, Is.EqualTo(timezone));
                // Nodatime provider should return timestamptz's as ZonedDateTime in the session timezone

                var instant            = Instant.FromUtc(2015, 6, 27, 8, 45, 12) + Duration.FromMilliseconds(345);
                var utcZonedDateTime   = instant.InUtc();
                var localZonedDateTime = utcZonedDateTime.WithZone(DateTimeZoneProviders.Tzdb[timezone]);
                var offsetDateTime     = localZonedDateTime.ToOffsetDateTime();

                conn.ExecuteNonQuery("CREATE TEMP TABLE data (d1 TIMESTAMPTZ, d2 TIMESTAMPTZ, d3 TIMESTAMPTZ, d4 TIMESTAMPTZ)");

                using (var cmd = new NpgsqlCommand("INSERT INTO data VALUES (@p1, @p2, @p3, @p4)", conn))
                {
                    cmd.Parameters.Add(new NpgsqlParameter("p1", NpgsqlDbType.TimestampTz)
                    {
                        Value = instant
                    });
                    cmd.Parameters.Add(new NpgsqlParameter {
                        ParameterName = "p2", Value = utcZonedDateTime
                    });
                    cmd.Parameters.Add(new NpgsqlParameter {
                        ParameterName = "p3", Value = localZonedDateTime
                    });
                    cmd.Parameters.Add(new NpgsqlParameter {
                        ParameterName = "p4", Value = offsetDateTime
                    });
                    cmd.ExecuteNonQuery();
                }

                using (var cmd = new NpgsqlCommand("SELECT d1::TEXT, d2::TEXT, d3::TEXT, d4::TEXT FROM data", conn))
                    using (var reader = cmd.ExecuteReader())
                    {
                        reader.Read();
                        // When converting timestamptz as a string as we're doing here, PostgreSQL automatically converts
                        // it to the session timezone
                        for (var i = 0; i < reader.FieldCount; i++)
                        {
                            Assert.That(reader.GetValue(i), Is.EqualTo(
                                            localZonedDateTime.ToString("uuuu'-'MM'-'dd' 'HH':'mm':'ss'.'fff", CultureInfo.InvariantCulture) + "-04")
                                        );
                        }
                    }

                using (var cmd = new NpgsqlCommand("SELECT * FROM data", conn))
                    using (var reader = cmd.ExecuteReader())
                    {
                        reader.Read();

                        for (var i = 0; i < reader.FieldCount; i++)
                        {
                            Assert.That(reader.GetFieldType(i), Is.EqualTo(typeof(Instant)));
                            Assert.That(reader.GetFieldValue <Instant>(i), Is.EqualTo(instant));
                            Assert.That(reader.GetValue(i), Is.EqualTo(instant));
                            Assert.That(reader.GetFieldValue <ZonedDateTime>(i), Is.EqualTo(localZonedDateTime));
                            Assert.That(reader.GetFieldValue <OffsetDateTime>(i), Is.EqualTo(offsetDateTime));
                            Assert.That(() => reader.GetFieldValue <LocalDateTime>(i), Throws.TypeOf <InvalidCastException>());
                            Assert.That(() => reader.GetDateTime(i), Throws.TypeOf <InvalidCastException>());
                            Assert.That(() => reader.GetDate(i), Throws.TypeOf <InvalidCastException>());
                        }
                    }
            }
        }
Example #13
0
        public static List <LeagueYear> GetLeagueYears()
        {
            var leagues = GetLeagues();
            List <LeagueYear> leagueYears = new List <LeagueYear>();

            foreach (var league in leagues)
            {
                var        eligibilityOverrides = new List <EligibilityOverride>();
                LeagueYear year = new LeagueYear(league, 2019, new LeagueOptions(12, 6, 1, 2, -1, 0, false, false, 0, new List <LeagueTagStatus>(), DraftSystem.Flexible, PickupSystem.Budget,
                                                                                 ScoringSystem.GetScoringSystem("Standard"), true), PlayStatus.DraftFinal, eligibilityOverrides, Instant.FromUtc(2019, 1, 5, 12, 0, 0));
                leagueYears.Add(year);
            }

            return(leagueYears);
        }
Example #14
0
 public TestTime(int threadCount = 1, Instant?startInstant = null)
 {
     _fakeClock     = new FakeClock(startInstant ?? Instant.FromUtc(2000, 1, 1, 0, 0));
     _taskScheduler = new TestTaskScheduler(threadCount);
     TaskHelper     = new TestTaskHelper(this);
 }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity <Race>()
            .HasData(
                new Race {
                Id = 1, Date = new LocalDate(2019, 1, 1), ScheduledStartTime = new LocalTime(8, 0, 0, 0), ScheduledDuration = DurationExtensions.FromParts(1, 0, 0, 0), ScheduledStart = new LocalDateTime(2019, 1, 1, 8, 0, 0, 0)
            },
                new Race {
                Id = 2, Date = new LocalDate(2019, 2, 1), ScheduledStartTime = new LocalTime(9, 1, 1, 1), ScheduledDuration = DurationExtensions.FromParts(2, 1, 1, 1), ScheduledStart = new LocalDateTime(2019, 2, 1, 9, 1, 1, 1)
            },
                new Race {
                Id = 3, Date = new LocalDate(2019, 3, 1), ScheduledStartTime = new LocalTime(10, 2, 2, 2), ScheduledDuration = DurationExtensions.FromParts(3, 2, 2, 2), ScheduledStart = new LocalDateTime(2019, 3, 1, 10, 2, 2, 2)
            },
                new Race {
                Id = 4, Date = new LocalDate(2019, 4, 1), ScheduledStartTime = new LocalTime(11, 3, 3, 3), ScheduledDuration = DurationExtensions.FromParts(4, 3, 3, 3), ScheduledStart = new LocalDateTime(2019, 4, 1, 11, 3, 3, 3)
            },
                new Race {
                Id = 5, Date = new LocalDate(2019, 5, 1), ScheduledStartTime = new LocalTime(12, 4, 4, 4), ScheduledDuration = DurationExtensions.FromParts(5, 4, 4, 4), ScheduledStart = new LocalDateTime(2019, 5, 1, 12, 4, 4, 4)
            },
                new Race {
                Id = 6, Date = new LocalDate(2019, 6, 1), ScheduledStartTime = new LocalTime(13, 5, 5, 5), ScheduledDuration = DurationExtensions.FromParts(6, 5, 5, 5), ScheduledStart = new LocalDateTime(2019, 6, 1, 13, 5, 5, 5)
            },
                new Race {
                Id = 7, Date = new LocalDate(2019, 7, 1), ScheduledStartTime = new LocalTime(14, 6, 6, 6), ScheduledDuration = DurationExtensions.FromParts(7, 6, 6, 6), ScheduledStart = new LocalDateTime(2019, 7, 1, 14, 6, 6, 6)
            },
                new Race {
                Id = 8, Date = new LocalDate(2019, 8, 1), ScheduledStartTime = new LocalTime(15, 7, 7, 7), ScheduledDuration = DurationExtensions.FromParts(8, 7, 7, 7), ScheduledStart = new LocalDateTime(2019, 8, 1, 15, 7, 7, 7)
            },
                new Race {
                Id = 9, Date = new LocalDate(2019, 9, 1), ScheduledStartTime = new LocalTime(16, 8, 8, 8), ScheduledDuration = DurationExtensions.FromParts(9, 8, 8, 8), ScheduledStart = new LocalDateTime(2019, 9, 1, 16, 8, 8, 8)
            },
                new Race {
                Id = 10, Date = new LocalDate(2019, 10, 1), ScheduledStartTime = new LocalTime(17, 9, 9, 9), ScheduledDuration = DurationExtensions.FromParts(10, 9, 9, 9), ScheduledStart = new LocalDateTime(2019, 10, 1, 17, 9, 9, 9)
            },
                new Race {
                Id = 11, Date = new LocalDate(2019, 11, 1), ScheduledStartTime = new LocalTime(18, 10, 10, 10), ScheduledDuration = DurationExtensions.FromParts(11, 10, 10, 10), ScheduledStart = new LocalDateTime(2019, 11, 1, 18, 10, 10, 10)
            },
                new Race {
                Id = 12, Date = new LocalDate(2019, 12, 1), ScheduledStartTime = new LocalTime(19, 11, 11, 11), ScheduledDuration = DurationExtensions.FromParts(12, 11, 11, 11), ScheduledStart = new LocalDateTime(2019, 12, 1, 19, 11, 11, 11)
            }
                );


            modelBuilder.Entity <RaceResult>()
            .HasData(
                new RaceResult {
                Id = 1, StartTime = Instant.FromUtc(2019, 1, 1, 8, 0), EndTime = Instant.FromUtc(2019, 1, 1, 9, 0), StartTimeOffset = OffsetDateTime.FromDateTimeOffset(new DateTimeOffset(new DateTime(2019, 1, 1, 8, 0, 0), TimeSpan.FromHours(5))), OffsetFromWinner = DurationExtensions.FromParts(0, 0, 0, 0, 0, 0)
            },
                new RaceResult {
                Id = 2, StartTime = Instant.FromUtc(2019, 2, 1, 9, 0), EndTime = Instant.FromUtc(2019, 2, 1, 10, 0), StartTimeOffset = OffsetDateTime.FromDateTimeOffset(new DateTimeOffset(new DateTime(2019, 2, 1, 9, 0, 0), TimeSpan.FromHours(5))), OffsetFromWinner = DurationExtensions.FromParts(0, 0, 0, 1, 0, 0)
            },
                new RaceResult {
                Id = 3, StartTime = Instant.FromUtc(2019, 3, 1, 10, 0), EndTime = Instant.FromUtc(2019, 3, 1, 11, 0), StartTimeOffset = OffsetDateTime.FromDateTimeOffset(new DateTimeOffset(new DateTime(2019, 3, 1, 10, 0, 0), TimeSpan.FromHours(5))), OffsetFromWinner = DurationExtensions.FromParts(0, 0, 0, 2, 0, 0)
            },
                new RaceResult {
                Id = 4, StartTime = Instant.FromUtc(2019, 4, 1, 11, 0), EndTime = Instant.FromUtc(2019, 4, 1, 12, 0), StartTimeOffset = OffsetDateTime.FromDateTimeOffset(new DateTimeOffset(new DateTime(2019, 4, 1, 11, 0, 0), TimeSpan.FromHours(5))), OffsetFromWinner = DurationExtensions.FromParts(0, 0, 0, 3, 0, 0)
            },
                new RaceResult {
                Id = 5, StartTime = Instant.FromUtc(2019, 5, 1, 12, 0), EndTime = Instant.FromUtc(2019, 5, 1, 13, 0), StartTimeOffset = OffsetDateTime.FromDateTimeOffset(new DateTimeOffset(new DateTime(2019, 5, 1, 12, 0, 0), TimeSpan.FromHours(5))), OffsetFromWinner = DurationExtensions.FromParts(0, 0, 0, 4, 0, 0)
            },
                new RaceResult {
                Id = 6, StartTime = Instant.FromUtc(2019, 6, 1, 13, 0), EndTime = Instant.FromUtc(2019, 6, 1, 14, 0), StartTimeOffset = OffsetDateTime.FromDateTimeOffset(new DateTimeOffset(new DateTime(2019, 6, 1, 13, 0, 0), TimeSpan.FromHours(5))), OffsetFromWinner = DurationExtensions.FromParts(0, 0, 0, 5, 0, 0)
            },
                new RaceResult {
                Id = 7, StartTime = Instant.FromUtc(2019, 7, 1, 14, 0), EndTime = Instant.FromUtc(2019, 7, 1, 15, 0), StartTimeOffset = OffsetDateTime.FromDateTimeOffset(new DateTimeOffset(new DateTime(2019, 7, 1, 14, 0, 0), TimeSpan.FromHours(5))), OffsetFromWinner = DurationExtensions.FromParts(0, 0, 0, 6, 0, 0)
            },
                new RaceResult {
                Id = 8, StartTime = Instant.FromUtc(2019, 8, 1, 15, 0), EndTime = Instant.FromUtc(2019, 8, 1, 16, 0), StartTimeOffset = OffsetDateTime.FromDateTimeOffset(new DateTimeOffset(new DateTime(2019, 8, 1, 15, 0, 0), TimeSpan.FromHours(5))), OffsetFromWinner = DurationExtensions.FromParts(0, 0, 0, 7, 0, 0)
            },
                new RaceResult {
                Id = 9, StartTime = Instant.FromUtc(2019, 9, 1, 16, 0), EndTime = Instant.FromUtc(2019, 9, 1, 17, 0), StartTimeOffset = OffsetDateTime.FromDateTimeOffset(new DateTimeOffset(new DateTime(2019, 9, 1, 16, 0, 0), TimeSpan.FromHours(5))), OffsetFromWinner = DurationExtensions.FromParts(0, 0, 0, 8, 0, 0)
            },
                new RaceResult {
                Id = 10, StartTime = Instant.FromUtc(2019, 10, 1, 17, 0), EndTime = Instant.FromUtc(2019, 10, 1, 18, 0), StartTimeOffset = OffsetDateTime.FromDateTimeOffset(new DateTimeOffset(new DateTime(2019, 10, 1, 17, 0, 0), TimeSpan.FromHours(5))), OffsetFromWinner = DurationExtensions.FromParts(0, 0, 0, 9, 0, 0)
            },
                new RaceResult {
                Id = 11, StartTime = Instant.FromUtc(2019, 11, 1, 18, 0), EndTime = Instant.FromUtc(2019, 11, 1, 19, 0), StartTimeOffset = OffsetDateTime.FromDateTimeOffset(new DateTimeOffset(new DateTime(2019, 11, 1, 18, 0, 0), TimeSpan.FromHours(5))), OffsetFromWinner = DurationExtensions.FromParts(0, 0, 0, 10, 0, 0)
            },
                new RaceResult {
                Id = 12, StartTime = Instant.FromUtc(2019, 12, 1, 19, 0), EndTime = Instant.FromUtc(2019, 12, 1, 20, 0), StartTimeOffset = OffsetDateTime.FromDateTimeOffset(new DateTimeOffset(new DateTime(2019, 12, 1, 19, 0, 0), TimeSpan.FromHours(5))), OffsetFromWinner = DurationExtensions.FromParts(0, 0, 0, 11, 0, 0)
            });

            modelBuilder.Entity <RaceSplit>()
            .HasData(
                new RaceSplit {
                Id = 1, TimeStampInstant = InstantExtensions.FromParts(2020, 1, 1, 1, 1, 1, 1, 1, 1), TimeStampLocalDateTime = LocalDateTimeExtensions.FromParts(2020, 1, 1, 1, 1, 1, 1, 1, 1), TimeStampLocalTime = LocalTimeExtensions.FromParts(1, 1, 1, 1, 1, 100), TimeStampOffsetDateTime = OffsetDateTimeExtensions.FromParts(2020, 1, 1, 1, 1, 1, 1, 1, 100, 300)
            },
                new RaceSplit {
                Id = 2, TimeStampInstant = InstantExtensions.FromParts(2020, 1, 1, 2, 2, 2, 2, 2, 2), TimeStampLocalDateTime = LocalDateTimeExtensions.FromParts(2020, 1, 1, 2, 2, 2, 2, 2, 2), TimeStampLocalTime = LocalTimeExtensions.FromParts(2, 2, 2, 2, 1, 100), TimeStampOffsetDateTime = OffsetDateTimeExtensions.FromParts(2020, 1, 1, 2, 2, 2, 2, 2, 200, 300)
            },
                new RaceSplit {
                Id = 3, TimeStampInstant = InstantExtensions.FromParts(2020, 1, 1, 3, 3, 3, 3, 3, 3), TimeStampLocalDateTime = LocalDateTimeExtensions.FromParts(2020, 1, 1, 3, 3, 3, 3, 3, 3), TimeStampLocalTime = LocalTimeExtensions.FromParts(3, 3, 3, 3, 3, 300), TimeStampOffsetDateTime = OffsetDateTimeExtensions.FromParts(2020, 1, 1, 3, 3, 3, 3, 3, 300, 300)
            },
                new RaceSplit {
                Id = 4, TimeStampInstant = InstantExtensions.FromParts(2020, 1, 1, 4, 4, 4, 4, 4, 4), TimeStampLocalDateTime = LocalDateTimeExtensions.FromParts(2020, 1, 1, 4, 4, 4, 4, 4, 4), TimeStampLocalTime = LocalTimeExtensions.FromParts(4, 4, 4, 4, 4, 400), TimeStampOffsetDateTime = OffsetDateTimeExtensions.FromParts(2020, 1, 1, 4, 4, 4, 4, 4, 400, 300)
            },
                new RaceSplit {
                Id = 5, TimeStampInstant = InstantExtensions.FromParts(2020, 1, 1, 5, 5, 5, 5, 5, 5), TimeStampLocalDateTime = LocalDateTimeExtensions.FromParts(2020, 1, 1, 5, 5, 5, 5, 5, 5), TimeStampLocalTime = LocalTimeExtensions.FromParts(5, 5, 5, 5, 5, 500), TimeStampOffsetDateTime = OffsetDateTimeExtensions.FromParts(2020, 1, 1, 5, 5, 5, 5, 5, 500, 300)
            },
                new RaceSplit {
                Id = 6, TimeStampInstant = InstantExtensions.FromParts(2020, 1, 1, 6, 6, 6, 6, 6, 6), TimeStampLocalDateTime = LocalDateTimeExtensions.FromParts(2020, 1, 1, 6, 6, 6, 6, 6, 6), TimeStampLocalTime = LocalTimeExtensions.FromParts(6, 6, 6, 6, 6, 600), TimeStampOffsetDateTime = OffsetDateTimeExtensions.FromParts(2020, 1, 1, 6, 6, 6, 6, 6, 600, 300)
            },
                new RaceSplit {
                Id = 7, TimeStampInstant = InstantExtensions.FromParts(2020, 1, 1, 7, 7, 7, 7, 7, 7), TimeStampLocalDateTime = LocalDateTimeExtensions.FromParts(2020, 1, 1, 7, 7, 7, 7, 7, 7), TimeStampLocalTime = LocalTimeExtensions.FromParts(7, 7, 7, 7, 7, 700), TimeStampOffsetDateTime = OffsetDateTimeExtensions.FromParts(2020, 1, 1, 7, 7, 7, 7, 7, 700, 300)
            },
                new RaceSplit {
                Id = 8, TimeStampInstant = InstantExtensions.FromParts(2020, 1, 1, 8, 8, 8, 8, 8, 8), TimeStampLocalDateTime = LocalDateTimeExtensions.FromParts(2020, 1, 1, 8, 8, 8, 8, 8, 8), TimeStampLocalTime = LocalTimeExtensions.FromParts(8, 8, 8, 8, 8, 800), TimeStampOffsetDateTime = OffsetDateTimeExtensions.FromParts(2020, 1, 1, 8, 8, 8, 8, 8, 800, 300)
            },
                new RaceSplit {
                Id = 9, TimeStampInstant = InstantExtensions.FromParts(2020, 1, 1, 9, 9, 9, 9, 9, 9), TimeStampLocalDateTime = LocalDateTimeExtensions.FromParts(2020, 1, 1, 9, 9, 9, 9, 9, 9), TimeStampLocalTime = LocalTimeExtensions.FromParts(9, 9, 9, 9, 9, 900), TimeStampOffsetDateTime = OffsetDateTimeExtensions.FromParts(2020, 1, 1, 9, 9, 9, 9, 9, 900, 300)
            }
                );
        }
Example #16
0
 public static ulong InstantToSnowflake(Instant time) =>
 (ulong)(time - Instant.FromUtc(2015, 1, 1, 0, 0, 0)).TotalMilliseconds >> 22;
Example #17
0
        public async Task SecondTokenRefreshWaitsForFirst()
        {
            using (var authDelegatingHandler = new AuthDelegatingHandler()
            {
                InnerHandler = _handler
            })
                using (var httpClient = new HttpClient(authDelegatingHandler))
                    using (var memoryCache = new MemoryCache(new MemoryCacheOptions()))
                    {
                        var tokenHandler        = new TestTokenSetRepository();
                        var fakeClock           = new FakeClock(Instant.FromUtc(2019, 05, 07, 2, 3));
                        var testTokenRepository = new TestTokenSetRepository();
                        var options             = new ActionstepServiceConfigurationOptions("clientId", "clientSecret");
                        var actionstepService   = new ActionstepService(new NullLogger <ActionstepService>(), httpClient, options, testTokenRepository, fakeClock, memoryCache);

                        var now = fakeClock.GetCurrentInstant();

                        /// We're using the TokenType purely as a mechanism to talk to <see cref="TestTokenSetRepository"/>.
                        /// This allows us to delay one refresh while queueing another to ensure the locking/retry works correctly
                        /// with concurrent refresh requests.
                        var tokenTypeTest1 = "bearer-test1";
                        var tokenTypeTest2 = "bearer-test2";

                        // First, store a locked expired token
                        var tokenId   = "locking test token";
                        var tokenSet1 = new TokenSet(
                            "testAccessToken1",
                            tokenTypeTest1,
                            3600,
                            new Uri("https://api.uri/api/auto-increment/"),
                            "testOrgKey",
                            "testRefreshToken1",
                            now.Minus(Duration.FromMinutes(120)),
                            "testUser",
                            tokenId);

                        tokenSet1.LockForRefresh(now.Plus(Duration.FromMinutes(60)));
                        var storedTokenSet1 = await testTokenRepository.AddOrUpdateTokenSet(tokenSet1);

                        // Now we set up a second expired token with the same id.
                        var tokenSet2 = new TokenSet(
                            "testAccessToken2",
                            tokenTypeTest2,
                            3600,
                            new Uri("https://api.uri/api/auto-increment/"),
                            "testOrgKey",
                            "testRefreshToken2",
                            now.Minus(Duration.FromMinutes(120)),
                            "testUser",
                            tokenId);

                        // Try to refresh using the second token (which has the same tokenId). It should be blocked by the locked token1 from above.
                        var tokenSet2RefreshTask = actionstepService.RefreshAccessTokenIfExpired(tokenSet2, forceRefresh: false);

                        /// Delay to give the <see cref="RefreshAccessTokenIfExpired"/> a chance to
                        await Task.Delay(50);

                        // Now store a valid token of test type 1, this will unlock the token
                        tokenSet1 = new TokenSet(
                            "testAccessToken1",
                            tokenTypeTest1,
                            3600,
                            new Uri("https://api.uri/api/auto-increment/"),
                            "testOrgKey",
                            "testRefreshToken1",
                            now,
                            "testUser",
                            tokenId);

                        await testTokenRepository.AddOrUpdateTokenSet(tokenSet1);

                        tokenSet2RefreshTask.Wait();

                        // The token from the refresh should be the one we put in the repository.
                        Assert.Equal(tokenTypeTest1, tokenSet2RefreshTask.Result.TokenType);
                    }
        }
        public async Task Instant_DateDiff_Minute()
        {
            var raceResults = await this.Db.RaceResult.Where(r => this.Functions.DateDiffMinute(r.StartTime, Instant.FromUtc(2019, 7, 1, 0, 0)) <= 100000).ToListAsync();

            Assert.Equal(
                condense(@$ "{RaceResultSelectStatement} WHERE DATEDIFF(MINUTE, [r].[StartTime], '2019-07-01T00:00:00.0000000Z') <= 100000"),
                condense(this.Db.Sql));

            Assert.Equal(8, raceResults.Count);
        }
        public async Task Instant_DateDiff_Month()
        {
            var raceResults = await this.Db.RaceResult.Where(r => this.Functions.DateDiffMonth(r.StartTime, Instant.FromUtc(2020, 1, 1, 0, 0)) >= 1).ToListAsync();

            Assert.Equal(
                condense(@$ "{RaceResultSelectStatement} WHERE DATEDIFF(MONTH, [r].[StartTime], '2020-01-01T00:00:00.0000000Z') >= 1"),
                condense(this.Db.Sql));

            Assert.Equal(12, raceResults.Count);
        }
Example #20
0
 public void TestToString_Padding()
 {
     TestToStringBase(Instant.FromUtc(1, 1, 1, 12, 34, 56), "0001-01-01T12:34:56Z");
 }
        public void CreateInterval()
        {
            // Arrange
            var generator = Fixture.Create <Generator <Interval> >();

            bool Predicate(Interval interval) => Instant.FromUtc(1900, 01, 01, 00, 00) <= interval.Start && interval.End < Instant.FromUtc(2100, 01, 01, 00, 00);

            // Act
            var allSatisfyPredicate = generator.Take(100).All(Predicate);

            // Assert
            allSatisfyPredicate.Should().BeTrue();
        }
Example #22
0
 /// <summary>
 /// Returns a fake clock initially set to the given year/month/day/time in UTC in the ISO calendar.
 /// The value of the <see cref="AutoAdvance"/> property will be initialised to zero.
 /// </summary>
 /// <param name="year">The year. This is the "absolute year",
 /// so a value of 0 means 1 BC, for example.</param>
 /// <param name="monthOfYear">The month of year.</param>
 /// <param name="dayOfMonth">The day of month.</param>
 /// <param name="hourOfDay">The hour.</param>
 /// <param name="minuteOfHour">The minute.</param>
 /// <param name="secondOfMinute">The second.</param>
 /// <returns>A <see cref="FakeClock"/> initialised to the given instant, with no auto-advance.</returns>
 public static FakeClock FromUtc(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute)
 {
     return(new FakeClock(Instant.FromUtc(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute)));
 }
 public void GenerateCodeLiteral_returns_Instant_literal()
 => Assert.Equal("NodaTime.Instant.FromUnixTimeTicks(15832607590000000L)",
                 CodeLiteral(Instant.FromUtc(2020, 3, 3, 18, 39, 19)));
Example #24
0
        public void FromUtcWithSeconds()
        {
            Instant viaUtc = DateTimeZone.Utc.AtStrictly(new LocalDateTime(2008, 4, 3, 10, 35, 23)).ToInstant();

            Assert.AreEqual(viaUtc, Instant.FromUtc(2008, 4, 3, 10, 35, 23));
        }
        public async Task Instant_DateDiff_Big_Second()
        {
            var raceResults = await this.Db.RaceResult.Where(r => this.Functions.DateDiffBigSecond(r.StartTime, Instant.FromUtc(2019, 7, 1, 0, 0)) >= 100000).ToListAsync();

            Assert.Equal(
                condense(@$ "{RaceResultSelectStatement} WHERE DATEDIFF_BIG(SECOND, [r].[StartTime], '2019-07-01T00:00:00.0000000Z') >= CAST(100000 AS bigint)"),
                condense(this.Db.Sql));

            Assert.Equal(6, raceResults.Count);
        }
Example #26
0
 public ClockServiceTests()
 {
     _timeZone  = DateTimeZoneProviders.Tzdb.GetZoneOrNull("US/Pacific");
     _now       = Instant.FromUtc(2017, 2, 14, 0, 0, 0);
     _fakeClock = new FakeClock(_now);
 }
Example #27
0
 public static Instant SnowflakeToInstant(ulong snowflake) =>
 Instant.FromUtc(2015, 1, 1, 0, 0, 0) + Duration.FromMilliseconds(snowflake >> 22);
        public async Task Instant_DateDiff_Big_Nanosecond()
        {
            var raceResults = await this.Db.RaceSplit.Where(r => this.Functions.DateDiffBigNanosecond(Instant.FromUtc(2020, 1, 1, 0, 0), r.TimeStampInstant) <= 15000000000000).ToListAsync();

            Assert.Equal(
                condense(@$ "{RaceSplitSelectStatement} WHERE DATEDIFF_BIG(NANOSECOND, '2020-01-01T00:00:00.0000000Z', [r].[TimeStampInstant]) <= CAST(15000000000000 AS bigint)"),
                condense(this.Db.Sql));

            Assert.Equal(4, raceResults.Count);
        }
Example #29
0
 public Instant GetCurrentInstant()
 {
     return(Instant.FromUtc(1970, 1, 1, 0, 0, 0));
 }
        public async Task Instant_PlusSeconds()
        {
            var raceResults = await this.Db.RaceResult.Where(r => r.StartTime.PlusSeconds(45) >= Instant.FromUtc(2019, 7, 1, 1, 0)).ToListAsync();

            Assert.Equal(
                condense(@$ "{RaceResultSelectStatement} WHERE DATEADD(second, CAST(45.0E0 AS int), [r].[StartTime]) >= '2019-07-01T01:00:00.0000000Z'"),
                condense(this.Db.Sql));

            Assert.Equal(6, raceResults.Count);
        }