Open shane0 opened 1 year ago
Feature: Scraping a website
Scenario: Scraping a website for data
Given I have a mock server running on "http://localhost:8000"
And I have the following data table:
| Column 1 | Column 2 | Column 3 |
| value 1 | value 2 | value 3 |
When I scrape the website "http://localhost:8000/data"
Then I should see the following values in the response:
| Column 1 | Column 2 | Column 3 |
| value 1 | value 2 | value 3 |
import responses
@responses.activate
def test_scraping_website(context):
# Set up the mock response
responses.add(responses.GET, 'http://localhost:8000/data',
json=[{"Column 1": "value 1", "Column 2": "value 2", "Column 3": "value 3"}])
# Run the test
context.runner.invoke(scrape_website, ['http://localhost:8000/data'])
# Assert that the response contains the expected values
assert context.response == [{"Column 1": "value 1", "Column 2": "value 2", "Column 3": "value 3"}]
stages:
- test
variables:
BEHAVE_COMMAND: "behave -f progress2 --no-capture --tags=-skip --tags=mock"
test_behave:
image: python:3.9
stage: test
before_script:
- pip install -r requirements.txt
script:
- cd tests
- $BEHAVE_COMMAND
Feature: Mock website
Scenario: Verify homepage content
Given the mock web server is running
When a user visits the homepage
Then the homepage should contain "Welcome to the mock website"
from behave import given, when, then, after
import requests
import subprocess
import re
MOCK_SERVER_PORT = 8000
@given("the mock web server is running")
def start_mock_server(context):
context.mock_server_process = subprocess.Popen(["python", "mock_server.py"])
context.mock_server_url = f"http://localhost:{MOCK_SERVER_PORT}"
@when("a user visits the homepage")
def visit_homepage(context):
context.response = requests.get(context.mock_server_url)
@then("the homepage should contain {text}")
def verify_homepage_content(context, text):
assert re.search(text, context.response.text)
@after
def stop_mock_server(context):
context.mock_server_process.terminate()
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return '<html><body><h1>Welcome to the mock website</h1></body></html>'
if __name__ == '__main__':
app.run(port=8000)
stages:
- build
- test
- deploy
build:
stage: build
script:
- echo "Building..."
test:
stage: test
script:
- echo "Running tests..."
- exit 1 # simulate test failure
allow_failure: true # allow this job to fail
deploy:
stage: deploy
script:
- echo "Deploying..."
dependencies:
- build
- test
stages:
- build
- test
- deploy
build:
script:
- echo "Building..."
stage: build
test:
script:
- echo "Testing..."
stage: test
needs: []
deploy:
script:
- echo "Deploying..."
stage: deploy
needs: []
the test and deploy stages do not depend on any previous stages, so they will run even if the build stage fails.
Scenario: Verify file content
Given the file "example.txt" exists
When I read the file "example.txt"
Then the file should contain the following data
| expected_data | regex_match |
| example data | .*example.* |
from behave import given, when, then
import os
import re
@given("the file {filename} exists")
def step_file_exists(context, filename):
assert os.path.exists(filename), f"{filename} does not exist"
@when("I read the file {filename}")
def step_read_file(context, filename):
with open(filename, 'r') as file:
context.file_content = file.read()
@then("the file should contain the following data")
def step_check_file_content(context):
expected_data = context.table
for row in expected_data:
expected_string = row['expected_data']
assert re.search(expected_string, context.file_content), \
f"{expected_string} not found in {context.file_content}"
Feature: Verify files contain text that matches a regex pattern
Scenario: Verify two files contain text that matches a regex pattern
Given two file paths: "file1.txt" and "file2.txt"
When I check if the files exist
Then I verify that the files contain the text matching the regex pattern:
"""
^This is a test file$
"""
from behave import given, when, then
import os
import re
@given('two file paths: {file1_path} and {file2_path}')
def step_impl(context, file1_path, file2_path):
context.file1_path = file1_path
context.file2_path = file2_path
@when('I check if the files exist')
def step_impl(context):
assert os.path.exists(context.file1_path), f"File {context.file1_path} does not exist"
assert os.path.exists(context.file2_path), f"File {context.file2_path} does not exist"
@then('I verify that the files contain the text matching the regex pattern:')
def step_impl(context):
pattern = re.compile(context.text)
with open(context.file1_path, 'r') as file1:
file1_contents = file1.read()
assert pattern.search(file1_contents), f"File {context.file1_path} does not contain text matching pattern"
with open(context.file2_path, 'r') as file2:
file2_contents = file2.read()
assert pattern.search(file2_contents), f"File {context.file2_path} does not contain text matching pattern"
Feature: Test API Endpoint
As a user
I want to test the API endpoint
So that I can ensure that it returns the correct data
Scenario: GET Request to API Endpoint
Given I have the endpoint URL "https://example.com/api/endpoint"
When I make a GET request to the endpoint
Then the response status code should be 200
And the response body should contain "Hello, World!"
import requests
from behave import *
@given('I have the endpoint URL "{url}"')
def step_impl(context, url):
context.url = url
@when('I make a GET request to the endpoint')
def step_impl(context):
context.response = requests.get(context.url)
@then('the response status code should be {status_code:d}')
def step_impl(context, status_code):
assert context.response.status_code == status_code
@then('the response body should contain "{text}"')
def step_impl(context, text):
assert text in context.response.text
Feature: API endpoint testing
As a user
I want to test the API endpoints
So that I can ensure that they are working correctly
Scenario: Test API endpoint
Given the host is "<host>"
When I send a GET request to the endpoint "<endpoint>"
Then the response status code should be "<status_code>"
And the response content should contain "<expected_content>"
Examples:
| host | endpoint | status_code | expected_content |
| https://example.com | /api/v1/users | 200 | "John Doe" |
| https://example.com | /api/v1/orders | 404 | "Order not found" |
| https://example.com | /api/v1/products| 401 | "Unauthorized" |
from behave import *
@given('the host is "{host}"')
def step_impl(context, host):
context.host = host
@when('I send a GET request to the endpoint "{endpoint}"')
def step_impl(context, endpoint):
context.response = requests.get(context.host + endpoint)
@then('the response status code should be "{status_code}"')
def step_impl(context, status_code):
assert context.response.status_code == int(status_code)
@then('the response content should contain "{expected_content}"')
def step_impl(context, expected_content):
assert expected_content in context.response.text
# features/ping_hosts.feature
Feature: Ping Hosts
As a user
I want to ping a list of hosts
So that I can verify that they are up and running
Scenario Outline: Ping Hosts with IP Address
Given I have a list of hosts
When I ping each host
Then the IP address of each host should match "<ip_address>"
Examples:
| host_name | ip_address |
| google.com | 172.217.14.46 |
| github.com | 140.82.121.3 |
| amazon.com | 205.251.242.103 |
# steps/ping_hosts.py
import subprocess
from behave import *
@given('I have a list of hosts')
def step_impl(context):
context.hosts = [row["host_name"] for row in context.table]
@when('I ping each host')
def step_impl(context):
context.ip_addresses = []
for host in context.hosts:
output = subprocess.check_output(['ping', '-c', '1', host])
ip_address = output.decode('utf-8').split('\n')[1].split()[3][1:-1]
context.ip_addresses.append(ip_address)
@then('the IP address of each host should match "{ip_address}"')
def step_impl(context, ip_address):
for i in range(len(context.hosts)):
assert context.ip_addresses[i] == ip_address, f"IP address for {context.hosts[i]} does not match {ip_address}"
# features/ping_host.feature
Feature: Ping hosts and match IP addresses
As a tester
I want to verify that I can ping hosts and match IP addresses
So that I can ensure the hosts are reachable and have the correct IP addresses
Scenario Outline: Ping a host and match IP address
Given I ping "<host>"
Then the IP address should match "<ip_address>"
Examples:
| host | ip_address |
| www.google.com | 172.217.6.196|
| www.github.com | 140.82.121.3 |
# steps/ping_host_steps.py
import subprocess
import re
from behave import given, then, use_step_matcher
# Define a custom step matcher to allow for variable substitution
use_step_matcher("re")
@given('I ping "(.*)"')
def step_ping_host(context, host):
# Use the subprocess module to execute the ping command and capture the output
ping_output = subprocess.check_output(["ping", "-c", "1", host])
# Save the ping output to the context so it can be used in subsequent steps
context.ping_output = ping_output.decode('utf-8')
@then('the IP address should match "(.*)"')
def step_match_ip_address(context, ip_address):
# Use a regular expression to extract the IP address from the ping output
ip_pattern = r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})"
match = re.search(ip_pattern, context.ping_output)
if match:
# If a match is found, compare it to the expected IP address
assert match.group(1) == ip_address, f"IP address {match.group(1)} does not match expected {ip_address}"
else:
# If no match is found, fail the test
assert False, "No IP address found in ping output"
# features/environment.py
def before_scenario(context, scenario):
# Add any necessary environment setup here, such as installing required packages
def after_scenario(context, scenario):
# Add any necessary environment cleanup here, such as deleting temporary files
Feature: Verify log files do not contain a regex match
Scenario Outline: Verify log files do not contain a regex match
Given I have a log file "<log_file>"
And I have a regex pattern "<regex_pattern>"
When I search for the pattern in the log file
Then the log file should not contain the pattern
Examples:
| log_file | regex_pattern |
| /var/log/messages | error |
| /var/log/syslog | warning |
from behave import given, when, then
import re
@given('I have a log file "{log_file}"')
def step_impl(context, log_file):
context.log_file = log_file
@given('I have a regex pattern "{regex_pattern}"')
def step_impl(context, regex_pattern):
context.regex_pattern = regex_pattern
@when('I search for the pattern in the log file')
def step_impl(context):
with open(context.log_file, 'r') as f:
context.log_content = f.read()
@then('the log file should not contain the pattern')
def step_impl(context):
matches = re.findall(context.regex_pattern, context.log_content)
assert not matches, f"Found {len(matches)} matches of pattern {context.regex_pattern} in {context.log_file}"
check web