コード例 #1
0
        public ChannelAdminBotTestFixture(TestsFixture fixture)
        {
            AddLifetime(
                initialize: async() =>
            {
                _channelChatFixture = new(fixture, Constants.TestCollections.ChannelAdminBots);
                await _channelChatFixture.InitializeAsync();
                // Save existing chat photo as byte[] to restore it later because Bot API 4.4+ invalidates old
                // file_ids after changing chat photo
                if (!string.IsNullOrEmpty(Chat.Photo?.BigFileId))
                {
                    await using MemoryStream stream = new();
                    await fixture.BotClient.GetInfoAndDownloadFileAsync(Chat.Photo.BigFileId, stream);
                    _oldChatPhoto = stream.ToArray();
                }
            },
                dispose: async() =>
            {
                // If chat had a photo before, reset the photo back.
                if (_oldChatPhoto is not null)
                {
                    await using MemoryStream photoStream = new(_oldChatPhoto);
                    await fixture.BotClient.SetChatPhotoAsync(
                        chatId: Chat.Id,
                        photo: photoStream
                        );
                }

                await _channelChatFixture.DisposeAsync();
            }
                );
        }
        private static async Task <Chat> GetChat(TestsFixture testsFixture, string collectionName)
        {
            Chat chat;

            if (int.TryParse(ConfigurationProvider.TestConfigurations.RegularGroupMemberId, out int userId))
            {
                chat = await testsFixture.BotClient.GetChatAsync(userId);
            }
            else
            {
                await testsFixture.UpdateReceiver.DiscardNewUpdatesAsync();

                await testsFixture.SendTestCollectionNotificationAsync(collectionName,
                                                                       $"No value is set for `{nameof(ConfigurationProvider.TestConfigurations.RegularGroupMemberId)}` " +
                                                                       "in test settings.\n" +
                                                                       "An admin should forward a message from non-admin member or send his/her contact."
                                                                       );

                chat = await testsFixture.GetChatFromAdminAsync();
            }

            if (chat.Username is null)
            {
                await testsFixture.SendTestCollectionNotificationAsync(collectionName,
                                                                       $"[{chat.FirstName}](tg://user?id={chat.Id}) doesn't have a username.\n" +
                                                                       "❎ Failing tests...");

                throw new ArgumentNullException(nameof(chat.Username), "Chat member doesn't have a username");
            }

            return(chat);
        }
コード例 #3
0
        public MessageReplyMarkupTestsFixture(TestsFixture testsFixture)
        {
            TestsFixture = testsFixture;

            var privateChatId = ConfigurationProvider.TestConfigurations.TesterPrivateChatId;

            if (privateChatId is null)
            {
                TestsFixture.SendTestCollectionNotificationAsync(
                    Constants.TestCollections.MessageReplyMarkup,
                    "A tester should send /test command in a private chat to begin")
                .Wait();

                TestsFixture.UpdateReceiver.DiscardNewUpdatesAsync().Wait();
                TesterPrivateChatId = TestsFixture.GetChatIdFromTesterAsync(ChatType.Private).Result;
            }
            else
            {
                TesterPrivateChatId = privateChatId;

                TestsFixture.SendTestCollectionNotificationAsync(Constants.TestCollections.MessageReplyMarkup,
                                                                 "All messages for this collection will be sent in private chat")
                .Wait();

                TestsFixture.SendTestCollectionNotificationAsync(Constants.TestCollections.MessageReplyMarkup, chatid: TesterPrivateChatId)
                .Wait();
            }
        }
コード例 #4
0
        public async Task Should_Throw_Exception_When_Answering_Late()
        {
            await TestsFixture.SendTestInstructionsAsync(
                "Write an inline query that I'll never answer!",
                startInlineQuery : true
                );

            Update queryUpdate = await TestsFixture.UpdateReceiver.GetInlineQueryUpdateAsync();

            InlineQueryResultBase[] results =
            {
                new InlineQueryResultArticle(
                    id: "article:bot-api",
                    title: "Telegram Bot API",
                    inputMessageContent: new InputTextMessageContent("https://core.telegram.org/bots/api"))
                {
                    Description = "The Bot API is an HTTP-based interface created for developers",
                },
            };

            await Task.Delay(10_000);

            InvalidQueryIdException exception = await Assert.ThrowsAsync <InvalidQueryIdException>(
                async() => await BotClient.AnswerInlineQueryAsync(
                    inlineQueryId: queryUpdate.InlineQuery !.Id,
                    results: results,
                    cacheTime: 0
                    )
                );

            Assert.Equal(400, exception.ErrorCode);
            Assert.Contains("query is too old and response timeout expired or query ID is invalid", exception.Message);
        }
コード例 #5
0
        private static async Task <Chat> GetChat(TestsFixture testsFixture, string collectionName)
        {
            Chat chat;

            if (int.TryParse(ConfigurationProvider.TestConfigurations.RegularGroupMemberId, out int userId))
            {
                chat = await testsFixture.BotClient.GetChatAsync(userId);
            }
            else
            {
                await testsFixture.UpdateReceiver.DiscardNewUpdatesAsync();

                string botUserName = testsFixture.BotUser.Username;
                await testsFixture.SendTestCollectionNotificationAsync(collectionName,
                                                                       $"No value is set for `{nameof(ConfigurationProvider.TestConfigurations.RegularGroupMemberId)}` " +
                                                                       $"in test settings. A non-admin chat member should send /test command in private chat with " +
                                                                       $"@{botUserName.Replace("_", @"\_")}."
                                                                       );

                chat = await testsFixture.GetChatFromTesterAsync(ChatType.Private);
            }

            if (chat.Username == null)
            {
                await testsFixture.SendTestCollectionNotificationAsync(collectionName,
                                                                       $"[{chat.FirstName}](tg://user?id={chat.Id}) doesn't have a username.\n" +
                                                                       "❎ Failing tests...");

                throw new ArgumentNullException(nameof(chat.Username), "Chat member doesn't have a username");
            }

            return(chat);
        }
コード例 #6
0
        protected AllChatsFixture(TestsFixture testsFixture, string collectionName)
            : base(testsFixture, collectionName)
        {
            var _ = new PrivateChatFixture(testsFixture, collectionName);

            SupergroupChat = testsFixture.SupergroupChat;
            PrivateChat    = testsFixture.PrivateChat;
        }
コード例 #7
0
        private static async Task <User> GetPlayerIdFromChatAdmins(TestsFixture testsFixture, long chatId)
        {
            ChatMember[] admins = await testsFixture.BotClient.GetChatAdministratorsAsync(chatId);

            ChatMember player = admins[new Random(DateTime.Now.Millisecond).Next(admins.Length)];

            return(player.User);
        }
コード例 #8
0
 public IdentityCardAndUtilityBillTests(
     TestsFixture fixture, EntityFixture <Update> classFixture, ITestOutputHelper output
     )
 {
     _fixture      = fixture;
     _classFixture = classFixture;
     _output       = output;
 }
コード例 #9
0
 public Interactive_BadRequestExceptionTests(
     TestsFixture testsFixture,
     PrivateChatFixture classFixture,
     PaymentFixture paymentFixture)
 {
     TestsFixture    = testsFixture;
     Fixture         = classFixture;
     _paymentFixture = paymentFixture;
 }
コード例 #10
0
        public ChannelChatFixture(TestsFixture testsFixture, string collectionName)
        {
            _testsFixture = testsFixture;

            if (_testsFixture.ChannelChat is default)
            {
                _testsFixture.ChannelChat = GetChat(collectionName).GetAwaiter().GetResult();
            }
            ChannelChat = _testsFixture.ChannelChat;

            ChannelChatId = ChannelChat.Username is default
コード例 #11
0
        public StickersTestsFixture(TestsFixture testsFixture)
        {
            TestStickerSetName = $"test14_by_{testsFixture.BotUser.Username}";
            int?ownerUserId = ConfigurationProvider.TestConfigurations.StickerOwnerUserId;

            if (ownerUserId == default)
            {
                // ToDo: use /me command to select owner at test execution time
                ownerUserId = 0;
            }

            OwnerUserId = ownerUserId.Value;
        }
コード例 #12
0
        public PaymentFixture(TestsFixture testsFixture)
            : base(testsFixture, Constants.TestCollections.Payment)
        {
            PaymentProviderToken = ConfigurationProvider.TestConfigurations.PaymentProviderToken;
            if (PaymentProviderToken is null)
            {
                throw new ArgumentNullException(nameof(PaymentProviderToken));
            }

            if (PaymentProviderToken.Length < 5)
            {
                throw new ArgumentException("Payment provider token is invalid", nameof(PaymentProviderToken));
            }
        }
コード例 #13
0
        public ChatMemberAdministrationTestFixture(TestsFixture testsFixture)
        {
            string collectionName = Constants.TestCollections.ChatMemberAdministration;

            RegularMemberChat = GetChat(testsFixture, collectionName).GetAwaiter().GetResult();

            testsFixture.SendTestCollectionNotificationAsync(
                collectionName,
                $"Chosen regular member is @{RegularMemberChat.Username.Replace("_", @"\_")}"
                ).GetAwaiter().GetResult();

            RegularMemberUserId   = (int)RegularMemberChat.Id;
            RegularMemberUserName = RegularMemberChat.Username;
        }
コード例 #14
0
        public ChatMemberAdministrationTestFixture(TestsFixture testsFixture)
        {
            TestsFixture = testsFixture;

            bool isUserIdNull   = string.IsNullOrWhiteSpace(ConfigurationProvider.TestConfigurations.RegularMemberUserId);
            bool isUserNameNull =
                string.IsNullOrWhiteSpace(ConfigurationProvider.TestConfigurations.RegularMemberUserName);
            bool isChatIdNull = string.IsNullOrWhiteSpace(ConfigurationProvider.TestConfigurations
                                                          .RegularMemberPrivateChatId);

            // All must have values or all must be null
            if (!(isUserIdNull == isUserNameNull && isUserNameNull == isChatIdNull))
            {
                throw new ArgumentException("All (or none) of Regular Chat Member configurations should be provided");
            }

            bool configValuesExist = !isUserIdNull;

            if (configValuesExist)
            {
                RegularMemberUserId        = int.Parse(ConfigurationProvider.TestConfigurations.RegularMemberUserId);
                RegularMemberUserName      = ConfigurationProvider.TestConfigurations.RegularMemberUserName;
                RegularMemberPrivateChatId = ConfigurationProvider.TestConfigurations.RegularMemberPrivateChatId;

                TestsFixture.SendTestCollectionNotificationAsync(
                    CommonConstants.TestCollections.ChatMemberAdministration).Wait();
            }
            else
            {
                TestsFixture.SendTestCollectionNotificationAsync(
                    CommonConstants.TestCollections.ChatMemberAdministration,
                    "A non-admin chat member should send /me command so bot can use his/her user id during tests")
                .Wait();

                Message replyInGroup = GetRegularGroupChatMemberUserIdAsync().Result;
                RegularMemberUserId   = replyInGroup.From.Id;
                RegularMemberUserName = replyInGroup.From.Username;

                TestsFixture.UpdateReceiver.DiscardNewUpdatesAsync().Wait();

                TestsFixture.BotClient.SendTextMessageAsync(TestsFixture.SuperGroupChatId,
                                                            $"Now, {RegularMemberUserName} should send bot /me command in his/her private chat with bot",
                                                            ParseMode.Markdown,
                                                            replyToMessageId: replyInGroup.MessageId).Wait();

                Message replyInPrivate = GetRegularMemberPrivateChatIdAsync(RegularMemberUserId).Result;
                RegularMemberPrivateChatId = replyInPrivate.Chat.Id;
            }
        }
コード例 #15
0
        public PrivateChatFixture(TestsFixture testsFixture, string collectionName)
        {
            _testsFixture = testsFixture;

            if (_testsFixture.PrivateChat == null)
            {
                _testsFixture.PrivateChat = GetChat(collectionName).GetAwaiter().GetResult();
            }
            PrivateChat = _testsFixture.PrivateChat;

            _testsFixture.SendTestCollectionNotificationAsync(
                collectionName,
                $"Tests will be executed in chat with @{PrivateChat.Username.Replace("_", @"\_")}"
                ).GetAwaiter().GetResult();
        }
コード例 #16
0
        public PrivateChatFixture(TestsFixture testsFixture, string collectionName)
        {
            AddLifetime(
                initialize: async() =>
            {
                testsFixture.PrivateChat ??= await GetChat(testsFixture, collectionName);
                PrivateChat = testsFixture.PrivateChat;

                await testsFixture.SendTestCollectionNotificationAsync(
                    collectionName,
                    $"Tests will be executed in chat with @{PrivateChat.GetSafeUsername()}"
                    );
            }
                );
        }
コード例 #17
0
        public BotCommandsFixture(TestsFixture testsFixture)
        {
            _testsFixture = testsFixture;

            AddLifetime(
                initialize: async() => _originalCommands = await _testsFixture.BotClient.GetMyCommandsAsync(),
                dispose: async() =>
            {
                // restore original bot commands
                if (_originalCommands?.Length != 0)
                {
                    await _testsFixture.BotClient.SetMyCommandsAsync(_originalCommands);
                }
            }
                );
        }
コード例 #18
0
        public ChatMemberAdministrationTestFixture(TestsFixture testsFixture)
        {
            _testsFixture = testsFixture;
            const string collectionName = Constants.TestCollections.ChatMemberAdministration;

            RegularMemberChat = GetChat(_testsFixture, collectionName).GetAwaiter().GetResult();

            testsFixture.SendTestCollectionNotificationAsync(
                collectionName,
                $"Chosen regular member is @{RegularMemberChat.Username.Replace("_", @"\_")}"
                ).GetAwaiter().GetResult();

            RegularMemberUserId   = RegularMemberChat.Id;
            RegularMemberUserName = RegularMemberChat.Username;
            // Updates from regular user will be received
            _testsFixture.UpdateReceiver.AllowedUsernames.Add(RegularMemberUserName);
        }
コード例 #19
0
        public ChannelChatFixture(TestsFixture testsFixture, string collectionName)
        {
            _testsFixture = testsFixture;

            if (_testsFixture.ChannelChat == null)
            {
                _testsFixture.ChannelChat = GetChat(collectionName).GetAwaiter().GetResult();
            }
            ChannelChat = _testsFixture.ChannelChat;

            ChannelChatId = ChannelChat.Username == null
                ? ChannelChat.Id.ToString()
                : '@' + ChannelChat.Username;

            _testsFixture.SendTestCollectionNotificationAsync(
                collectionName,
                $"Tests will be executed in channel {ChannelChatId.Replace("_", @"\_")}"
                ).GetAwaiter().GetResult();
        }
        public SupergroupAdminBotTestsFixture(TestsFixture testsFixture)
        {
            TestsFixture   = testsFixture;
            PinnedMessages = new List <Message>(3);

            AddLifetime(
                initialize: async() =>
            {
                Chat chat = await TestsFixture.BotClient.GetChatAsync(TestsFixture.SupergroupChat);

                // Save existing chat photo as byte[] to restore it later because Bot API 4.4+ invalidates old
                // file_ids after changing chat photo
                if (!string.IsNullOrEmpty(chat.Photo?.BigFileId))
                {
                    await using MemoryStream stream = new();
                    await TestsFixture.BotClient.GetInfoAndDownloadFileAsync(chat.Photo.BigFileId, stream);

                    _oldChatPhoto = stream.ToArray();
                }

                // Save default permissions so they can be restored
                ExistingDefaultPermissions = chat.Permissions;
            },
                dispose: async() =>
            {
                // If chat had a photo before, reset the photo back.
                if (_oldChatPhoto is not null)
                {
                    await using MemoryStream photoStream = new(_oldChatPhoto);
                    await TestsFixture.BotClient.SetChatPhotoAsync(
                        chatId: Chat.Id,
                        photo: photoStream
                        );
                }

                // Reset original default permissions
                await TestsFixture.BotClient.SetChatPermissionsAsync(
                    TestsFixture.SupergroupChat,
                    ExistingDefaultPermissions
                    );
            }
                );
        }
コード例 #21
0
        public GamesFixture(TestsFixture fixture)
        {
            _fixture = fixture;

            GameShortName = "game1";

            try
            {
                fixture.BotClient.SendGameAsync(fixture.SupergroupChat.Id, GameShortName).GetAwaiter().GetResult();
            }
            catch (InvalidGameShortNameException e)
            {
                throw new ArgumentException(
                          $@"Bot doesn't have game: ""{GameShortName}"". Make sure you set up a game with @BotFather.",
                          e.Parameter, e
                          );
            }

            Player = GetPlayerIdFromChatAdmins(fixture.SupergroupChat.Id)
                     .GetAwaiter().GetResult();
        }
コード例 #22
0
        public ChannelChatFixture(TestsFixture testsFixture, string collectionName)
        {
            _testsFixture = testsFixture;

            AddLifetime(
                initialize: async() =>
            {
                _testsFixture.ChannelChat ??= await GetChat(collectionName);
                ChannelChat = _testsFixture.ChannelChat;

                ChannelChatId = ChannelChat.Username is null
                        ? ChannelChat.Id.ToString()
                        : $"@{ChannelChat.GetSafeUsername()}";

                await _testsFixture.SendTestCollectionNotificationAsync(
                    collectionName,
                    $"Tests will be executed in channel {ChannelChatId}"
                    );
            }
                );
        }
コード例 #23
0
        public PaymentTestsFixture(TestsFixture testsFixture)
        {
            TestsFixture = testsFixture;

            PaymentProviderToken = ConfigurationProvider.TestConfigurations.PaymentProviderToken;
            if (string.IsNullOrWhiteSpace(PaymentProviderToken))
            {
                throw new ArgumentNullException(nameof(PaymentProviderToken),
                                                "Payment provider token is not provided or is empty.");
            }

            if (PaymentProviderToken.Length < 15)
            {
                throw new ArgumentException("Payment provider token is too short.", nameof(PaymentProviderToken));
            }

            string privateChatId = ConfigurationProvider.TestConfigurations.TesterPrivateChatId;

            if (string.IsNullOrWhiteSpace(privateChatId))
            {
                TestsFixture.SendTestCollectionNotificationAsync(
                    CommonConstants.TestCollections.Payment,
                    "A tester should send /test command in a private chat to begin")
                .Wait();

                TestsFixture.UpdateReceiver.DiscardNewUpdatesAsync().Wait();
                TesterPrivateChatId = TestsFixture.GetChatIdFromTesterAsync(ChatType.Private).Result;
            }
            else
            {
                TesterPrivateChatId = privateChatId;

                TestsFixture.SendTestCollectionNotificationAsync(CommonConstants.TestCollections.Payment,
                                                                 "All messages for this collection will be sent in private chat")
                .Wait();

                TestsFixture.SendTestCollectionNotificationAsync(CommonConstants.TestCollections.Payment, chatid: TesterPrivateChatId)
                .Wait();
            }
        }
コード例 #24
0
        public GamesFixture(TestsFixture fixture)
        {
            GameShortName = "game1";

            AddLifetime(
                initialize: async() =>
            {
                try
                {
                    await fixture.BotClient.SendGameAsync(fixture.SupergroupChat.Id, GameShortName);
                }
                catch (InvalidGameShortNameException e)
                {
                    throw new ArgumentException(
                        $@"Bot doesn't have game: ""{GameShortName}"". Make sure you set up a game with @BotFather.",
                        e.Parameter, e
                        );
                }

                Player = await GetPlayerIdFromChatAdmins(fixture, fixture.SupergroupChat.Id);
            }
                );
        }
コード例 #25
0
        private static async Task <Chat> GetChat(TestsFixture testsFixture, string collectionName)
        {
            Chat chat;
            long?chatId = ConfigurationProvider.TestConfigurations.TesterPrivateChatId;

            if (chatId.HasValue)
            {
                chat = await testsFixture.BotClient.GetChatAsync(chatId);
            }
            else
            {
                await testsFixture.UpdateReceiver.DiscardNewUpdatesAsync();

                string botUsername = testsFixture.BotUser.GetSafeUsername();
                await testsFixture.SendTestCollectionNotificationAsync(collectionName,
                                                                       $"No value is set for `{nameof(ConfigurationProvider.TestConfigurations.TesterPrivateChatId)}` in test " +
                                                                       $"settings. Tester should send /test command in private chat with @{botUsername}."
                                                                       );

                chat = await testsFixture.GetChatFromTesterAsync(ChatType.Private);
            }
            return(chat);
        }
コード例 #26
0
        private static async Task <int> GetStickerOwnerIdAsync(TestsFixture testsFixture, string collectionName)
        {
            int ownerId;

            if (ConfigurationProvider.TestConfigurations.StickerOwnerUserId == default)
            {
                await testsFixture.UpdateReceiver.DiscardNewUpdatesAsync();

                Message notifMessage = await testsFixture.SendTestCollectionNotificationAsync(collectionName,
                                                                                              $"\nNo value is set for `{nameof(ConfigurationProvider.TestConfigurations.StickerOwnerUserId)}` " +
                                                                                              "in test settings.\n\n" +
                                                                                              ""
                                                                                              );

                const string cqData    = "sticker_tests:owner";
                Message      cqMessage = await testsFixture.BotClient.SendTextMessageAsync(
                    testsFixture.SupergroupChat,
                    testsFixture.UpdateReceiver.GetTesters() +
                    "\nUse the following button to become Sticker Set Owner",
                    replyToMessageId : notifMessage.MessageId,
                    replyMarkup : new InlineKeyboardMarkup(
                        InlineKeyboardButton.WithCallbackData("I am the Owner!", cqData)
                        )
                    );

                Update cqUpdate = await testsFixture.UpdateReceiver
                                  .GetCallbackQueryUpdateAsync(cqMessage.MessageId, cqData);

                ownerId = cqUpdate.CallbackQuery.From.Id;
            }
            else
            {
                ownerId = ConfigurationProvider.TestConfigurations.StickerOwnerUserId.Value;
            }

            return(ownerId);
        }
コード例 #27
0
        public ChatMemberAdministrationTestFixture(TestsFixture testsFixture)
        {
            AddLifetime(
                initialize: async() =>
            {
                const string collectionName = Constants.TestCollections.ChatMemberAdministration;

                RegularMemberChat = await GetChat(testsFixture, collectionName);

                await testsFixture.SendTestCollectionNotificationAsync(
                    collectionName,
                    $"Chosen regular member is @{RegularMemberChat.GetSafeUsername()}"
                    );

                RegularMemberUserId   = RegularMemberChat.Id;
                RegularMemberUserName = RegularMemberChat.Username;
                // Updates from regular user will be received
                testsFixture.UpdateReceiver.AllowedUsernames.Add(RegularMemberUserName);
            }
                );

            // Remove regular user from AllowedUserNames
            AddLifetime(() => testsFixture.UpdateReceiver.AllowedUsernames.Remove(RegularMemberUserName));
        }
コード例 #28
0
 public ApiExceptionsTests(TestsFixture fixture)
 {
     _fixture = fixture;
 }
コード例 #29
0
 public SendingPhotoMessageTests(TestsFixture fixture, EntityFixture <Message> classFixture)
 {
     _fixture      = fixture;
     _classFixture = classFixture;
 }
コード例 #30
0
 public EditMessageContentTests2(TestsFixture fixture)
 {
     _fixture = fixture;
 }