import unittest
class RiskAnalysis:
def __init__(self, features):
self.features = features # List of dicts with 'name', 'impact', 'likelihood'
def calculate_risk_scores(self):
for feature in self.features:
feature['risk_score'] = feature['impact'] * feature['likelihood']
return self.features
def get_top_risk_features(self, top_n=3):
scored = self.calculate_risk_scores()
sorted_features = sorted(scored, key=lambda f: f['risk_score'], reverse=True)
return sorted_features[:top_n]
class TestRiskAnalysis(unittest.TestCase):
def setUp(self):
self.features = [
{'name': 'Login', 'impact': 5, 'likelihood': 4},
{'name': 'Payment', 'impact': 9, 'likelihood': 3},
{'name': 'Search', 'impact': 4, 'likelihood': 2},
{'name': 'Profile Update', 'impact': 3, 'likelihood': 5},
{'name': 'Notifications', 'impact': 2, 'likelihood': 1}
]
self.risk_analysis = RiskAnalysis(self.features)
def test_calculate_risk_scores(self):
scored = self.risk_analysis.calculate_risk_scores()
expected_scores = {
'Login': 20,
'Payment': 27,
'Search': 8,
'Profile Update': 15,
'Notifications': 2
}
for feature in scored:
self.assertEqual(feature['risk_score'], expected_scores[feature['name']])
def test_get_top_risk_features(self):
top_features = self.risk_analysis.get_top_risk_features()
top_names = [f['name'] for f in top_features]
expected_top = ['Payment', 'Login', 'Profile Update']
self.assertEqual(top_names, expected_top)
if __name__ == '__main__':
unittest.main()This code defines a RiskAnalysis class that calculates risk scores by multiplying impact and likelihood for each feature. It then sorts features by risk score descending and selects the top 3.
The TestRiskAnalysis class uses Python's unittest framework. The setUp method prepares test data with features and their risk factors.
The first test test_calculate_risk_scores checks if risk scores are calculated correctly for each feature.
The second test test_get_top_risk_features verifies that the top 3 features selected are the ones with the highest risk scores.
This separation keeps calculation logic and assertions clear. The tests are independent and repeatable.