예제 #1
0
 public ConfigurationController(IConfiguration configuration, ISharedVariablesProvider sharedVariablesProvider, IReservedVariableProvider reservedVariableProvider, SnippetFileReader snippetFileReader)
 {
     _configuration            = configuration;
     _sharedVariablesProvider  = sharedVariablesProvider;
     _reservedVariableProvider = reservedVariableProvider;
     _snippetFileReader        = snippetFileReader;
 }
예제 #2
0
        public void should_return_empty_list_when_snippet_directory_does_not_exist()
        {
            // given
            var config = new JsonConfiguration();

            config.ScriptSnippetDirectory = "doesnt-exist";
            var snippetReader = new SnippetFileReader(config);

            // when
            IEnumerable <string> files = snippetReader.GetSnippetFilenames(ScriptSnippetType.BeforeExecute);

            // then
            Assert.That(files.Count(), Is.EqualTo(0));
        }
예제 #3
0
        public void should_read_text_file()
        {
            // given
            string typeDirectory = Path.Combine(_snippetDirectory, ScriptSnippetType.BeforeExecute.ToString().ToLower());

            string filename1 = Path.Combine(typeDirectory, "snippet1.snippet");

            File.WriteAllText(filename1, "snippet 1");

            var config = new JsonConfiguration();

            config.ScriptSnippetDirectory = _snippetDirectory;

            var snippetReader = new SnippetFileReader(config);

            // when
            string snippetText = snippetReader.ReadFile(filename1);

            // then
            Assert.That(snippetText, Is.EqualTo("snippet 1"));
        }
예제 #4
0
        public void should_get_snippet_filenames_from_directory()
        {
            // given
            string typeDirectory = Path.Combine(_snippetDirectory, ScriptSnippetType.BeforeExecute.ToString().ToLower());

            string filename1 = Path.Combine(typeDirectory, "snippet1.snippet");
            string filename2 = Path.Combine(typeDirectory, "snippet2.snippet");

            File.WriteAllText(filename1, "snippet 1");
            File.WriteAllText(filename2, "snippet 2");

            var config = new JsonConfiguration();

            config.ScriptSnippetDirectory = _snippetDirectory;
            var snippetReader = new SnippetFileReader(config);

            // when
            IEnumerable <string> files = snippetReader.GetSnippetFilenames(ScriptSnippetType.BeforeExecute);

            // then
            Assert.That(files.Count(), Is.EqualTo(2));
            Assert.That(files, Contains.Item("snippet1.snippet"));
            Assert.That(files, Contains.Item("snippet2.snippet"));
        }
예제 #5
0
        public void should_return_empty_list_when_snippet_sub_directory_does_not_exist()
        {
            // given
            string typeDirectory = Path.Combine(_snippetDirectory, ScriptSnippetType.BeforeExecute.ToString().ToLower());

            try
            {
                Directory.Delete(typeDirectory);
            }
            catch (IOException)
            {
            }

            var config = new JsonConfiguration();

            config.ScriptSnippetDirectory = _snippetDirectory;
            var snippetReader = new SnippetFileReader(config);

            // when
            IEnumerable <string> files = snippetReader.GetSnippetFilenames(ScriptSnippetType.BeforeExecute);

            // then
            Assert.That(files.Count(), Is.EqualTo(0));
        }
예제 #6
0
        internal async Task <TestResult> RunTestAsync(Test test, int position, ICapturedVariableProvider variables, AssertionsMatcher assertionMatcher)
        {
            var testResult = new TestResult
            {
                Position  = position,
                SessionId = SessionId,
                Test      = test
            };

            try
            {
                string resolvedUrl = variables.ReplacePlainTextVariablesIn(test.Url);
                testResult.ActualUrl = resolvedUrl;

                string postBody = variables.ReplacePlainTextVariablesIn(test.PostBody);
                foreach (HeaderItem header in test.Headers)
                {
                    header.Value = variables.ReplacePlainTextVariablesIn(header.Value);
                }

                IRestRequest request = _httpClient.CreateRestRequest(test.Method, resolvedUrl, postBody, test.Headers);
                var          logger  = _loggerFactory.CreateLogger();

                // Scripting part
                if (test.ScriptSnippets != null && !string.IsNullOrEmpty(test.ScriptSnippets.BeforeExecuteFilename))
                {
                    logger.WriteLine("Evaluating C# script");

                    try
                    {
                        var  snippetReader = new SnippetFileReader(_configuration);
                        var  evaluator     = new TestFileScriptEvaluator(_configuration, snippetReader);
                        bool success       = evaluator.EvaluateBeforeExecute(test, request);

                        if (success)
                        {
                            request = evaluator.RequestGlobals.Request;
                            test    = evaluator.RequestGlobals.Test;
                            logger.WriteLine("Compilation successful.");
                        }
                    }
                    catch (Exception ex)
                    {
                        testResult.ScriptCompilationSuccess = false;
                        testResult.ExceptionMessage         = "The script failed to compile - see the log file for a stack trace.";
                        logger.WriteLine("Compilation failed: {0}", ex);
                    }
                }

                var          httpLogWriter = new HttpLogWriter();
                HttpResponse response      = await _httpClient.ExecuteRequestAsync(request, httpLogWriter);

                testResult.ResponseTime = response.ResponseTime;
                testResult.HttpResponse = response;
                testResult.HttpLog      = httpLogWriter.StringBuilder.ToString();
                testResult.HttpContent  = response.Content;

                if (response.StatusCode == test.ExpectedHttpStatusCode)
                {
                    testResult.ResponseCodeSuccess = true;
                    string content = response.ToString();

                    // Put the captured variables regex values in the current variable set
                    foreach (var capturedVariable in test.CapturedVariables)
                    {
                        capturedVariable.Regex = variables.ReplacePlainTextVariablesIn(capturedVariable.Regex);
                    }

                    List <Variable> parsedVariables = CapturedVariableProvider.MatchVariables(test.CapturedVariables, content, logger);
                    variables.AddOrUpdateVariables(parsedVariables);
                    logger.WriteLine("{0} captured variable(s) parsed.", parsedVariables.Count);

                    // Verify assertions
                    testResult.AssertionResults = assertionMatcher.MatchVerifications(test.Assertions, content);
                    logger.WriteLine("Verifying {0} assertion(s)", testResult.AssertionResults.Count);
                    foreach (Assertion item in testResult.AssertionResults)
                    {
                        logger.AppendTextLine(item.Log);
                    }

                    // Store the log
                    testResult.Log = logger.GetLog();
                }
                else
                {
                    testResult.ResponseCodeSuccess = false;
                    testResult.Log = $"No verifications run - the response code {response.StatusCode} did not match the expected response code {test.ExpectedHttpStatusCode}.";
                }
            }
            catch (Exception ex)
            {
                testResult.Log = "An exception occured: " + ex;
                testResult.ResponseCodeSuccess = false;
                testResult.ExceptionMessage    = ex.Message;
            }

            return(testResult);
        }
예제 #7
0
        internal async Task <TestResult> RunTestAsync(Test test, int position, ICapturedVariableProvider variables, AssertionsMatcher assertionMatcher, string environment)
        {
            var testResult = new TestResult
            {
                Position    = position,
                SessionId   = SessionId,
                Test        = test,
                ResultState = TestResultState.Failed
            };

            if (test.TestConditions.RequiredEnvironments.Any())
            {
                bool inEnvironment = test.TestConditions.RequiredEnvironments
                                     .Where(x => !string.IsNullOrEmpty(x))
                                     .Any(x => x.Equals(environment, StringComparison.InvariantCultureIgnoreCase));
                if (!inEnvironment)
                {
                    testResult.ResultState = TestResultState.Skipped;
                    return(testResult);
                }
            }

            try
            {
                string resolvedUrl = variables.ReplacePlainTextVariablesIn(test.Url);
                testResult.ActualUrl = resolvedUrl;

                string postBody = variables.ReplacePlainTextVariablesIn(test.PostBody);
                foreach (HeaderItem header in test.Headers)
                {
                    header.Value = variables.ReplacePlainTextVariablesIn(header.Value);
                }

                var          logger  = _loggerFactory.CreateLogger();
                IRestRequest request = _httpClient.CreateRestRequest(test.Method, resolvedUrl, postBody, test.Headers);

                // Scripting part
                if (!string.IsNullOrEmpty(test.ScriptSnippets?.BeforeExecuteFilename))
                {
                    logger.WriteLine("Evaluating C# script");

                    try
                    {
                        var  snippetReader = new SnippetFileReader(_configuration);
                        var  evaluator     = new TestFileScriptEvaluator(_configuration, snippetReader);
                        bool success       = evaluator.EvaluateBeforeExecute(test, request);

                        if (success)
                        {
                            request = evaluator.RequestGlobals.Request;
                            test    = evaluator.RequestGlobals.Test;
                            logger.WriteLine("Compilation successful.");
                        }
                    }
                    catch (Exception ex)
                    {
                        testResult.ScriptCompilationSuccess = false;
                        testResult.ExceptionMessage         = "The script failed to compile - see the log file for a stack trace.";
                        logger.WriteLine("Compilation failed: {0}", ex);
                    }
                }

                var          httpLogWriter = new HttpLogWriter();
                HttpResponse response      = await _httpClient.ExecuteRequestAsync(request, httpLogWriter);

                ProcessResponse(test, variables, assertionMatcher, testResult, response, httpLogWriter, logger);
            }
            catch (Exception ex)
            {
                testResult.Log = "An exception occured: " + ex;
                testResult.ResponseCodeSuccess = false;
                testResult.ExceptionMessage    = ex.Message;
            }

            if (testResult.ResponseCodeSuccess && testResult.AssertionsSuccess && testResult.ScriptCompilationSuccess)
            {
                testResult.ResultState = TestResultState.Success;
            }

            return(testResult);
        }