Files
MyClub/scripts/form_tester.py
T
Tomas Dvorak dfc079288f hot fix #1
2026-01-26 08:13:18 +01:00

182 lines
7.3 KiB
Python

#!/usr/bin/env python3
"""
Form Testing Script for PHP Application
Tests form submission with valid data every 20 seconds
"""
import requests
import time
import random
from datetime import datetime, timedelta
class FormTester:
def __init__(self, base_url="http://192.168.2.38"):
self.base_url = base_url
self.session = requests.Session()
self.session.headers.update({
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
})
def generate_test_data(self):
"""Generate realistic test data for the form"""
# Extended list of company names with various Czech company types
company_prefixes = [
"Česká", "Slovenská", "Evropská", "Mezinárodní", "Regionální", "Místní",
"Nová", "Moderní", "Tradiční", "První", "Jednotná", "Spojená"
]
company_main = [
"Technologická", "Průmyslová", "Obchodní", "Stavební", "Dopravní",
"Energetická", "Zemědělská", "Potravinářská", "Textilní", "Kovovýroba",
"Softwarová", "Marketingová", "Finanční", "Logistická", "Vzdělávací"
]
company_suffixes = [
"s.r.o.", "a.s.", "o.s.", "v.o.s.", "k.s.", "Ltd.", "Inc.", "GmbH",
"Společnost", "Firma", "Podnik", "Závod", "Družstvo", "Holding"
]
# Extended list of Czech cities and towns
cities = [
"Praha", "Brno", "Ostrava", "Plzeň", "Liberec", "Olomouc", "Budějovice",
"Hradec Králové", "Ústí nad Labem", "Pardubice", "Karlovy Vary", "Jihlava",
"Zlín", "Mladá Boleslav", "Kladno", "Most", "Opava", "Frýdek-Místek",
"Teplice", "Chomutov", "Jablonec nad Nisou", "Mělník", "Prostějov",
"Přerov", "Trutnov", "Tábor", "Kolín", "Kroměříž", "Havířov", "České Budějovice",
"Děčín", "Krnov", "Šumperk", "Orlová", "Litvínov", "Vsetín", "Valašské Meziříčí",
"Česká Lípa", "Beroun", "Žďár nad Sázavou", "Klatovy", "Rumburk", "Vrchlabí"
]
# Generate random company name with structure
prefix = random.choice(company_prefixes)
main = random.choice(company_main)
suffix = random.choice(company_suffixes)
# Sometimes add additional descriptors
if random.random() < 0.3: # 30% chance to add extra descriptor
descriptors = ["Group", "International", "Central", "Premium", "Plus", "Max"]
company_name = f"{prefix} {main} {random.choice(descriptors)} {suffix}"
else:
company_name = f"{prefix} {main} {suffix}"
# Sometimes add a number
if random.random() < 0.2: # 20% chance to add number
company_name += f" {random.randint(1, 500)}"
# Generate random city
city = random.choice(cities)
# Generate random founding date (between 1950 and 2024)
start_year = 1950
end_year = 2024
year = random.randint(start_year, end_year)
month = random.randint(1, 12)
# Generate valid day for the month
if month in [4, 6, 9, 11]:
day = random.randint(1, 30)
elif month == 2:
# Handle leap years
if (year % 400 == 0) or (year % 100 != 0 and year % 4 == 0):
day = random.randint(1, 29)
else:
day = random.randint(1, 28)
else:
day = random.randint(1, 31)
founding_date = f"{year:04d}-{month:02d}-{day:02d}"
return {
'nazev': company_name,
'mesto': city,
'datum_zalozeni': founding_date,
'odeslat': 'Uložit do databáze'
}
def submit_form(self, form_data):
"""Submit the form with provided data"""
try:
response = self.session.post(
f"{self.base_url}/zapisfirem.php",
data=form_data,
timeout=30
)
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Form submitted:")
print(f" Name: {form_data['nazev']}")
print(f" City: {form_data['mesto']}")
print(f" Date: {form_data['datum_zalozeni']}")
print(f" Status Code: {response.status_code}")
print(f" Response Length: {len(response.text)} characters")
# Check for success message
if "Firma byla úspěšně vložena do databáze" in response.text:
print(" ✅ Success: Company inserted into database")
elif "Firma byla spn vloena do databze" in response.text: # Handle encoding issues
print(" ✅ Success: Company inserted into database (encoding detected)")
else:
print(" ⚠️ Unknown response - check if submission was successful")
print("-" * 60)
return response.status_code == 200
except requests.exceptions.RequestException as e:
print(f"❌ Error submitting form: {e}")
return False
def run_test(self, interval_seconds=20, max_iterations=None):
"""Run the form testing loop"""
print(f"🧪 Starting form testing...")
print(f"📡 Target: {self.base_url}/zapisfirem.php")
print(f"⏰ Interval: {interval_seconds} seconds")
print(f"🔄 Max iterations: {'Unlimited' if max_iterations is None else max_iterations}")
print("=" * 60)
iteration = 0
try:
while True:
if max_iterations and iteration >= max_iterations:
print(f"🏁 Reached maximum iterations ({max_iterations})")
break
iteration += 1
print(f"📝 Iteration {iteration}")
# Generate and submit test data
form_data = self.generate_test_data()
success = self.submit_form(form_data)
if not success:
print("⚠️ Submission failed, but continuing...")
# Wait for the specified interval
if max_iterations is None or iteration < max_iterations:
print(f"⏳ Waiting {interval_seconds} seconds...")
time.sleep(interval_seconds)
except KeyboardInterrupt:
print(f"\n🛑 Testing stopped by user after {iteration} iterations")
except Exception as e:
print(f"❌ Unexpected error: {e}")
print("🏁 Form testing completed")
def main():
"""Main function to run the tester"""
print("PHP Form Testing Script")
print("======================")
print("This script will submit form data every 0.5 seconds to test your PHP application.")
print("Press Ctrl+C to stop the testing at any time.")
print()
# Create and run the tester
tester = FormTester()
# Run with 0.5-second interval for faster testing (you can change this)
tester.run_test(interval_seconds=0.001)
if __name__ == "__main__":
main()