public async void function_http_trigger_should_return_401_if_SonarqubeSecretValidator_rejects_request()
        {
            // Arrange
            SetEnvironmentVariables();

            var request = TestFactory.CreateHttpRequest();

            var sonarqubeSecretValidator = new Mock <ISonarqubeSecretValidator>();

            sonarqubeSecretValidator.Setup(x => x.IsValidSignature(
                                               request,
                                               It.IsAny <string>(),
                                               Environment.GetEnvironmentVariable(SonarqubeMSTeamsBridge.Setting_SonarqubeWebhookSecret))
                                           ).Returns(false);

            var        sonarqubeMSTeamsBridgeFunction = new SonarqubeMSTeamsBridge(null, sonarqubeSecretValidator.Object, null, null);
            ListLogger logger = (ListLogger)TestFactory.CreateLogger(LoggerTypes.List);

            // Act
            var response = (StatusCodeResult)await sonarqubeMSTeamsBridgeFunction.Run(request, logger);

            // Assert
            Assert.Equal(401, response.StatusCode);
            Assert.Contains($"Sonarqube secret http header is missing or not valid. Config setting {SonarqubeMSTeamsBridge.Setting_SonarqubeWebhookSecret} must match secret in Sonarqube Webhook header {SonarqubeSecretValidator.SonarqubeAuthSignatureHeaderName}.", logger.Logs);
        }
        public async void basic_healthcheck_returns_ok()
        {
            var request  = TestFactory.CreateHttpRequest();
            var response = (OkObjectResult)await HealthFunction.Run(request, "basic", logger);

            Assert.Equal("healthy", response.Value);
        }
Beispiel #3
0
        [InlineData("17")]                    // parameter is given, but out of range number value
        public async Task Run_Should_Return_BadRequest_When_Invalid_runtime_argument_given(string argumentValue)
        {
            //  Arrange

            var trigger = new Trigger(_mockBenchMarkResultService.Object, _mockResponseConverter.Object);

            var request = TestFactory.CreateHttpRequest(new Dictionary <string, StringValues>()
            {
                { "cloudProvider", "Azure" },
                { "hostingEnvironment", "Windows" },
                { "runtime", argumentValue },
            });



            //  Act

            var response = await trigger.Run(request, _logger);



            //  Assert

            Assert.IsType <BadRequestResult>(response);
        }
Beispiel #4
0
        public async Task Run_Should_Return_NotFoundResult_When_Service_returns_No_BenchMarkData()
        {
            //  Arrange

            Environment.SetEnvironmentVariable("dayRange", "1");
            _mockBenchMarkResultService.Setup(c => c.GetDateTimeNow()).Returns(new DateTime(2020, 1, 2));

            var benchMarkResults = new List <BenchMarkResult>();

            _mockBenchMarkResultService.Setup(c =>
                                              c.GetBenchMarkResultsAsync(It.IsAny <CloudProvider>(), It.IsAny <HostEnvironment>(), It.IsAny <Runtime>(), It.IsAny <DateTime>()))
            .Returns(Task.FromResult(benchMarkResults));

            var trigger = new Trigger(_mockBenchMarkResultService.Object, _mockResponseConverter.Object);
            var request = TestFactory.CreateHttpRequest(new Dictionary <string, StringValues>()
            {
                { "cloudProvider", "Firebase" }, { "hostingEnvironment", "Linux" }, { "runtime", "Fsharp" }
            });



            //  Act

            var response = await trigger.Run(request, _logger);



            //  Assert

            Assert.IsType <NotFoundResult>(response);
        }
        public HttpRequest Build()
        {
            var req = TestFactory.CreateHttpRequest();

            if (authHeader != null)
            {
                req.Headers.Add("Authorization", $"Bearer {authHeader}");
            }
            if (query != null)
            {
                req.Query = new QueryCollection(query);
            }

            if (body != null)
            {
                var json   = JsonConvert.SerializeObject(body);
                var stream = new MemoryStream();
                var writer = new StreamWriter(stream);
                writer.Write(json);
                writer.Flush();
                stream.Position = 0;

                req.Body = stream;
            }

            return(req);
        }
Beispiel #6
0
        public async void ReturnKnownStringFromData(string queryStringKey, string queryStringValue)
        {
            var request  = TestFactory.CreateHttpRequest(queryStringKey, queryStringValue);
            var response = (OkObjectResult)await DefaultHttpTemplate.Run(request, logger);

            Assert.Equal($"Hello, {queryStringValue}. This HTTP triggered function executed successfully.", response.Value);
        }
Beispiel #7
0
        public async Task FunctionShouldReturnProvidedName()
        {
            #region Arrange

            string nameValue = "BenchCloud";

            var request = TestFactory.CreateHttpRequest(new Dictionary <string, StringValues>()
            {
                { "name", nameValue }
            });

            #endregion

            #region Act

            var response = await Trigger.Run(request, _logger);

            #endregion

            #region Assert

            var responseObject = Assert.IsType <OkObjectResult>(response);
            Assert.Equal($"Hello, {nameValue}", responseObject.Value);

            #endregion
        }
Beispiel #8
0
        public async Task GetDocumentLibraries_Returns_DocumentLibraries_When_Found()
        {
            // Arrange
            var req               = TestFactory.CreateHttpRequest();
            var logger            = TestFactory.CreateLogger(LoggerTypes.List);
            var documentLibraries = new List <DocumentLibrary>
            {
                new DocumentLibrary {
                    Id = "Id1", Name = "DocumentLibrary1"
                },
                new DocumentLibrary {
                    Id = "Id2", Name = "DocumentLibrary2"
                },
            };

            _fileServiceMock.Setup(x => x.GetDocumentLibrariesAsync(It.Is <string>(p => p == "siteId"))).ReturnsAsync(DocumentLibrariesResult.Success(documentLibraries));

            // Act
            var httpActionResult = await _controller.GetDocumentLibraries(req, logger);

            // Assert
            Assert.IsInstanceOf(typeof(OkObjectResult), httpActionResult);

            _fileServiceMock.Verify(x => x.GetDocumentLibrariesAsync(It.Is <string>(p => p == "siteId")), Times.Once);

            var result = ((OkObjectResult)httpActionResult).Value as DocumentLibraryModelInfo[];

            Assert.IsNotNull(result);
            Assert.AreEqual(2, result.Length);
            Assert.AreEqual("Id1", result[0].Id);
            Assert.AreEqual("DocumentLibrary1", result[0].Name);
            Assert.AreEqual("Id2", result[1].Id);
            Assert.AreEqual("DocumentLibrary2", result[1].Name);
        }
Beispiel #9
0
        public async void Should_UploadEnd_Fail_400_With_No_Data()
        {
            var request        = TestFactory.CreateHttpRequest("none", "nil");
            var uploadDir      = _app.Repository.GetBlobDirectory(BlobNames.UploadDirectory + "/test");
            var uploadTmpTable = _app.Repository.GetTable(TableNames.CommUpload);
            var queue          = _app.Repository.GetQueue(QueueNames.CommProcess);

            var tmpUploadEntity = new TableEntityAdapter <UploadSession>(
                new UploadSession {
                SessionId = "test"
            }, "test", new IdGenerator().UploadSessionId());

            // call Azure Function
            var response = (ObjectResult)await UploadFunctions.End(request,
                                                                   "test",
                                                                   $"{DateTime.Now:u} Sample 2.pdf",
                                                                   uploadDir,
                                                                   tmpUploadEntity,
                                                                   uploadTmpTable,
                                                                   queue,
                                                                   _app.App,
                                                                   _logger);

            var upload = response.Value.IsOrMap <UploadSession>();

            Assert.Equal(StatusCodes.Status400BadRequest, response.StatusCode);
            Assert.Null(upload.ManifestFile);
            Assert.Null(upload.LastUploadedFile);
            Assert.Null(upload.UploadEnd);

            _output.WriteLine(upload.ToJson(Formatting.Indented));
        }
Beispiel #10
0
        public async void ReturnAString()
        {
            var request  = TestFactory.CreateHttpRequest("name", "Kevin");
            var response = (OkObjectResult)await DefaultHttpTemplate.Run(request, logger);

            Assert.Equal("Hello, Kevin. This HTTP triggered function executed successfully.", response.Value);
        }
Beispiel #11
0
        private async Task <FunctionResult> CallFunction(FractalOptions options)
        {
            var request = TestFactory.CreateHttpRequest(options);
            var result  = (OkObjectResult)await EntryPoint.RunLocally(request, _logger);

            return((FunctionResult)result.Value);;
        }
Beispiel #12
0
        public async void Http_trigger_should_return_invalid_email(string email)
        {
            var request  = TestFactory.CreateHttpRequest("email", email);
            var response = (BadRequestResult)await EmailValidatorFunction.Run(request, logger);

            Assert.Equal(400, response.StatusCode);
        }
Beispiel #13
0
        public async Task GetFiles_Returns_Files_When_Found()
        {
            // Arrange
            var req               = TestFactory.CreateHttpRequest();
            var logger            = TestFactory.CreateLogger(LoggerTypes.List);
            var documentLibraryId = "documentLibraryId1";
            var files             = new List <File>
            {
                new File
                {
                    Id             = "Id1",
                    Name           = "FileName1",
                    Description    = "FileDescription1",
                    CreatedAt      = new DateTimeOffset(new DateTime(2020, 3, 4)),
                    LastModifiedAt = new DateTimeOffset(new DateTime(2020, 3, 4)),
                    DownloadUrl    = "https://downloadurl1",
                    Size           = 250L
                },
                new File
                {
                    Id             = "Id2",
                    Name           = "FileName2",
                    Description    = "FileDescription2",
                    CreatedAt      = new DateTimeOffset(new DateTime(2020, 3, 5)),
                    LastModifiedAt = new DateTimeOffset(new DateTime(2020, 3, 5)),
                    DownloadUrl    = "https://downloadurl2",
                    Size           = 500L
                }
            };

            _fileServiceMock.Setup(x => x.GetFilesAsync(It.Is <string>(p => p == "siteId"), It.Is <string>(p => p == documentLibraryId))).ReturnsAsync(FilesResult.Success(files));

            // Act
            var httpActionResult = await _controller.GetFiles(req, documentLibraryId, logger);

            // Assert
            Assert.IsInstanceOf(typeof(OkObjectResult), httpActionResult);

            _fileServiceMock.Verify(x => x.GetFilesAsync(It.Is <string>(p => p == "siteId"), It.Is <string>(p => p == documentLibraryId)), Times.Once);

            var result = ((OkObjectResult)httpActionResult).Value as FileModelInfo[];

            Assert.IsNotNull(result);
            Assert.AreEqual(2, result.Length);
            Assert.AreEqual("Id1", result[0].Id);
            Assert.AreEqual("FileName1", result[0].Name);
            Assert.AreEqual("FileDescription1", result[0].Description);
            Assert.AreEqual(new DateTime(2020, 3, 4), result[0].CreatedAt);
            Assert.AreEqual(new DateTime(2020, 3, 4), result[0].LastModifiedAt);
            Assert.AreEqual("https://downloadurl1", result[0].DownloadUrl);
            Assert.AreEqual(250L, result[0].Size);
            Assert.AreEqual("Id2", result[1].Id);
            Assert.AreEqual("FileName2", result[1].Name);
            Assert.AreEqual("FileDescription2", result[1].Description);
            Assert.AreEqual(new DateTime(2020, 3, 5), result[1].CreatedAt);
            Assert.AreEqual(new DateTime(2020, 3, 5), result[1].LastModifiedAt);
            Assert.AreEqual("https://downloadurl2", result[1].DownloadUrl);
            Assert.AreEqual(500L, result[1].Size);
        }
        public async Task Should_CreateItemAsync_When_Collection_IsNull()
        {
            var model    = new MathMultiplyOperationModel();
            var request  = TestFactory.CreateHttpRequest("0", "0");
            var response = (OkObjectResult)await TestMathStartMultiply.Run(request, logger);

            Assert.Equal("Result: 0", "Result: " + ((Quest_Project.Models.MathMultiplyOperationModel)response.Value).Result);
        }
        private static HttpRequestMessage CreateRequest(out ILogger logger, TelegramUpdate requestPayload)
        {
            var request = TestFactory.CreateHttpRequest(HttpMethod.Post, "");

            logger = TestFactory.CreateLogger();
            ;
            request.Content = new ObjectContent <TelegramUpdate>(requestPayload, new JsonMediaTypeFormatter());
            return(request);
        }
Beispiel #16
0
        public async void EventGenerator_should_perform_certain_number_of_actions()
        {
            var request = TestFactory.CreateHttpRequest("amount", "4");
            await _sut.Run(request);

            var logs = ((ListLogger)_logger).Logs;

            Assert.Equal(6, logs.Count);
        }
        public async Task GetMatchingBallotsForPattern_BadRequestWhenNoPattern()
        {
            var request  = TestFactory.CreateHttpRequest();
            var logger   = TestFactory.CreateLogger();
            var svc      = TestFactory.CreateElectionResultsService();
            var response = (BadRequestObjectResult)await new BallotLookup(svc.Object).GetMatchingBallotsForPattern(request, null, logger);

            Assert.IsNotNull(response);
            Assert.AreEqual((int)HttpStatusCode.BadRequest, response.StatusCode);
        }
Beispiel #18
0
        public async void GetSasReturnASasWithPermitionOfRW()
        {
            var request  = TestFactory.CreateHttpRequest("", "");
            var response = await HelloWd.Run(request, logger);

            var result = response as OkObjectResult;

            Assert.Contains("?sv=", result.Value.ToString());;
            Assert.Contains("&sp=rl", result.Value.ToString());;
        }
Beispiel #19
0
        public async void EventGenerator_should_send_action_info_a_certain_number_of_times()
        {
            var request = TestFactory.CreateHttpRequest("amount", "4");
            await _sut.Run(request);

            var logs = ((ListLogger)_logger).Logs;
            var numberOfActionsSent = logs.Where(s => s.Contains("Sending ActionInfo to Event Hub")).Count();

            Assert.Equal(4, numberOfActionsSent);
        }
Beispiel #20
0
        public async Task FunctionShouldReturnOkObjectResultContainingBenchMarkData()
        {
            #region Arrange

            var benchMarkResults = new List <BenchMarkResult>()
            {
                new BenchMarkResult()
                {
                    Id                 = 1,
                    CloudProvider      = 0,
                    HostingEnvironment = 0,
                    Runtime            = 0,
                    CreatedAt          = DateTimeOffset.Now,
                    RequestDuration    = 200,
                    Success            = true
                }
            };

            _mockBenchMarkResultService.Setup(c =>
                                              c.GetBenchMarkResults(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int>()))
            .Returns(Task.FromResult(benchMarkResults));

            var sampleBenchMarkData = new BenchMarkData()
            {
                CloudProvider = "Azure"
            };

            _mockResponseConverter.Setup(c => c.ConvertToBenchMarkData(benchMarkResults))
            .Returns(sampleBenchMarkData);

            var trigger = new Trigger(_mockBenchMarkResultService.Object, _mockResponseConverter.Object);
            var request = TestFactory.CreateHttpRequest(new Dictionary <string, StringValues>()
            {
                { "cloudProvider", "Azure" }, { "hostingEnvironment", "Windows" }, { "runtime", "Csharp" }
            });

            #endregion

            #region Act

            var response = await trigger.Run(request, _logger);

            #endregion

            #region Assert

            var responseObject = Assert.IsType <OkObjectResult>(response);

            var benchMarkData = Assert.IsType <BenchMarkData>(responseObject.Value);

            Assert.Equal(benchMarkData.CloudProvider, sampleBenchMarkData.CloudProvider);

            #endregion
        }
        public async void DarioBotCanHandleBadFormatRequest(string darioRequest, HttpStatusCode expectedStatus)
        {
            var request = TestFactory.CreateHttpRequest(HttpMethod.Post, "");
            var logger  = TestFactory.CreateLogger();

            request.Content = new StringContent(darioRequest);

            var response = await HappyDarioBot.HappyDarioBot.Run(request, logger);

            Assert.Equal(expectedStatus, response.StatusCode);
        }
Beispiel #22
0
        public async void Succeeds_and_returns_a_correctly_formatted_value()
        {
            // Arrange
            var request = TestFactory.CreateHttpRequest();
            // Act
            var response = (OkObjectResult)await VersionFunction.Run(request, logger);

            // Assert
            Assert.Equal(200, response.StatusCode);
            Assert.True(Version.TryParse(response.Value.ToString(), out Version parsed));
        }
        public async Task GetElectionSummary_ReturnDefaultSummary()
        {
            var request  = TestFactory.CreateHttpRequest();
            var logger   = TestFactory.CreateLogger();
            var svc      = TestFactory.CreateElectionResultsService();
            var response = (JsonResult)await new Functions.Api.ElectionSummary(svc.Object).GetElectionSummary(request, logger);
            var summary  = response.Value as Models.ElectionSummary;

            Assert.IsNotNull(summary);
            Assert.IsFalse(summary.IsComplete);
        }
        public void should_greet_with_name_given()
        {
            var httpRequest = TestFactory.CreateHttpRequest("name", TestName);

            A.CallTo(() => greetService.Greet(TestName)).Returns("Welcome!");
            var greetFunctions = new GreetFunctions(greetService, log);

            var response = (OkObjectResult)greetFunctions.Greet(httpRequest);

            Assert.That(log.Logs[0], Is.EqualTo("C# HTTP trigger function processed a request."));
            Assert.That(response.Value, Is.EqualTo("Welcome!"));
        }
        public async Task GetMatchingBallotsForPattern_ReturnsEmptyList()
        {
            var pattern  = "dance";
            var request  = TestFactory.CreateHttpRequest("pattern", pattern);
            var logger   = TestFactory.CreateLogger();
            var svc      = TestFactory.CreateElectionResultsService();
            var response = (JsonResult)await new BallotLookup(svc.Object).GetMatchingBallotsForPattern(request, pattern, logger);
            var list     = response?.Value as List <BallotStatus>;

            Assert.IsNotNull(list);
            Assert.AreEqual(0, list.Count);
        }
Beispiel #26
0
        public async Task Http_trigger_emptykey_should_return_badrequest()
        {
            //Arrange
            string key = "";

            //Act
            var request  = TestFactory.CreateHttpRequest("key", key);
            var response = await HashFunction.Run(request, key, logger);

            //Assert
            Assert.IsInstanceOf <BadRequestObjectResult>(response);
        }
        public async void Version2_algorithm(int inputValue, int expectedResult)
        {
            // Arrange
            var request = TestFactory.CreateHttpRequest();

            Environment.SetEnvironmentVariable("FF_USE_V2_ALGORITHM", "true", EnvironmentVariableTarget.Process);
            // Act
            var response = (OkObjectResult)await CalcFunction.Run(request, inputValue, logger);

            // Assert
            Assert.Equal(expectedResult, response.Value);
        }
Beispiel #28
0
        public async void RoutingTest()
        {
            var formCollection = new Dictionary <string, StringValues>
            {
                { "From", "111-555-4512" },
                { "Body", "" }
            };
            var request       = TestFactory.CreateHttpRequest(formCollection);
            var durableClient = DurableClientFactory.CreateDurableClient("SomeFunction");
            var response      = (OkObjectResult)await FnOrchestrator.Process(request, durableClient, logger);

            Assert.Equal(true, response.Value);
        }
Beispiel #29
0
        public async Task Download_Returns_BadRequest_When_DocumentLibraryIdIsNull()
        {
            // Arrange
            var req = TestFactory.CreateHttpRequest();

            var driveItemId = SettingsHelper.DriveItemId;

            // Act
            var httpActionResult = await _sut.Download(req, null, driveItemId, _logger);

            // Assert
            Assert.IsInstanceOf(typeof(BadRequestObjectResult), httpActionResult);
        }
        public async void Http_trigger_should_return_same_entity()
        {
            // Arrange
            var request = TestFactory.CreateHttpRequest();
            var entity  = new SomeEntity {
                Name = "TestName", Description = "Some useful info", RowKey = "dummyRowKey"
            };
            // Act
            var response = (OkObjectResult)await EntitiesFunction.Run(request, entity, Guid.Empty.ToString(), logger);

            // Assert
            Assert.Equal(entity, response.Value);
        }