File size: 17,783 Bytes
225af6a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 |
"""
System tests for end-to-end workflows.
Tests the complete system including training and inference pipelines.
"""
import pytest
import numpy as np
import pandas as pd
import tempfile
from pathlib import Path
from unittest.mock import patch, MagicMock
import joblib
from sklearn.ensemble import RandomForestClassifier
from sklearn.multioutput import MultiOutputClassifier
@pytest.mark.system
@pytest.mark.slow
class TestTrainingPipeline:
"""System tests for model training pipeline."""
def test_complete_training_workflow(self, sample_dataframe):
"""Test complete training workflow from data to model."""
from hopcroft_skill_classification_tool_competition.features import (
extract_tfidf_features,
prepare_labels,
)
from sklearn.model_selection import train_test_split
# Extract features
features, vectorizer = extract_tfidf_features(sample_dataframe, max_features=50)
labels = prepare_labels(sample_dataframe)
# Split data
X_train, X_test, y_train, y_test = train_test_split(
features, labels.values, test_size=0.2, random_state=42
)
# Train model
rf = RandomForestClassifier(n_estimators=10, random_state=42)
model = MultiOutputClassifier(rf)
model.fit(X_train, y_train)
# Predict
predictions = model.predict(X_test)
# Verify
assert predictions.shape[0] == X_test.shape[0]
assert predictions.shape[1] == y_test.shape[1]
assert np.all((predictions == 0) | (predictions == 1))
def test_training_with_oversampling(self, sample_dataframe):
"""Test training pipeline with oversampling."""
from hopcroft_skill_classification_tool_competition.features import (
extract_tfidf_features,
prepare_labels,
)
from imblearn.over_sampling import RandomOverSampler
from sklearn.model_selection import train_test_split
# Prepare data
features, _ = extract_tfidf_features(sample_dataframe, max_features=50)
labels = prepare_labels(sample_dataframe)
# Use only one label column for oversampling
y_single = labels.iloc[:, 0].values
# Split
X_train, X_test, y_train, y_test = train_test_split(
features, y_single, test_size=0.2, random_state=42
)
# Oversample
ros = RandomOverSampler(random_state=42)
X_resampled, y_resampled = ros.fit_resample(X_train, y_train)
# Train
rf = RandomForestClassifier(n_estimators=10, random_state=42)
rf.fit(X_resampled, y_resampled)
# Predict
predictions = rf.predict(X_test)
# Verify
assert len(predictions) == len(X_test)
assert np.all((predictions == 0) | (predictions == 1))
def test_model_serialization(self, sample_dataframe):
"""Test model can be saved and loaded."""
from hopcroft_skill_classification_tool_competition.features import (
extract_tfidf_features,
prepare_labels,
)
# Train simple model
features, _ = extract_tfidf_features(sample_dataframe, max_features=50)
labels = prepare_labels(sample_dataframe)
rf = RandomForestClassifier(n_estimators=5, random_state=42)
model = MultiOutputClassifier(rf)
model.fit(features, labels.values)
# Save and load
with tempfile.NamedTemporaryFile(suffix='.pkl', delete=False) as f:
model_path = f.name
try:
joblib.dump(model, model_path)
loaded_model = joblib.load(model_path)
# Verify predictions match
pred_original = model.predict(features)
pred_loaded = loaded_model.predict(features)
np.testing.assert_array_equal(pred_original, pred_loaded)
finally:
Path(model_path).unlink()
@pytest.mark.system
class TestInferencePipeline:
"""System tests for inference pipeline."""
def test_inference_on_new_text(self, sample_dataframe):
"""Test inference pipeline on new unseen text."""
from hopcroft_skill_classification_tool_competition.features import (
extract_tfidf_features,
prepare_labels,
clean_github_text,
)
# Train model
features, vectorizer = extract_tfidf_features(sample_dataframe, max_features=50)
labels = prepare_labels(sample_dataframe)
rf = RandomForestClassifier(n_estimators=5, random_state=42)
model = MultiOutputClassifier(rf)
model.fit(features, labels.values)
# New text
new_texts = [
"Fixed critical bug in authentication module",
"Added new REST API endpoint for users",
]
# Process new text
cleaned_texts = [clean_github_text(text) for text in new_texts]
new_features = vectorizer.transform(cleaned_texts).toarray()
# Predict
predictions = model.predict(new_features)
# Verify
assert predictions.shape[0] == len(new_texts)
assert predictions.shape[1] == labels.shape[1]
assert np.all((predictions == 0) | (predictions == 1))
def test_inference_with_empty_input(self, sample_dataframe):
"""Test inference handles empty input gracefully."""
from hopcroft_skill_classification_tool_competition.features import (
extract_tfidf_features,
prepare_labels,
clean_github_text,
)
# Train model
features, vectorizer = extract_tfidf_features(sample_dataframe, max_features=50)
labels = prepare_labels(sample_dataframe)
rf = RandomForestClassifier(n_estimators=5, random_state=42)
model = MultiOutputClassifier(rf)
model.fit(features, labels.values)
# Empty text
empty_text = ""
cleaned = clean_github_text(empty_text)
new_features = vectorizer.transform([cleaned]).toarray()
# Should not crash
predictions = model.predict(new_features)
assert predictions.shape[0] == 1
assert predictions.shape[1] == labels.shape[1]
def test_batch_inference(self, sample_dataframe):
"""Test inference on batch of samples."""
from hopcroft_skill_classification_tool_competition.features import (
extract_tfidf_features,
prepare_labels,
)
# Train model
features, vectorizer = extract_tfidf_features(sample_dataframe, max_features=50)
labels = prepare_labels(sample_dataframe)
rf = RandomForestClassifier(n_estimators=5, random_state=42)
model = MultiOutputClassifier(rf)
model.fit(features, labels.values)
# Batch prediction
predictions = model.predict(features)
assert predictions.shape == labels.shape
assert np.all((predictions == 0) | (predictions == 1))
@pytest.mark.system
@pytest.mark.requires_data
class TestEndToEndDataFlow:
"""System tests for complete data flow from raw to predictions."""
def test_full_pipeline_database_to_predictions(self, temp_db):
"""Test complete pipeline from database to predictions."""
from hopcroft_skill_classification_tool_competition.features import (
load_data_from_db,
extract_tfidf_features,
prepare_labels,
)
from sklearn.model_selection import train_test_split
# Load data
df = load_data_from_db(temp_db)
# Extract features
features, vectorizer = extract_tfidf_features(df, max_features=50)
labels = prepare_labels(df)
# Split
X_train, X_test, y_train, y_test = train_test_split(
features, labels.values, test_size=0.4, random_state=42
)
# Train
rf = RandomForestClassifier(n_estimators=5, random_state=42)
model = MultiOutputClassifier(rf)
model.fit(X_train, y_train)
# Predict
predictions = model.predict(X_test)
# Evaluate (simple check)
from sklearn.metrics import accuracy_score
# Per-label accuracy
accuracies = []
for i in range(y_test.shape[1]):
acc = accuracy_score(y_test[:, i], predictions[:, i])
accuracies.append(acc)
# Should have some predictive power (better than random for at least one label)
assert np.mean(accuracies) > 0.4 # Very lenient threshold for small test data
@pytest.mark.system
class TestModelValidation:
"""System tests for model validation workflows."""
def test_cross_validation_workflow(self, sample_dataframe):
"""Test cross-validation workflow."""
from hopcroft_skill_classification_tool_competition.features import (
extract_tfidf_features,
prepare_labels,
)
from sklearn.model_selection import cross_val_score
# Prepare data
features, _ = extract_tfidf_features(sample_dataframe, max_features=50)
labels = prepare_labels(sample_dataframe)
# Use single label for CV
y_single = labels.iloc[:, 0].values
# Cross-validation
rf = RandomForestClassifier(n_estimators=5, random_state=42)
# Should not crash (though scores may be poor with small data)
scores = cross_val_score(rf, features, y_single, cv=2, scoring='accuracy')
assert len(scores) == 2
assert all(0 <= score <= 1 for score in scores)
def test_grid_search_workflow(self, sample_dataframe):
"""Test grid search workflow."""
from hopcroft_skill_classification_tool_competition.features import (
extract_tfidf_features,
prepare_labels,
)
from sklearn.model_selection import GridSearchCV
# Prepare data
features, _ = extract_tfidf_features(sample_dataframe, max_features=50)
labels = prepare_labels(sample_dataframe)
# Use single label
y_single = labels.iloc[:, 0].values
# Small grid search
param_grid = {
'n_estimators': [5, 10],
'max_depth': [5, 10],
}
rf = RandomForestClassifier(random_state=42)
grid_search = GridSearchCV(rf, param_grid, cv=2, scoring='accuracy')
grid_search.fit(features, y_single)
# Verify
assert hasattr(grid_search, 'best_params_')
assert hasattr(grid_search, 'best_score_')
assert grid_search.best_score_ >= 0
@pytest.mark.system
@pytest.mark.regression
class TestRegressionScenarios:
"""Regression tests for known issues and edge cases."""
def test_empty_feature_vectors_handling(self):
"""
Regression test: Ensure empty feature vectors don't crash training.
This was identified in Great Expectations TEST 2 - 25 samples with
zero features after TF-IDF extraction.
"""
from sklearn.ensemble import RandomForestClassifier
from sklearn.multioutput import MultiOutputClassifier
# Create data with some zero vectors
X = np.array([
[0.1, 0.2, 0.3],
[0.0, 0.0, 0.0], # Empty vector
[0.4, 0.5, 0.6],
[0.0, 0.0, 0.0], # Another empty vector
])
y = np.array([
[1, 0],
[0, 1],
[1, 1],
[0, 0],
])
# Should not crash
rf = RandomForestClassifier(n_estimators=5, random_state=42)
model = MultiOutputClassifier(rf)
model.fit(X, y)
predictions = model.predict(X)
assert predictions.shape == y.shape
def test_zero_occurrence_labels_handling(self):
"""
Regression test: Handle labels with zero occurrences.
This was identified in Great Expectations TEST 5 - 75 labels with
zero occurrences in the dataset.
"""
from hopcroft_skill_classification_tool_competition.features import get_label_columns
# Create dataframe with some zero-occurrence labels
df = pd.DataFrame({
'issue text': ['text1', 'text2', 'text3'],
'Label1': [1, 1, 0], # Has occurrences
'Label2': [0, 0, 0], # Zero occurrences
'Label3': [1, 0, 1], # Has occurrences
})
label_cols = get_label_columns(df)
# Should include all labels
assert 'Label1' in label_cols
assert 'Label2' in label_cols
assert 'Label3' in label_cols
# Training code should filter these out before stratification
# This test just verifies detection works
def test_high_sparsity_features(self):
"""
Regression test: Handle very sparse features (>99% zeros).
This was identified in Great Expectations TEST 6 - 99.88% sparsity.
"""
from sklearn.ensemble import RandomForestClassifier
# Create highly sparse feature matrix
X = np.zeros((100, 1000))
# Only 0.12% non-zero values (very sparse)
for i in range(100):
indices = np.random.choice(1000, size=1, replace=False)
X[i, indices] = np.random.rand(1)
y = np.random.randint(0, 2, size=100)
# Should handle high sparsity without crashing
rf = RandomForestClassifier(n_estimators=5, random_state=42)
rf.fit(X, y)
predictions = rf.predict(X)
assert len(predictions) == len(y)
def test_duplicate_samples_detection(self):
"""
Regression test: Detect duplicate samples.
This was identified in Deepchecks validation - 481 duplicates (6.72%).
"""
df = pd.DataFrame({
'issue text': ['duplicate', 'duplicate', 'unique'],
'issue description': ['desc', 'desc', 'different'],
'Label1': [1, 1, 0],
})
# Check for duplicates
duplicates = df[['issue text', 'issue description']].duplicated()
assert duplicates.sum() == 1 # One duplicate found
# Removal should be done in data cleaning pipeline
df_cleaned = df.drop_duplicates(subset=['issue text', 'issue description'])
assert len(df_cleaned) == 2
@pytest.mark.system
@pytest.mark.acceptance
class TestAcceptanceCriteria:
"""Acceptance tests verifying requirements are met."""
def test_multi_label_classification_support(self, sample_dataframe):
"""
Acceptance test: System supports multi-label classification.
Requirement: Each issue can have multiple skill labels.
"""
from hopcroft_skill_classification_tool_competition.features import (
extract_tfidf_features,
prepare_labels,
)
features, _ = extract_tfidf_features(sample_dataframe, max_features=50)
labels = prepare_labels(sample_dataframe)
# Train multi-output model
rf = RandomForestClassifier(n_estimators=5, random_state=42)
model = MultiOutputClassifier(rf)
model.fit(features, labels.values)
# Predict multiple labels
predictions = model.predict(features)
# Verify multiple labels can be predicted
labels_per_sample = predictions.sum(axis=1)
assert np.any(labels_per_sample > 1), "System should support multiple labels per sample"
def test_handles_github_text_format(self):
"""
Acceptance test: System handles GitHub issue text format.
Requirement: Process text from GitHub issues with URLs, code, etc.
"""
from hopcroft_skill_classification_tool_competition.features import clean_github_text
github_text = """
Fixed bug in authentication #123
See: https://github.com/repo/issues/123
```python
def login(user):
return authenticate(user)
```
Related to <b>security</b> improvements 🔒
"""
cleaned = clean_github_text(github_text)
# Should remove noise but keep meaningful content
assert "https://" not in cleaned
assert "```" not in cleaned
assert "<b>" not in cleaned
assert len(cleaned) > 0
def test_produces_binary_predictions(self, sample_dataframe):
"""
Acceptance test: System produces binary predictions (0 or 1).
Requirement: Clear yes/no predictions for each skill.
"""
from hopcroft_skill_classification_tool_competition.features import (
extract_tfidf_features,
prepare_labels,
)
features, _ = extract_tfidf_features(sample_dataframe, max_features=50)
labels = prepare_labels(sample_dataframe)
rf = RandomForestClassifier(n_estimators=5, random_state=42)
model = MultiOutputClassifier(rf)
model.fit(features, labels.values)
predictions = model.predict(features)
# All predictions should be 0 or 1
assert np.all((predictions == 0) | (predictions == 1))
|