import os import sys import unittest # Add root to path sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from detection.ai_detector import VulnerabilityDetector class TestJavaDetection(unittest.TestCase): @classmethod def setUpClass(cls): cls.detector = VulnerabilityDetector() def test_java_sqli_detection(self): # The user-provided Java SQLi snippet code = """ // Get username from parameters String username = request.getParameter("username"); // Create a statement from database connection Statement statement = connection.createStatement(); // Create unsafe query by concatenating user defined data with query string String query = "SELECT secret FROM Users WHERE (username = '" + username + "' AND NOT role = 'admin')"; // Execute query and return the results ResultSet result = statement.executeQuery(query); """ cwe, name, confidence, line, desc = self.detector.predict(code) print(f"DEBUG: Detected {cwe} - {name} (Conf: {confidence}) at line {line}") print(f"DEBUG: Description: {desc}") self.assertEqual(cwe, "CWE-89") # Regex data-flow should catch this with high confidence (1.0) self.assertEqual(confidence, 1.0) # Line where it's used in executeQuery self.assertEqual(line, 9) def test_java_cmd_injection(self): code = """ String script = request.getParameter("script"); Runtime.getRuntime().exec("sh " + script); """ cwe, name, confidence, line, desc = self.detector.predict(code) self.assertEqual(cwe, "CWE-78") self.assertEqual(confidence, 1.0) def test_safe_java_jdbc(self): code = """ String username = request.getParameter("username"); PreparedStatement pstmt = connection.prepareStatement("SELECT * FROM users WHERE username = ?"); pstmt.setString(1, username); ResultSet rs = pstmt.executeQuery(); """ cwe, name, confidence, line, desc = self.detector.predict(code) # Should NOT be caught by simple regex data-flow as pstmt.executeQuery() doesn't contain the tainted var name directly self.assertNotEqual(confidence, 1.0) if __name__ == '__main__': test = TestJavaDetection() test.setUpClass() print("--- Running Java SQLi Test ---") test.test_java_sqli_detection() print("--- Running Java Cmd Inj Test ---") test.test_java_cmd_injection() print("--- Running Safe Java JDBC Test ---") test.test_safe_java_jdbc() print("--- All tests finished ---")