# python/02-test-categories.py"""Test categories and markers for organized testing"""importpytestfromtypingimportList,Dict,Anyfromunittest.mockimportMock,patchclassTestCategories:"""Organize tests by categories and complexity"""@pytest.mark.unitdeftest_basic_functionality(self):"""Test basic functionality - unit test"""# Test basic functionalityassertTrue@pytest.mark.integrationdeftest_database_integration(self,mock_database):"""Test database integration - integration test"""# Test database operationsassertmock_databaseisnotNone@pytest.mark.apideftest_api_endpoint(self,mock_api_client):"""Test API endpoint - API test"""# Test API functionalityresponse=mock_api_client.get("/test")assertresponse["status"]=="success"@pytest.mark.slowdeftest_performance_intensive(self):"""Test performance intensive operation - slow test"""# Test that takes timeimporttimetime.sleep(0.1)# Simulate slow operationassertTrue@pytest.mark.networkdeftest_external_api_call(self):"""Test external API call - network test"""# Test that requires network accesswithpatch('requests.get')asmock_get:mock_get.return_value.json.return_value={"status":"success"}# Test external API callassertTrueclassTestDataDriven:"""Data-driven testing patterns"""@pytest.mark.parametrize("input_value,expected",[(1,2),(2,4),(3,6),(0,0),(-1,-2)])deftest_double_function(self,input_value,expected):"""Test doubling function with multiple inputs"""defdouble(x):returnx*2result=double(input_value)assertresult==expected@pytest.mark.parametrize("test_case",[{"input":"hello","expected":"HELLO"},{"input":"world","expected":"WORLD"},{"input":"test","expected":"TEST"}])deftest_uppercase_function(self,test_case):"""Test uppercase function with test cases"""defuppercase(text):returntext.upper()result=uppercase(test_case["input"])assertresult==test_case["expected"]classTestFixtures:"""Advanced fixture patterns"""@pytest.fixture(scope="class")defclass_fixture(self):"""Class-scoped fixture"""return{"data":"class_data"}@pytest.fixture(scope="module")defmodule_fixture(self):"""Module-scoped fixture"""return{"data":"module_data"}@pytest.fixture(autouse=True)defauto_fixture(self):"""Auto-use fixture"""print("Auto fixture setup")yieldprint("Auto fixture teardown")@pytest.fixture(params=["option1","option2","option3"])defparametrized_fixture(self,request):"""Parametrized fixture"""return{"option":request.param}deftest_with_fixtures(self,class_fixture,module_fixture,parametrized_fixture):"""Test using multiple fixtures"""assertclass_fixture["data"]=="class_data"assertmodule_fixture["data"]=="module_data"assertparametrized_fixture["option"]in["option1","option2","option3"]
# python/04-performance-testing.py"""Performance testing patterns and benchmarks"""importpytestimporttimeimportcProfileimportpstatsfromtypingimportList,Dict,Anyfromunittest.mockimportMockclassPerformanceTesting:"""Performance testing patterns"""deftest_execution_time(self):"""Test execution time of a function"""defslow_function():time.sleep(0.1)# Simulate slow operationreturn"result"start_time=time.time()result=slow_function()end_time=time.time()execution_time=end_time-start_timeassertresult=="result"assertexecution_time<0.2# Should complete within 200msdeftest_memory_usage(self):"""Test memory usage of a function"""importsysdefmemory_intensive_function():data=[iforiinrange(10000)]returnlen(data)initial_memory=sys.getsizeof([])result=memory_intensive_function()final_memory=sys.getsizeof([])assertresult==10000# Memory usage should be reasonableassertfinal_memory-initial_memory<1000000# 1MBdeftest_algorithm_complexity(self):"""Test algorithm time complexity"""deflinear_search(items:List[int],target:int)->int:fori,iteminenumerate(items):ifitem==target:returnireturn-1# Test with different input sizestest_cases=[(list(range(100)),50),(list(range(1000)),500),(list(range(10000)),5000)]foritems,targetintest_cases:start_time=time.time()result=linear_search(items,target)end_time=time.time()execution_time=end_time-start_timeassertresult==targetassertexecution_time<0.1# Should be fast@pytest.mark.benchmarkdeftest_benchmark_function(self,benchmark):"""Benchmark a function using pytest-benchmark"""defbenchmark_function():returnsum(range(1000))result=benchmark(benchmark_function)assertresult==499500deftest_profiling(self):"""Test function profiling"""defprofiled_function():total=0foriinrange(1000):total+=i*ireturntotal# Profile the functionprofiler=cProfile.Profile()profiler.enable()result=profiled_function()profiler.disable()# Get profiling statsstats=pstats.Stats(profiler)stats.sort_stats('cumulative')assertresult==332833500# Verify function was profiledassertstats.total_calls>0classLoadTesting:"""Load testing patterns"""deftest_concurrent_requests(self):"""Test concurrent request handling"""importthreadingimportqueuedefworker(q,results):"""Worker function for concurrent testing"""whileTrue:try:item=q.get(timeout=1)# Simulate worktime.sleep(0.01)results.append(f"processed_{item}")q.task_done()exceptqueue.Empty:break# Create queue and resultswork_queue=queue.Queue()results=[]# Add work itemsforiinrange(10):work_queue.put(i)# Start worker threadsthreads=[]for_inrange(3):thread=threading.Thread(target=worker,args=(work_queue,results))thread.start()threads.append(thread)# Wait for completionwork_queue.join()# Stop threadsforthreadinthreads:thread.join()assertlen(results)==10assertall(result.startswith("processed_")forresultinresults)deftest_memory_leak_detection(self):"""Test for memory leaks"""importgcdefcreate_objects():"""Create objects that might leak memory"""objects=[]foriinrange(1000):obj={"id":i,"data":"x"*100}objects.append(obj)returnobjects# Get initial memorygc.collect()initial_objects=len(gc.get_objects())# Create and destroy objectsfor_inrange(10):objects=create_objects()delobjectsgc.collect()# Check final memoryfinal_objects=len(gc.get_objects())# Memory should not grow significantlyassertfinal_objects-initial_objects<1000
# 1. Setup pytest frameworkfrompathlibimportPathproject_path=Path("my-project")frompython.testing_setupimportsetup_pytest_frameworksetup_pytest_framework(project_path)# 2. Run testsimportsubprocesssubprocess.run(["pytest","tests/"],cwd=project_path)# 3. Run with coveragesubprocess.run(["pytest","--cov=src","tests/"],cwd=project_path)# 4. Run specific test categoriessubprocess.run(["pytest","-m","unit","tests/"],cwd=project_path)subprocess.run(["pytest","-m","integration","tests/"],cwd=project_path)