Modified CveDB and Settings so that they are no longer singletons; first step in thread safety updates

This commit is contained in:
Jeremy Long
2017-08-30 06:47:45 -04:00
parent c4b67a1db2
commit 74a2326e0e
113 changed files with 1809 additions and 1400 deletions

View File

@@ -44,7 +44,7 @@ public class AnalysisTaskTest extends BaseTest {
result = true;
}};
AnalysisTask analysisTask = new AnalysisTask(fileTypeAnalyzer, dependency, null, null, Settings.getInstance());
AnalysisTask analysisTask = new AnalysisTask(fileTypeAnalyzer, dependency, null, null, getSettings());
boolean shouldAnalyze = analysisTask.shouldAnalyze();
assertTrue(shouldAnalyze);
@@ -61,7 +61,7 @@ public class AnalysisTaskTest extends BaseTest {
result = false;
}};
AnalysisTask analysisTask = new AnalysisTask(fileTypeAnalyzer, dependency, null, null, Settings.getInstance());
AnalysisTask analysisTask = new AnalysisTask(fileTypeAnalyzer, dependency, null, null, getSettings());
boolean shouldAnalyze = analysisTask.shouldAnalyze();
assertFalse(shouldAnalyze);
@@ -69,7 +69,7 @@ public class AnalysisTaskTest extends BaseTest {
@Test
public void taskAnalyzes() throws Exception {
final AnalysisTask analysisTask = new AnalysisTask(fileTypeAnalyzer, dependency, engine, null, Settings.getInstance());
final AnalysisTask analysisTask = new AnalysisTask(fileTypeAnalyzer, dependency, engine, null, getSettings());
new Expectations(analysisTask) {{
analysisTask.shouldAnalyze();
result = true;
@@ -85,7 +85,7 @@ public class AnalysisTaskTest extends BaseTest {
@Test
public void taskDoesNothingIfItShouldNotAnalyze() throws Exception {
final AnalysisTask analysisTask = new AnalysisTask(fileTypeAnalyzer, dependency, engine, null, Settings.getInstance());
final AnalysisTask analysisTask = new AnalysisTask(fileTypeAnalyzer, dependency, engine, null, getSettings());
new Expectations(analysisTask) {{
analysisTask.shouldAnalyze();
result = false;

View File

@@ -43,17 +43,19 @@ public abstract class BaseDBTestCase extends BaseTest {
private final static Logger LOGGER = LoggerFactory.getLogger(BaseDBTestCase.class);
@Before
public void setUpDb() throws Exception {
@Override
public void setUp() throws Exception {
super.setUp();
ensureDBExists();
}
public static void ensureDBExists() throws Exception {
public void ensureDBExists() throws Exception {
File f = new File("./target/data/dc.h2.db");
if (f.exists() && f.isFile() && f.length() < 71680) {
f.delete();
}
File dataPath = Settings.getDataDirectory();
String fileName = Settings.getString(Settings.KEYS.DB_FILE_NAME);
File dataPath = getSettings().getDataDirectory();
String fileName = getSettings().getString(Settings.KEYS.DB_FILE_NAME);
LOGGER.trace("DB file name {}", fileName);
File dataFile = new File(dataPath, fileName);
LOGGER.trace("Ensuring {} exists", dataFile.toString());

View File

@@ -18,9 +18,11 @@ package org.owasp.dependencycheck;
import java.io.File;
import java.io.InputStream;
import java.net.URISyntaxException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assume;
import org.junit.Before;
import org.junit.BeforeClass;
import org.owasp.dependencycheck.utils.Settings;
@@ -30,9 +32,25 @@ import org.owasp.dependencycheck.utils.Settings;
*/
public class BaseTest {
@BeforeClass
public static void setUpClass() throws Exception {
Settings.initialize();
/**
* The configured settings.
*/
private Settings settings;
/**
* Initialize the {@link Settings}.
*/
@Before
public void setUp() throws Exception {
settings = new Settings();
}
/**
* Clean the {@link Settings}.
*/
@After
public void tearDown() throws Exception {
settings.cleanup(true);
}
@AfterClass
@@ -45,13 +63,12 @@ public class BaseTest {
System.err.println("------------------------------------------------");
System.err.println("------------------------------------------------");
}
Settings.cleanup(true);
}
/**
* Returns the given resource as an InputStream using the object's class loader. The org.junit.Assume API is used so that test
* cases are skipped if the resource is not available.
* Returns the given resource as an InputStream using the object's class
* loader. The org.junit.Assume API is used so that test cases are skipped
* if the resource is not available.
*
* @param o the object used to obtain a reference to the class loader
* @param resource the name of the resource to load
@@ -63,20 +80,30 @@ public class BaseTest {
}
/**
* Returns the given resource as a File using the object's class loader. The org.junit.Assume API is used so that test cases
* are skipped if the resource is not available.
* Returns the given resource as a File using the object's class loader. The
* org.junit.Assume API is used so that test cases are skipped if the
* resource is not available.
*
* @param o the object used to obtain a reference to the class loader
* @param resource the name of the resource to load
* @return the resource as an File
*/
public static File getResourceAsFile(Object o, String resource) {
try{
try {
File f = new File(o.getClass().getClassLoader().getResource(resource).toURI().getPath());
Assume.assumeTrue(String.format("%n%n[SEVERE] Unable to load resource for test case: %s%n%n", resource), f.exists());
return f;
}catch (URISyntaxException e){
} catch (URISyntaxException e) {
throw new UnsupportedOperationException(e);
}
}
/**
* Returns the settings for the test cases.
*
* @return
*/
protected Settings getSettings() {
return settings;
}
}

View File

@@ -48,10 +48,10 @@ public class EngineIT extends BaseDBTestCase {
@Test
public void testEngine() throws IOException, InvalidSettingException, DatabaseException, ReportException, ExceptionCollection {
String testClasses = "target/test-classes";
boolean autoUpdate = Settings.getBoolean(Settings.KEYS.AUTO_UPDATE);
Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false);
Engine instance = new Engine();
Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, autoUpdate);
boolean autoUpdate = getSettings().getBoolean(Settings.KEYS.AUTO_UPDATE);
getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false);
Engine instance = new Engine(getSettings());
getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, autoUpdate);
instance.scan(testClasses);
assertTrue(instance.getDependencies().size() > 0);
try {

View File

@@ -38,26 +38,35 @@ public class EngineModeIT extends BaseTest {
private String originalDataDir = null;
@Before
@Override
public void setUp() throws Exception {
super.setUp();
// Have to use System properties as the Settings object pulls from the
// system properties before configured properties
originalDataDir = Settings.getString(Settings.KEYS.DATA_DIRECTORY);
originalDataDir = getSettings().getString(Settings.KEYS.DATA_DIRECTORY);
System.setProperty(Settings.KEYS.DATA_DIRECTORY, tempDir.newFolder().getAbsolutePath());
}
@After
public void tearDown() throws IOException {
//delete temp files
FileUtils.delete(Settings.getDataDirectory());
//Reset system property to original value just to be safe for other tests.
System.setProperty(Settings.KEYS.DATA_DIRECTORY, originalDataDir);
@Override
public void tearDown() throws Exception {
try {
//delete temp files
FileUtils.delete(getSettings().getDataDirectory());
//Reset system property to original value just to be safe for other tests.
System.setProperty(Settings.KEYS.DATA_DIRECTORY, originalDataDir);
} catch (IOException ex) {
throw new RuntimeException(ex);
} finally {
super.tearDown();
}
}
@Test
public void testEvidenceCollectionAndEvidenceProcessingModes() throws Exception {
List<Dependency> dependencies;
try (Engine engine = new Engine(Engine.Mode.EVIDENCE_COLLECTION)) {
try (Engine engine = new Engine(Engine.Mode.EVIDENCE_COLLECTION, getSettings())) {
engine.openDatabase(); //does nothing in the current mode
assertDatabase(false);
for (AnalysisPhase phase : Engine.Mode.EVIDENCE_COLLECTION.getPhases()) {
assertThat(engine.getAnalyzers(phase), is(notNullValue()));
@@ -76,7 +85,8 @@ public class EngineModeIT extends BaseTest {
assertTrue(dependency.getVulnerabilities().isEmpty());
}
try (Engine engine = new Engine(Engine.Mode.EVIDENCE_PROCESSING)) {
try (Engine engine = new Engine(Engine.Mode.EVIDENCE_PROCESSING, getSettings())) {
engine.openDatabase();
assertDatabase(true);
for (AnalysisPhase phase : Engine.Mode.EVIDENCE_PROCESSING.getPhases()) {
assertThat(engine.getAnalyzers(phase), is(notNullValue()));
@@ -93,7 +103,8 @@ public class EngineModeIT extends BaseTest {
@Test
public void testStandaloneMode() throws Exception {
try (Engine engine = new Engine(Engine.Mode.STANDALONE)) {
try (Engine engine = new Engine(Engine.Mode.STANDALONE, getSettings())) {
engine.openDatabase();
assertDatabase(true);
for (AnalysisPhase phase : Engine.Mode.STANDALONE.getPhases()) {
assertThat(engine.getAnalyzers(phase), is(notNullValue()));
@@ -111,16 +122,15 @@ public class EngineModeIT extends BaseTest {
}
private void assertDatabase(boolean exists) throws Exception {
Assume.assumeThat(Settings.getString(Settings.KEYS.DB_DRIVER_NAME), is("org.h2.Driver"));
Path directory = Settings.getDataDirectory().toPath();
Assume.assumeThat(getSettings().getString(Settings.KEYS.DB_DRIVER_NAME), is("org.h2.Driver"));
Path directory = getSettings().getDataDirectory().toPath();
assertThat(Files.exists(directory), is(true));
assertThat(Files.isDirectory(directory), is(true));
Path database = directory.resolve(Settings.getString(Settings.KEYS.DB_FILE_NAME));
System.err.println(database.toString());
for (String f : directory.toFile().list()) {
System.err.println(f);
}
Path database = directory.resolve(getSettings().getString(Settings.KEYS.DB_FILE_NAME));
//System.err.println(database.toString());
//for (String f : directory.toFile().list()) {
// System.err.println(f);
//}
assertThat(Files.exists(database), is(exists));
}
}

View File

@@ -54,7 +54,7 @@ public class EngineTest extends BaseDBTestCase {
*/
@Test
public void testScanFile() throws DatabaseException {
Engine instance = new Engine();
Engine instance = new Engine(getSettings());
instance.addFileTypeAnalyzer(new JarAnalyzer());
File file = BaseTest.getResourceAsFile(this, "dwr.jar");
Dependency dwr = instance.scanFile(file);
@@ -72,7 +72,7 @@ public class EngineTest extends BaseDBTestCase {
@Test(expected = ExceptionCollection.class)
public void exceptionDuringAnalysisTaskExecutionIsFatal() throws DatabaseException, ExceptionCollection {
final ExecutorService executorService = Executors.newFixedThreadPool(3);
final Engine instance = new Engine();
final Engine instance = new Engine(getSettings());
final List<Throwable> exceptions = new ArrayList<>();
new Expectations() {
@@ -89,14 +89,11 @@ public class EngineTest extends BaseDBTestCase {
{
instance.getExecutorService(analyzer);
result = executorService;
instance.getAnalysisTasks(analyzer, exceptions);
result = failingAnalysisTask;
}
};
instance.executeAnalysisTasks(analyzer, exceptions);
assertTrue(executorService.isShutdown());
}
}

View File

@@ -39,14 +39,18 @@ import org.owasp.dependencycheck.utils.Settings.KEYS;
*/
public class AbstractSuppressionAnalyzerTest extends BaseTest {
/** A second suppression file to test with. */
/**
* A second suppression file to test with.
*/
private static final String OTHER_SUPPRESSIONS_FILE = "other-suppressions.xml";
/** Suppression file to test with. */
/**
* Suppression file to test with.
*/
private static final String SUPPRESSIONS_FILE = "suppressions.xml";
private AbstractSuppressionAnalyzer instance;
@Before
public void createObjectUnderTest() throws Exception {
instance = new AbstractSuppressionAnalyzerImpl();
@@ -75,7 +79,7 @@ public class AbstractSuppressionAnalyzerTest extends BaseTest {
/**
* Test of getRules method, of class AbstractSuppressionAnalyzer for
* suppression file on the classpath.
* suppression file on the class path.
*/
@Test
public void testGetRulesFromSuppressionFileInClasspath() throws Exception {
@@ -84,7 +88,8 @@ public class AbstractSuppressionAnalyzerTest extends BaseTest {
}
/**
* Assert that rules are loaded from multiple files if multiple files are denfined in the {@link Settings} singleton.
* Assert that rules are loaded from multiple files if multiple files are
* defined in the {@link Settings}.
*/
@Test
public void testGetRulesFromMultipleSuppressionFiles() throws Exception {
@@ -97,71 +102,75 @@ public class AbstractSuppressionAnalyzerTest extends BaseTest {
final int rulesInSecondFile = getNumberOfRulesLoadedFromPath(OTHER_SUPPRESSIONS_FILE) - rulesInCoreFile;
// WHEN initializing with both suppression files
final String[] suppressionFiles = { SUPPRESSIONS_FILE, OTHER_SUPPRESSIONS_FILE };
Settings.setArrayIfNotEmpty(KEYS.SUPPRESSION_FILE, suppressionFiles);
instance.initialize();
final String[] suppressionFiles = {SUPPRESSIONS_FILE, OTHER_SUPPRESSIONS_FILE};
getSettings().setArrayIfNotEmpty(KEYS.SUPPRESSION_FILE, suppressionFiles);
instance.initializeSettings(getSettings());
instance.initialize(null);
// THEN rules from both files were loaded
final int expectedSize = rulesInFirstFile + rulesInSecondFile + rulesInCoreFile;
assertThat("Expected suppressions from both files", instance.getRuleCount(), is(expectedSize));
}
@Test(expected = InitializationException.class)
public void testFailureToLocateSuppressionFileAnywhere() throws Exception {
Settings.setString(Settings.KEYS.SUPPRESSION_FILE, "doesnotexist.xml");
instance.initialize();
getSettings().setString(Settings.KEYS.SUPPRESSION_FILE, "doesnotexist.xml");
instance.initializeSettings(getSettings());
instance.initialize(null);
}
/**
* Return the number of rules that are loaded from the core suppression file.
* Return the number of rules that are loaded from the core suppression
* file.
*
* @return the number of rules defined in the core suppresion file.
* @return the number of rules defined in the core suppression file.
* @throws Exception if loading the rules fails.
*/
private int getNumberOfRulesLoadedInCoreFile() throws Exception {
Settings.removeProperty(KEYS.SUPPRESSION_FILE);
getSettings().removeProperty(KEYS.SUPPRESSION_FILE);
final AbstractSuppressionAnalyzerImpl coreFileAnalyzer = new AbstractSuppressionAnalyzerImpl();
coreFileAnalyzer.initialize();
coreFileAnalyzer.initializeSettings(getSettings());
coreFileAnalyzer.initialize(null);
return coreFileAnalyzer.getRuleCount();
}
/**
* Load a file into the {@link AbstractSuppressionAnalyzer} and return the number of rules loaded.
* Load a file into the {@link AbstractSuppressionAnalyzer} and return the
* number of rules loaded.
*
* @param path the path to load.
* @return the number of rules that were loaded (including the core rules).
* @throws Exception if loading the rules fails.
*/
private int getNumberOfRulesLoadedFromPath(final String path) throws Exception {
Settings.setString(KEYS.SUPPRESSION_FILE, path);
getSettings().setString(KEYS.SUPPRESSION_FILE, path);
final AbstractSuppressionAnalyzerImpl fileAnalyzer = new AbstractSuppressionAnalyzerImpl();
fileAnalyzer.initialize();
fileAnalyzer.initializeSettings(getSettings());
fileAnalyzer.initialize(null);
return fileAnalyzer.getRuleCount();
}
public class AbstractSuppressionAnalyzerImpl extends AbstractSuppressionAnalyzer {
@Override
public void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public String getName() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public AnalysisPhase getAnalysisPhase() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
protected String getAnalyzerEnabledSettingKey() {
return "unknown";
}
}
}

View File

@@ -40,13 +40,14 @@ public class AnalyzerServiceTest extends BaseDBTestCase {
*/
@Test
public void testGetAnalyzers() {
AnalyzerService instance = new AnalyzerService(Thread.currentThread().getContextClassLoader());
AnalyzerService instance = new AnalyzerService(Thread.currentThread().getContextClassLoader(), false);
List<Analyzer> result = instance.getAnalyzers();
boolean found = false;
for (Analyzer a : result) {
if ("Jar Analyzer".equals(a.getName())) {
found = true;
break;
}
}
assertTrue("JarAnalyzer loaded", found);
@@ -57,7 +58,7 @@ public class AnalyzerServiceTest extends BaseDBTestCase {
*/
@Test
public void testGetAnalyzers_SpecificPhases() throws Exception {
AnalyzerService instance = new AnalyzerService(Thread.currentThread().getContextClassLoader());
AnalyzerService instance = new AnalyzerService(Thread.currentThread().getContextClassLoader(), false);
List<Analyzer> result = instance.getAnalyzers(INITIAL, FINAL);
for (Analyzer a : result) {
@@ -72,8 +73,7 @@ public class AnalyzerServiceTest extends BaseDBTestCase {
*/
@Test
public void testGetExperimentalAnalyzers() {
Settings.setBoolean(Settings.KEYS.ANALYZER_EXPERIMENTAL_ENABLED, false);
AnalyzerService instance = new AnalyzerService(Thread.currentThread().getContextClassLoader());
AnalyzerService instance = new AnalyzerService(Thread.currentThread().getContextClassLoader(), false);
List<Analyzer> result = instance.getAnalyzers();
String experimental = "CMake Analyzer";
boolean found = false;
@@ -83,8 +83,8 @@ public class AnalyzerServiceTest extends BaseDBTestCase {
}
}
assertFalse("Experimental analyzer loaded when set to false", found);
Settings.setBoolean(Settings.KEYS.ANALYZER_EXPERIMENTAL_ENABLED, true);
instance = new AnalyzerService(Thread.currentThread().getContextClassLoader(), true);
result = instance.getAnalyzers();
found = false;
for (Analyzer a : result) {

View File

@@ -41,6 +41,7 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase {
@Test
public void testSupportsExtensions() {
ArchiveAnalyzer instance = new ArchiveAnalyzer();
instance.initializeSettings(getSettings());
Set<String> expResult = new HashSet<>();
expResult.add("zip");
expResult.add("war");
@@ -65,6 +66,7 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase {
@Test
public void testGetName() {
ArchiveAnalyzer instance = new ArchiveAnalyzer();
instance.initializeSettings(getSettings());
String expResult = "Archive Analyzer";
String result = instance.getName();
assertEquals(expResult, result);
@@ -77,6 +79,7 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase {
public void testSupportsExtension() {
String extension = "test.7z"; //not supported
ArchiveAnalyzer instance = new ArchiveAnalyzer();
instance.initializeSettings(getSettings());
assertFalse(extension, instance.accept(new File(extension)));
}
@@ -86,6 +89,7 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase {
@Test
public void testGetAnalysisPhase() {
ArchiveAnalyzer instance = new ArchiveAnalyzer();
instance.initializeSettings(getSettings());
AnalysisPhase expResult = AnalysisPhase.INITIAL;
AnalysisPhase result = instance.getAnalysisPhase();
assertEquals(expResult, result);
@@ -97,10 +101,11 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase {
@Test
public void testInitialize() {
ArchiveAnalyzer instance = new ArchiveAnalyzer();
instance.initializeSettings(getSettings());
try {
instance.setEnabled(true);
instance.setFilesMatched(true);
instance.initialize();
instance.initialize(null);
} catch (InitializationException ex) {
fail(ex.getMessage());
} finally {
@@ -120,16 +125,18 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase {
@Test
public void testAnalyze() throws Exception {
ArchiveAnalyzer instance = new ArchiveAnalyzer();
instance.initializeSettings(getSettings());
//trick the analyzer into thinking it is active.
instance.accept(new File("test.ear"));
try {
instance.initialize();
getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false);
Engine engine = new Engine(getSettings());
instance.initialize(engine);
File file = BaseTest.getResourceAsFile(this, "daytrader-ear-2.1.7.ear");
Dependency dependency = new Dependency(file);
Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false);
Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false);
Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false);
Engine engine = new Engine();
int initial_size = engine.getDependencies().size();
instance.analyze(dependency, engine);
@@ -150,16 +157,17 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase {
@Test
public void testAnalyzeExecutableJar() throws Exception {
ArchiveAnalyzer instance = new ArchiveAnalyzer();
instance.initializeSettings(getSettings());
//trick the analyzer into thinking it is active.
instance.accept(new File("test.ear"));
try {
instance.initialize();
instance.initialize(null);
File file = BaseTest.getResourceAsFile(this, "bootable-0.1.0.jar");
Dependency dependency = new Dependency(file);
Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false);
Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false);
Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false);
Engine engine = new Engine();
getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false);
Engine engine = new Engine(getSettings());
int initial_size = engine.getDependencies().size();
instance.analyze(dependency, engine);
@@ -180,19 +188,20 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase {
@Test
public void testAnalyzeTar() throws Exception {
ArchiveAnalyzer instance = new ArchiveAnalyzer();
instance.initializeSettings(getSettings());
//trick the analyzer into thinking it is active so that it will initialize
instance.accept(new File("test.tar"));
try {
instance.initialize();
instance.initialize(null);
//File file = new File(this.getClass().getClassLoader().getResource("file.tar").getPath());
//File file = new File(this.getClass().getClassLoader().getResource("stagedhttp-modified.tar").getPath());
File file = BaseTest.getResourceAsFile(this, "stagedhttp-modified.tar");
Dependency dependency = new Dependency(file);
Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false);
Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false);
Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false);
Engine engine = new Engine();
getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false);
Engine engine = new Engine(getSettings());
int initial_size = engine.getDependencies().size();
instance.analyze(dependency, engine);
@@ -212,17 +221,18 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase {
@Test
public void testAnalyzeTarGz() throws Exception {
ArchiveAnalyzer instance = new ArchiveAnalyzer();
instance.initializeSettings(getSettings());
instance.accept(new File("zip")); //ensure analyzer is "enabled"
try {
instance.initialize();
instance.initialize(null);
//File file = new File(this.getClass().getClassLoader().getResource("file.tar.gz").getPath());
File file = BaseTest.getResourceAsFile(this, "file.tar.gz");
//Dependency dependency = new Dependency(file);
Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false);
Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false);
Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false);
Engine engine = new Engine();
getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false);
Engine engine = new Engine(getSettings());
int initial_size = engine.getDependencies().size();
//instance.analyze(dependency, engine);
@@ -243,14 +253,15 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase {
@Test
public void testAnalyzeTarBz2() throws Exception {
ArchiveAnalyzer instance = new ArchiveAnalyzer();
instance.initializeSettings(getSettings());
instance.accept(new File("zip")); //ensure analyzer is "enabled"
try {
instance.initialize();
instance.initialize(null);
File file = BaseTest.getResourceAsFile(this, "file.tar.bz2");
Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false);
Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false);
Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false);
Engine engine = new Engine();
getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false);
Engine engine = new Engine(getSettings());
int initial_size = engine.getDependencies().size();
engine.scan(file);
engine.analyzeDependencies();
@@ -268,16 +279,17 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase {
@Test
public void testAnalyzeTgz() throws Exception {
ArchiveAnalyzer instance = new ArchiveAnalyzer();
instance.initializeSettings(getSettings());
instance.accept(new File("zip")); //ensure analyzer is "enabled"
try {
instance.initialize();
instance.initialize(null);
//File file = new File(this.getClass().getClassLoader().getResource("file.tgz").getPath());
File file = BaseTest.getResourceAsFile(this, "file.tgz");
Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false);
Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false);
Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false);
Engine engine = new Engine();
getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false);
Engine engine = new Engine(getSettings());
int initial_size = engine.getDependencies().size();
engine.scan(file);
@@ -297,14 +309,15 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase {
@Test
public void testAnalyzeTbz2() throws Exception {
ArchiveAnalyzer instance = new ArchiveAnalyzer();
instance.initializeSettings(getSettings());
instance.accept(new File("zip")); //ensure analyzer is "enabled"
try {
instance.initialize();
instance.initialize(null);
File file = BaseTest.getResourceAsFile(this, "file.tbz2");
Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false);
Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false);
Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false);
Engine engine = new Engine();
getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false);
Engine engine = new Engine(getSettings());
int initial_size = engine.getDependencies().size();
engine.scan(file);
engine.analyzeDependencies();
@@ -322,16 +335,17 @@ public class ArchiveAnalyzerIT extends BaseDBTestCase {
@Test
public void testAnalyze_badZip() throws Exception {
ArchiveAnalyzer instance = new ArchiveAnalyzer();
instance.initializeSettings(getSettings());
try {
instance.initialize();
instance.initialize(null);
//File file = new File(this.getClass().getClassLoader().getResource("test.zip").getPath());
File file = BaseTest.getResourceAsFile(this, "test.zip");
Dependency dependency = new Dependency(file);
Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false);
Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false);
Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false);
Engine engine = new Engine();
getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false);
Engine engine = new Engine(getSettings());
int initial_size = engine.getDependencies().size();
// boolean failed = false;
// try {

View File

@@ -36,8 +36,10 @@ import org.owasp.dependencycheck.utils.Settings;
public class ArchiveAnalyzerTest extends BaseTest {
@Before
public void setUp() {
Settings.setString(Settings.KEYS.ADDITIONAL_ZIP_EXTENSIONS, "z2, z3");
@Override
public void setUp() throws Exception {
super.setUp();
getSettings().setString(Settings.KEYS.ADDITIONAL_ZIP_EXTENSIONS, "z2, z3");
}
/**
@@ -47,6 +49,7 @@ public class ArchiveAnalyzerTest extends BaseTest {
public void testZippableExtensions() throws Exception {
assumeFalse(isPreviouslyLoaded("org.owasp.dependencycheck.analyzer.ArchiveAnalyzer"));
ArchiveAnalyzer instance = new ArchiveAnalyzer();
instance.initializeSettings(getSettings());
assertTrue(instance.getFileFilter().accept(new File("c:/test.zip")));
assertTrue(instance.getFileFilter().accept(new File("c:/test.z2")));
assertTrue(instance.getFileFilter().accept(new File("c:/test.z3")));
@@ -59,15 +62,7 @@ public class ArchiveAnalyzerTest extends BaseTest {
m.setAccessible(true);
Object t = m.invoke(Thread.currentThread().getContextClassLoader(), className);
return t != null;
} catch (NoSuchMethodException ex) {
Logger.getLogger(ArchiveAnalyzerTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(ArchiveAnalyzerTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(ArchiveAnalyzerTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(ArchiveAnalyzerTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(ArchiveAnalyzerTest.class.getName()).log(Level.SEVERE, null, ex);
}
return false;

View File

@@ -65,11 +65,14 @@ public class AssemblyAnalyzerTest extends BaseTest {
* @throws Exception if anything goes sideways
*/
@Before
@Override
public void setUp() throws Exception {
super.setUp();
try {
analyzer = new AssemblyAnalyzer();
analyzer.initializeSettings(getSettings());
analyzer.accept(new File("test.dll")); // trick into "thinking it is active"
analyzer.initialize();
analyzer.initialize(null);
assertGrokAssembly();
} catch (Exception e) {
if (e.getMessage().contains("Could not execute .NET AssemblyAnalyzer")) {
@@ -86,8 +89,8 @@ public class AssemblyAnalyzerTest extends BaseTest {
// directory and they must match the resources they were created from.
File grokAssemblyExeFile = null;
File grokAssemblyConfigFile = null;
File tempDirectory = Settings.getTempDirectory();
File tempDirectory = getSettings().getTempDirectory();
for (File file : tempDirectory.listFiles()) {
String filename = file.getName();
if (filename.startsWith("GKA") && filename.endsWith(".exe")) {
@@ -99,10 +102,8 @@ public class AssemblyAnalyzerTest extends BaseTest {
grokAssemblyConfigFile = new File(grokAssemblyExeFile.getPath() + ".config");
assertTrue("The GrokAssembly config was not created.", grokAssemblyConfigFile.isFile());
assertFileContent("The GrokAssembly executable has incorrect content.", "GrokAssembly.exe",
grokAssemblyExeFile);
assertFileContent("The GrokAssembly config has incorrect content.", "GrokAssembly.exe.config",
grokAssemblyConfigFile);
assertFileContent("The GrokAssembly executable has incorrect content.", "GrokAssembly.exe", grokAssemblyExeFile);
assertFileContent("The GrokAssembly config has incorrect content.", "GrokAssembly.exe.config", grokAssemblyConfigFile);
}
private void assertFileContent(String message, String expectedResourceName, File actualFile) throws IOException {
@@ -183,7 +184,7 @@ public class AssemblyAnalyzerTest extends BaseTest {
//This test doesn't work on Windows.
assumeFalse(System.getProperty("os.name").startsWith("Windows"));
String oldValue = Settings.getString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH);
String oldValue = getSettings().getString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH);
// if oldValue is null, that means that neither the system property nor the setting has
// been set. If that's the case, then we have to make it such that when we recover,
// null still comes back. But you can't put a null value in a HashMap, so we have to set
@@ -191,7 +192,7 @@ public class AssemblyAnalyzerTest extends BaseTest {
if (oldValue == null) {
System.setProperty(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH, "/yooser/bine/mono");
} else {
Settings.setString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH, "/yooser/bine/mono");
getSettings().setString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH, "/yooser/bine/mono");
}
String oldProp = System.getProperty(LOG_KEY, "info");
@@ -201,7 +202,7 @@ public class AssemblyAnalyzerTest extends BaseTest {
// Have to make a NEW analyzer because during setUp, it would have gotten the correct one
AssemblyAnalyzer aanalyzer = new AssemblyAnalyzer();
aanalyzer.accept(new File("test.dll")); // trick into "thinking it is active"
aanalyzer.initialize();
aanalyzer.initialize(null);
fail("Expected an InitializationException");
} catch (InitializationException ae) {
assertEquals("An error occurred with the .NET AssemblyAnalyzer", ae.getMessage());
@@ -213,13 +214,20 @@ public class AssemblyAnalyzerTest extends BaseTest {
if (oldValue == null) {
System.getProperties().remove(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH);
} else {
Settings.setString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH, oldValue);
getSettings().setString(Settings.KEYS.ANALYZER_ASSEMBLY_MONO_PATH, oldValue);
}
}
}
@After
@Override
public void tearDown() throws Exception {
analyzer.closeAnalyzer();
try {
analyzer.closeAnalyzer();
} catch (Exception ex) {
throw new RuntimeException(ex);
} finally {
super.tearDown();
}
}
}

View File

@@ -30,11 +30,13 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* Unit tests for AutoconfAnalyzer. The test resources under autoconf/ were obtained from outside open source software projects.
* Links to those projects are given below.
* Unit tests for AutoconfAnalyzer. The test resources under autoconf/ were
* obtained from outside open source software projects. Links to those projects
* are given below.
*
* @author Dale Visser
* @see <a href="http://readable.sourceforge.net/">Readable Lisp S-expressions Project</a>
* @see <a href="http://readable.sourceforge.net/">Readable Lisp S-expressions
* Project</a>
* @see <a href="https://gnu.org/software/binutils/">GNU Binutils</a>
* @see <a href="https://gnu.org/software/ghostscript/">GNU Ghostscript</a>
*/
@@ -66,10 +68,13 @@ public class AutoconfAnalyzerTest extends BaseTest {
* @throws Exception thrown if there is a problem
*/
@Before
@Override
public void setUp() throws Exception {
super.setUp();
analyzer = new AutoconfAnalyzer();
analyzer.initializeSettings(getSettings());
analyzer.setFilesMatched(true);
analyzer.initialize();
analyzer.initialize(null);
}
/**
@@ -78,13 +83,16 @@ public class AutoconfAnalyzerTest extends BaseTest {
* @throws Exception thrown if there is a problem
*/
@After
@Override
public void tearDown() throws Exception {
analyzer.close();
analyzer = null;
super.tearDown();
}
/**
* Test whether expected evidence is gathered from Ghostscript's configure.ac.
* Test whether expected evidence is gathered from Ghostscript's
* configure.
*
* @throws AnalysisException is thrown when an exception occurs.
*/
@@ -130,7 +138,8 @@ public class AutoconfAnalyzerTest extends BaseTest {
}
/**
* Test whether expected evidence is gathered from GNU Ghostscript's configure.
* Test whether expected evidence is gathered from GNU Ghostscript's
* configure.
*
* @throws AnalysisException is thrown when an exception occurs.
*/

View File

@@ -61,21 +61,29 @@ public class CMakeAnalyzerTest extends BaseDBTestCase {
* @throws Exception if there is a problem
*/
@Before
@Override
public void setUp() throws Exception {
super.setUp();
analyzer = new CMakeAnalyzer();
analyzer.initializeSettings(getSettings());
analyzer.setFilesMatched(true);
analyzer.initialize();
analyzer.initialize(null);
}
/**
* Cleanup any resources used.
*
* @throws Exception if there is a problem
*/
@After
@Override
public void tearDown() throws Exception {
analyzer.close();
analyzer = null;
try {
analyzer.close();
} catch (Exception ex) {
throw new RuntimeException(ex);
} finally {
super.tearDown();
}
}
/**
@@ -124,14 +132,15 @@ public class CMakeAnalyzerTest extends BaseDBTestCase {
final String product = "zlib";
assertProductEvidence(result, product);
}
private void assertProductEvidence(Dependency result, String product) {
assertTrue("Expected product evidence to contain \"" + product + "\".",
result.getProductEvidence().toString().contains(product));
}
/**
* Test whether expected version evidence is gathered from OpenCV's third party cmake files.
* Test whether expected version evidence is gathered from OpenCV's third
* party cmake files.
*
* @throws AnalysisException is thrown when an exception occurs.
*/
@@ -139,7 +148,7 @@ public class CMakeAnalyzerTest extends BaseDBTestCase {
public void testAnalyzeCMakeListsOpenCV3rdParty() throws AnalysisException, DatabaseException {
final Dependency result = new Dependency(BaseTest.getResourceAsFile(
this, "cmake/opencv/3rdparty/ffmpeg/ffmpeg_version.cmake"));
final Engine engine = new Engine();
final Engine engine = new Engine(getSettings());
analyzer.analyze(result, engine);
assertProductEvidence(result, "libavcodec");
assertVersionEvidence(result, "55.18.102");
@@ -151,12 +160,12 @@ public class CMakeAnalyzerTest extends BaseDBTestCase {
assertProductEvidence(last, "libavresample");
assertVersionEvidence(last, "1.0.1");
}
private void assertVersionEvidence(Dependency result, String version) {
assertTrue("Expected version evidence to contain \"" + version + "\".",
result.getVersionEvidence().toString().contains(version));
}
@Test(expected = InitializationException.class)
public void analyzerIsDisabledInCaseOfMissingMessageDigest() throws InitializationException {
new MockUp<MessageDigest>() {
@@ -165,12 +174,13 @@ public class CMakeAnalyzerTest extends BaseDBTestCase {
throw new NoSuchAlgorithmException();
}
};
analyzer = new CMakeAnalyzer();
analyzer.setFilesMatched(true);
assertTrue(analyzer.isEnabled());
analyzer.initialize();
analyzer.initializeSettings(getSettings());
analyzer.initialize(null);
assertFalse(analyzer.isEnabled());
}
}

View File

@@ -24,8 +24,6 @@ import java.util.List;
import java.util.Set;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.queryparser.classic.ParseException;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.owasp.dependencycheck.BaseTest;
import org.owasp.dependencycheck.BaseDBTestCase;
@@ -58,9 +56,9 @@ public class CPEAnalyzerIT extends BaseDBTestCase {
String vendor = "apache software foundation";
String product = "struts 2 core";
CPEAnalyzer instance = new CPEAnalyzer();
CPEAnalyzer instance = new CPEAnalyzer();
instance.initializeSettings(getSettings());
String queryText = instance.buildSearch(vendor, product, null, null);
String expResult = " product:( struts 2 core ) AND vendor:( apache software foundation ) ";
assertTrue(expResult.equals(queryText));
@@ -86,21 +84,26 @@ public class CPEAnalyzerIT extends BaseDBTestCase {
@Test
public void testDetermineCPE_full() throws Exception {
//update needs to be performed so that xtream can be tested
Engine e = new Engine();
Engine e = new Engine(getSettings());
e.doUpdates();
CPEAnalyzer cpeAnalyzer = new CPEAnalyzer();
try {
cpeAnalyzer.initialize();
cpeAnalyzer.initializeSettings(getSettings());
cpeAnalyzer.initialize(e);
FileNameAnalyzer fnAnalyzer = new FileNameAnalyzer();
fnAnalyzer.initialize();
fnAnalyzer.initializeSettings(getSettings());
fnAnalyzer.initialize(e);
JarAnalyzer jarAnalyzer = new JarAnalyzer();
jarAnalyzer.initializeSettings(getSettings());
jarAnalyzer.accept(new File("test.jar"));//trick analyzer into "thinking it is active"
jarAnalyzer.initialize();
jarAnalyzer.initialize(e);
HintAnalyzer hAnalyzer = new HintAnalyzer();
hAnalyzer.initialize();
hAnalyzer.initializeSettings(getSettings());
hAnalyzer.initialize(e);
FalsePositiveAnalyzer fp = new FalsePositiveAnalyzer();
fp.initialize();
fp.initializeSettings(getSettings());
fp.initialize(e);
callDetermineCPE_full("hazelcast-2.5.jar", null, cpeAnalyzer, fnAnalyzer, jarAnalyzer, hAnalyzer, fp);
callDetermineCPE_full("spring-context-support-2.5.5.jar", "cpe:/a:springsource:spring_framework:2.5.5", cpeAnalyzer, fnAnalyzer, jarAnalyzer, hAnalyzer, fp);
@@ -159,10 +162,12 @@ public class CPEAnalyzerIT extends BaseDBTestCase {
fnAnalyzer.analyze(struts, null);
HintAnalyzer hintAnalyzer = new HintAnalyzer();
hintAnalyzer.initialize();
hintAnalyzer.initializeSettings(getSettings());
hintAnalyzer.initialize(null);
JarAnalyzer jarAnalyzer = new JarAnalyzer();
jarAnalyzer.initializeSettings(getSettings());
jarAnalyzer.accept(new File("test.jar"));//trick analyzer into "thinking it is active"
jarAnalyzer.initialize();
jarAnalyzer.initialize(null);
jarAnalyzer.analyze(struts, null);
hintAnalyzer.analyze(struts, null);
@@ -185,7 +190,10 @@ public class CPEAnalyzerIT extends BaseDBTestCase {
hintAnalyzer.analyze(spring3, null);
CPEAnalyzer instance = new CPEAnalyzer();
instance.open();
Engine engine = new Engine(getSettings());
engine.openDatabase();
instance.initializeSettings(getSettings());
instance.initialize(engine);
instance.determineCPE(commonValidator);
instance.determineCPE(struts);
instance.determineCPE(spring);
@@ -204,6 +212,7 @@ public class CPEAnalyzerIT extends BaseDBTestCase {
assertTrue("Incorrect match size - spring3 - " + spring3.getIdentifiers().size(), spring3.getIdentifiers().size() >= 1);
jarAnalyzer.close();
engine.cleanup();
}
/**
@@ -219,7 +228,10 @@ public class CPEAnalyzerIT extends BaseDBTestCase {
openssl.getVersionEvidence().addEvidence("test", "version", "1.0.1c", Confidence.HIGHEST);
CPEAnalyzer instance = new CPEAnalyzer();
instance.open();
Engine engine = new Engine(getSettings());
engine.openDatabase();
instance.initializeSettings(getSettings());
instance.initialize(engine);
instance.determineIdentifiers(openssl, "openssl", "openssl", Confidence.HIGHEST);
instance.close();
@@ -227,7 +239,7 @@ public class CPEAnalyzerIT extends BaseDBTestCase {
Identifier expIdentifier = new Identifier("cpe", expResult, expResult);
assertTrue(openssl.getIdentifiers().contains(expIdentifier));
engine.cleanup();
}
/**
@@ -243,7 +255,10 @@ public class CPEAnalyzerIT extends BaseDBTestCase {
String expProduct = "struts";
CPEAnalyzer instance = new CPEAnalyzer();
instance.open();
Engine engine = new Engine(getSettings());
engine.openDatabase();
instance.initializeSettings(getSettings());
instance.initialize(engine);
Set<String> productWeightings = Collections.singleton("struts2");
Set<String> vendorWeightings = Collections.singleton("apache");

View File

@@ -55,10 +55,13 @@ public class ComposerLockAnalyzerTest extends BaseDBTestCase {
* @throws Exception thrown if there is a problem
*/
@Before
@Override
public void setUp() throws Exception {
super.setUp();
analyzer = new ComposerLockAnalyzer();
analyzer.initializeSettings(getSettings());
analyzer.setFilesMatched(true);
analyzer.initialize();
analyzer.initialize(null);
}
/**
@@ -67,9 +70,10 @@ public class ComposerLockAnalyzerTest extends BaseDBTestCase {
* @throws Exception thrown if there is a problem
*/
@After
@Override
public void tearDown() throws Exception {
analyzer.close();
analyzer = null;
super.tearDown();
}
/**
@@ -95,27 +99,27 @@ public class ComposerLockAnalyzerTest extends BaseDBTestCase {
*/
@Test
public void testAnalyzePackageJson() throws Exception {
final Engine engine = new Engine();
final Engine engine = new Engine(getSettings());
final Dependency result = new Dependency(BaseTest.getResourceAsFile(this,
"composer.lock"));
analyzer.analyze(result, engine);
}
@Test(expected = InitializationException.class)
public void analyzerIsDisabledInCaseOfMissingMessageDigest() throws InitializationException {
new MockUp<MessageDigest>() {
@Mock
MessageDigest getInstance(String ignore) throws NoSuchAlgorithmException {
throw new NoSuchAlgorithmException();
throw new NoSuchAlgorithmException("SHA1 is missing");
}
};
analyzer = new ComposerLockAnalyzer();
analyzer.setFilesMatched(true);
analyzer.initializeSettings(getSettings());
assertTrue(analyzer.isEnabled());
analyzer.initialize();
analyzer.initialize(null);
assertFalse(analyzer.isEnabled());
}
}

View File

@@ -81,7 +81,8 @@ public class FileNameAnalyzerTest extends BaseTest {
public void testInitialize() {
FileNameAnalyzer instance = new FileNameAnalyzer();
try {
instance.initialize();
instance.initializeSettings(getSettings());
instance.initialize(null);
} catch (InitializationException ex) {
fail(ex.getMessage());
}

View File

@@ -69,11 +69,11 @@ public class HintAnalyzerTest extends BaseDBTestCase {
//File spring = new File(this.getClass().getClassLoader().getResource("spring-core-3.0.0.RELEASE.jar").getPath());
File spring = BaseTest.getResourceAsFile(this, "spring-core-3.0.0.RELEASE.jar");
//Dependency spring = new Dependency(files);
Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false);
Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false);
Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false);
Engine engine = new Engine();
getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false);
Engine engine = new Engine(getSettings());
engine.scan(guice);
engine.scan(spring);
engine.analyzeDependencies();
@@ -91,14 +91,14 @@ public class HintAnalyzerTest extends BaseDBTestCase {
final Evidence springTest3 = new Evidence("hint analyzer", "vendor", "vmware", Confidence.HIGH);
final Evidence springTest4 = new Evidence("hint analyzer", "product", "springsource_spring_framework", Confidence.HIGH);
final Evidence springTest5 = new Evidence("hint analyzer", "vendor", "vmware", Confidence.HIGH);
Set<Evidence> evidence = gdep.getEvidence().getEvidence();
assertFalse(evidence.contains(springTest1));
assertFalse(evidence.contains(springTest2));
assertFalse(evidence.contains(springTest3));
assertFalse(evidence.contains(springTest4));
assertFalse(evidence.contains(springTest5));
evidence = sdep.getEvidence().getEvidence();
assertTrue(evidence.contains(springTest1));
assertTrue(evidence.contains(springTest2));
@@ -106,15 +106,17 @@ public class HintAnalyzerTest extends BaseDBTestCase {
//assertTrue(evidence.contains(springTest4));
//assertTrue(evidence.contains(springTest5));
}
/**
* Test of analyze method, of class HintAnalyzer.
*/
@Test
public void testAnalyze_1() throws Exception {
File path = BaseTest.getResourceAsFile(this, "hints_12.xml");
Settings.setString(Settings.KEYS.HINTS_FILE, path.getPath());
getSettings().setString(Settings.KEYS.HINTS_FILE, path.getPath());
HintAnalyzer instance = new HintAnalyzer();
instance.initialize();
instance.initializeSettings(getSettings());
instance.initialize(null);
Dependency d = new Dependency();
d.getVersionEvidence().addEvidence("version source", "given version name", "1.2.3", Confidence.HIGH);
d.getVersionEvidence().addEvidence("hint analyzer", "remove version name", "value", Confidence.HIGH);
@@ -124,14 +126,13 @@ public class HintAnalyzerTest extends BaseDBTestCase {
d.getVendorEvidence().addEvidence("hint analyzer", "other vendor name", "vendor", Confidence.HIGH);
d.getProductEvidence().addEvidence("hint analyzer", "other product name", "product", Confidence.HIGH);
assertEquals("vendor evidence mismatch",2, d.getVendorEvidence().size());
assertEquals("product evidence mismatch",2, d.getProductEvidence().size());
assertEquals("version evidence mismatch",3, d.getVersionEvidence().size());
assertEquals("vendor evidence mismatch", 2, d.getVendorEvidence().size());
assertEquals("product evidence mismatch", 2, d.getProductEvidence().size());
assertEquals("version evidence mismatch", 3, d.getVersionEvidence().size());
instance.analyze(d, null);
assertEquals("vendor evidence mismatch",1, d.getVendorEvidence().size());
assertEquals("product evidence mismatch",1, d.getProductEvidence().size());
assertEquals("version evidence mismatch",2, d.getVersionEvidence().size());
assertEquals("vendor evidence mismatch", 1, d.getVendorEvidence().size());
assertEquals("product evidence mismatch", 1, d.getProductEvidence().size());
assertEquals("version evidence mismatch", 2, d.getVersionEvidence().size());
}
}

View File

@@ -50,7 +50,8 @@ public class JarAnalyzerTest extends BaseTest {
File file = BaseTest.getResourceAsFile(this, "struts2-core-2.1.2.jar");
Dependency result = new Dependency(file);
JarAnalyzer instance = new JarAnalyzer();
instance.initializeFileTypeAnalyzer();
instance.initializeSettings(getSettings());
instance.initializeFileTypeAnalyzer(null);
instance.analyze(result, null);
assertTrue(result.getVendorEvidence().toString().toLowerCase().contains("apache"));
assertTrue(result.getVendorEvidence().getWeighting().contains("apache"));
@@ -115,7 +116,8 @@ public class JarAnalyzerTest extends BaseTest {
@Test
public void testAcceptSupportedExtensions() throws Exception {
JarAnalyzer instance = new JarAnalyzer();
instance.initialize();
instance.initializeSettings(getSettings());
instance.initialize(null);
instance.setEnabled(true);
String[] files = {"test.jar", "test.war"};
for (String name : files) {
@@ -181,12 +183,12 @@ public class JarAnalyzerTest extends BaseTest {
JarAnalyzer instance = new JarAnalyzer();
Dependency macOSMetaDataFile = new Dependency();
macOSMetaDataFile
.setActualFilePath(FileUtils.getFile("src", "test", "resources", "._avro-ipc-1.5.0.jar").getAbsolutePath());
.setActualFilePath(FileUtils.getFile("src", "test", "resources", "._avro-ipc-1.5.0.jar").getAbsolutePath());
macOSMetaDataFile.setFileName("._avro-ipc-1.5.0.jar");
Dependency actualJarFile = new Dependency();
actualJarFile.setActualFilePath(BaseTest.getResourceAsFile(this, "avro-ipc-1.5.0.jar").getAbsolutePath());
actualJarFile.setFileName("avro-ipc-1.5.0.jar");
Engine engine = new Engine();
Engine engine = new Engine(getSettings());
engine.setDependencies(Arrays.asList(macOSMetaDataFile, actualJarFile));
instance.analyzeDependency(macOSMetaDataFile, engine);
}
@@ -196,9 +198,9 @@ public class JarAnalyzerTest extends BaseTest {
JarAnalyzer instance = new JarAnalyzer();
Dependency textFileWithJarExtension = new Dependency();
textFileWithJarExtension
.setActualFilePath(BaseTest.getResourceAsFile(this, "textFileWithJarExtension.jar").getAbsolutePath());
.setActualFilePath(BaseTest.getResourceAsFile(this, "textFileWithJarExtension.jar").getAbsolutePath());
textFileWithJarExtension.setFileName("textFileWithJarExtension.jar");
Engine engine = new Engine();
Engine engine = new Engine(getSettings());
engine.setDependencies(Collections.singletonList(textFileWithJarExtension));
instance.analyzeDependency(textFileWithJarExtension, engine);
}

View File

@@ -48,10 +48,13 @@ public class NodePackageAnalyzerTest extends BaseTest {
* @throws Exception thrown if there is a problem
*/
@Before
@Override
public void setUp() throws Exception {
super.setUp();
analyzer = new NodePackageAnalyzer();
analyzer.setFilesMatched(true);
analyzer.initialize();
analyzer.initializeSettings(getSettings());
analyzer.initialize(null);
}
/**
@@ -60,9 +63,10 @@ public class NodePackageAnalyzerTest extends BaseTest {
* @throws Exception thrown if there is a problem
*/
@After
@Override
public void tearDown() throws Exception {
analyzer.close();
analyzer = null;
super.tearDown();
}
/**

View File

@@ -16,16 +16,20 @@ public class NspAnalyzerTest extends BaseTest {
private NspAnalyzer analyzer;
@Before
@Override
public void setUp() throws Exception {
super.setUp();
analyzer = new NspAnalyzer();
analyzer.setFilesMatched(true);
analyzer.initialize();
analyzer.initializeSettings(getSettings());
analyzer.initialize(null);
}
@After
@Override
public void tearDown() throws Exception {
analyzer.close();
analyzer = null;
super.tearDown();
}
@Test

View File

@@ -31,9 +31,12 @@ public class NuspecAnalyzerTest extends BaseTest {
private NuspecAnalyzer instance;
@Before
@Override
public void setUp() throws Exception {
super.setUp();
instance = new NuspecAnalyzer();
instance.initialize();
instance.initializeSettings(getSettings());
instance.initialize(null);
instance.setEnabled(true);
}
@@ -53,5 +56,3 @@ public class NuspecAnalyzerTest extends BaseTest {
assertEquals(AnalysisPhase.INFORMATION_COLLECTION, instance.getAnalysisPhase());
}
}
// vim: cc=120:sw=4:ts=4:sts=4

View File

@@ -47,10 +47,13 @@ public class OpenSSLAnalyzerTest extends BaseTest {
* @throws Exception if there is a problem
*/
@Before
@Override
public void setUp() throws Exception {
super.setUp();
analyzer = new OpenSSLAnalyzer();
analyzer.setFilesMatched(true);
analyzer.initialize();
analyzer.initializeSettings(getSettings());
analyzer.initialize(null);
}
/**
@@ -59,9 +62,10 @@ public class OpenSSLAnalyzerTest extends BaseTest {
* @throws Exception if there is a problem
*/
@After
@Override
public void tearDown() throws Exception {
analyzer.close();
analyzer = null;
super.tearDown();
}
/**
@@ -69,8 +73,7 @@ public class OpenSSLAnalyzerTest extends BaseTest {
*/
@Test
public void testGetName() {
assertEquals("Analyzer name wrong.", "OpenSSL Source Analyzer",
analyzer.getName());
assertEquals("Analyzer name wrong.", "OpenSSL Source Analyzer", analyzer.getName());
}
/**

View File

@@ -49,10 +49,13 @@ public class PythonDistributionAnalyzerTest extends BaseTest {
* @throws Exception thrown if there is a problem
*/
@Before
@Override
public void setUp() throws Exception {
super.setUp();
analyzer = new PythonDistributionAnalyzer();
analyzer.setFilesMatched(true);
analyzer.initialize();
analyzer.initializeSettings(getSettings());
analyzer.initialize(null);
}
/**
@@ -61,9 +64,10 @@ public class PythonDistributionAnalyzerTest extends BaseTest {
* @throws Exception thrown if there is a problem
*/
@After
@Override
public void tearDown() throws Exception {
analyzer.close();
analyzer = null;
super.tearDown();
}
/**

View File

@@ -48,10 +48,13 @@ public class PythonPackageAnalyzerTest extends BaseTest {
* @throws Exception if there is a problem
*/
@Before
@Override
public void setUp() throws Exception {
super.setUp();
analyzer = new PythonPackageAnalyzer();
analyzer.setFilesMatched(true);
analyzer.initialize();
analyzer.initializeSettings(getSettings());
analyzer.initialize(null);
}
/**
@@ -60,9 +63,10 @@ public class PythonPackageAnalyzerTest extends BaseTest {
* @throws Exception if there is a problem
*/
@After
@Override
public void tearDown() throws Exception {
analyzer.close();
analyzer = null;
super.tearDown();
}
/**

View File

@@ -54,7 +54,7 @@ import org.owasp.dependencycheck.exception.InitializationException;
* @author Dale Visser
*/
public class RubyBundleAuditAnalyzerTest extends BaseDBTestCase {
private static final Logger LOGGER = LoggerFactory.getLogger(RubyBundleAuditAnalyzerTest.class);
/**
@@ -68,11 +68,14 @@ public class RubyBundleAuditAnalyzerTest extends BaseDBTestCase {
* @throws Exception thrown if there is a problem
*/
@Before
@Override
public void setUp() throws Exception {
Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false);
Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false);
Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false);
super.setUp();
getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false);
analyzer = new RubyBundleAuditAnalyzer();
analyzer.initializeSettings(getSettings());
analyzer.setFilesMatched(true);
}
@@ -82,11 +85,13 @@ public class RubyBundleAuditAnalyzerTest extends BaseDBTestCase {
* @throws Exception thrown if there is a problem
*/
@After
@Override
public void tearDown() throws Exception {
if (analyzer != null) {
analyzer.close();
analyzer = null;
}
super.tearDown();
}
/**
@@ -113,14 +118,14 @@ public class RubyBundleAuditAnalyzerTest extends BaseDBTestCase {
@Test
public void testAnalysis() throws AnalysisException, DatabaseException {
try {
analyzer.initialize();
analyzer.initialize(null);
final String resource = "ruby/vulnerable/gems/rails-4.1.15/Gemfile.lock";
final Dependency result = new Dependency(BaseTest.getResourceAsFile(this, resource));
final Engine engine = new Engine();
final Engine engine = new Engine(getSettings());
analyzer.analyze(result, engine);
int size = engine.getDependencies().size();
assertTrue(size >= 1);
Dependency dependency = engine.getDependencies().get(0);
assertTrue(dependency.getProductEvidence().toString().toLowerCase().contains("redcarpet"));
assertTrue(dependency.getVersionEvidence().toString().toLowerCase().contains("2.2.2"));
@@ -138,17 +143,17 @@ public class RubyBundleAuditAnalyzerTest extends BaseDBTestCase {
@Test
public void testAddCriticalityToVulnerability() throws AnalysisException, DatabaseException {
try {
analyzer.initialize();
analyzer.initialize(null);
final Dependency result = new Dependency(BaseTest.getResourceAsFile(this,
"ruby/vulnerable/gems/sinatra/Gemfile.lock"));
final Engine engine = new Engine();
final Engine engine = new Engine(getSettings());
analyzer.analyze(result, engine);
Dependency dependency = engine.getDependencies().get(0);
Vulnerability vulnerability = dependency.getVulnerabilities().first();
assertEquals(vulnerability.getCvssScore(), 5.0f, 0.0);
} catch (InitializationException | DatabaseException | AnalysisException e) {
LOGGER.warn("Exception setting up RubyBundleAuditAnalyzer. Make sure Ruby gem bundle-audit is installed. You may also need to set property \"analyzer.bundle.audit.path\".");
Assume.assumeNoException("Exception setting up RubyBundleAuditAnalyzer; bundle audit may not be installed, or property \"analyzer.bundle.audit.path\" may not be set.", e);
@@ -163,10 +168,11 @@ public class RubyBundleAuditAnalyzerTest extends BaseDBTestCase {
@Test
public void testMissingBundleAudit() throws AnalysisException, DatabaseException {
//set a non-exist bundle-audit
Settings.setString(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH, "phantom-bundle-audit");
getSettings().setString(Settings.KEYS.ANALYZER_BUNDLE_AUDIT_PATH, "phantom-bundle-audit");
analyzer.initializeSettings(getSettings());
try {
//initialize should fail.
analyzer.initialize();
analyzer.initialize(null);
} catch (Exception e) {
//expected, so ignore.
assertNotNull(e);
@@ -184,7 +190,7 @@ public class RubyBundleAuditAnalyzerTest extends BaseDBTestCase {
*/
@Test
public void testDependenciesPath() throws AnalysisException, DatabaseException {
final Engine engine = new Engine();
final Engine engine = new Engine(getSettings());
engine.scan(BaseTest.getResourceAsFile(this,
"ruby/vulnerable/gems/rails-4.1.15/"));
try {
@@ -202,14 +208,14 @@ public class RubyBundleAuditAnalyzerTest extends BaseDBTestCase {
while (dIterator.hasNext()) {
Dependency dept = dIterator.next();
LOGGER.info("dept path: {}", dept.getActualFilePath());
Set<Identifier> identifiers = dept.getIdentifiers();
Iterator<Identifier> idIterator = identifiers.iterator();
while (idIterator.hasNext()) {
Identifier id = idIterator.next();
LOGGER.info(" Identifier: {}, type={}, url={}, conf={}", id.getValue(), id.getType(), id.getUrl(), id.getConfidence());
}
Set<Evidence> prodEv = dept.getProductEvidence().getEvidence();
Iterator<Evidence> it = prodEv.iterator();
while (it.hasNext()) {
@@ -222,7 +228,7 @@ public class RubyBundleAuditAnalyzerTest extends BaseDBTestCase {
Evidence e = vIt.next();
LOGGER.info(" version: name={}, value={}, source={}, confidence={}", e.getName(), e.getValue(), e.getSource(), e.getConfidence());
}
Set<Evidence> vendorEv = dept.getVendorEvidence().getEvidence();
Iterator<Evidence> vendorIt = vendorEv.iterator();
while (vendorIt.hasNext()) {

View File

@@ -48,10 +48,13 @@ public class RubyBundlerAnalyzerTest extends BaseTest {
* @throws Exception thrown if there is a problem
*/
@Before
@Override
public void setUp() throws Exception {
super.setUp();
analyzer = new RubyBundlerAnalyzer();
analyzer.initializeSettings(getSettings());
analyzer.setFilesMatched(true);
analyzer.initialize();
analyzer.initialize(null);
}
/**
@@ -60,9 +63,10 @@ public class RubyBundlerAnalyzerTest extends BaseTest {
* @throws Exception thrown if there is a problem
*/
@After
@Override
public void tearDown() throws Exception {
analyzer.close();
analyzer = null;
super.tearDown();
}
/**

View File

@@ -48,10 +48,13 @@ public class RubyGemspecAnalyzerTest extends BaseTest {
* @throws Exception thrown if there is a problem
*/
@Before
@Override
public void setUp() throws Exception {
super.setUp();
analyzer = new RubyGemspecAnalyzer();
analyzer.initializeSettings(getSettings());
analyzer.setFilesMatched(true);
analyzer.initialize();
analyzer.initialize(null);
}
/**
@@ -60,9 +63,10 @@ public class RubyGemspecAnalyzerTest extends BaseTest {
* @throws Exception thrown if there is a problem
*/
@After
@Override
public void tearDown() throws Exception {
analyzer.close();
analyzer = null;
super.tearDown();
}
/**

View File

@@ -32,14 +32,18 @@ public class SwiftAnalyzersTest extends BaseTest {
* @throws Exception thrown if there is a problem
*/
@Before
@Override
public void setUp() throws Exception {
super.setUp();
podsAnalyzer = new CocoaPodsAnalyzer();
podsAnalyzer.initializeSettings(getSettings());
podsAnalyzer.setFilesMatched(true);
podsAnalyzer.initialize();
podsAnalyzer.initialize(null);
spmAnalyzer = new SwiftPackageManagerAnalyzer();
spmAnalyzer.initializeSettings(getSettings());
spmAnalyzer.setFilesMatched(true);
spmAnalyzer.initialize();
spmAnalyzer.initialize(null);
}
/**
@@ -48,12 +52,15 @@ public class SwiftAnalyzersTest extends BaseTest {
* @throws Exception thrown if there is a problem
*/
@After
@Override
public void tearDown() throws Exception {
podsAnalyzer.close();
podsAnalyzer = null;
spmAnalyzer.close();
spmAnalyzer = null;
super.tearDown();
}
/**

View File

@@ -48,6 +48,7 @@ public class VersionFilterAnalyzerTest extends BaseTest {
@Test
public void testGetAnalysisPhase() {
VersionFilterAnalyzer instance = new VersionFilterAnalyzer();
instance.initializeSettings(getSettings());
AnalysisPhase expResult = AnalysisPhase.POST_INFORMATION_COLLECTION;
AnalysisPhase result = instance.getAnalysisPhase();
assertEquals(expResult, result);
@@ -60,6 +61,7 @@ public class VersionFilterAnalyzerTest extends BaseTest {
@Test
public void testGetAnalyzerEnabledSettingKey() {
VersionFilterAnalyzer instance = new VersionFilterAnalyzer();
instance.initializeSettings(getSettings());
String expResult = Settings.KEYS.ANALYZER_VERSION_FILTER_ENABLED;
String result = instance.getAnalyzerEnabledSettingKey();
assertEquals(expResult, result);
@@ -78,6 +80,7 @@ public class VersionFilterAnalyzerTest extends BaseTest {
versions.addEvidence("other", "Implementation-Version", "1.2.3", Confidence.HIGHEST);
VersionFilterAnalyzer instance = new VersionFilterAnalyzer();
instance.initializeSettings(getSettings());
instance.analyzeDependency(dependency, null);
assertEquals(3, versions.size());
@@ -119,6 +122,7 @@ public class VersionFilterAnalyzerTest extends BaseTest {
versions.addEvidence("other", "Implementation-Version", "1.2.3", Confidence.HIGHEST);
VersionFilterAnalyzer instance = new VersionFilterAnalyzer();
instance.initializeSettings(getSettings());
instance.analyzeDependency(dependency, null);
assertEquals(3, versions.size());
@@ -156,6 +160,7 @@ public class VersionFilterAnalyzerTest extends BaseTest {
versions.addEvidence("other", "Implementation-Version", "1.2.3", Confidence.HIGHEST);
VersionFilterAnalyzer instance = new VersionFilterAnalyzer();
instance.initializeSettings(getSettings());
instance.analyzeDependency(dependency, null);
assertEquals(3, versions.size());
@@ -183,6 +188,7 @@ public class VersionFilterAnalyzerTest extends BaseTest {
versions.addEvidence("other", "Implementation-Version", "1.2.3", Confidence.HIGHEST);
VersionFilterAnalyzer instance = new VersionFilterAnalyzer();
instance.initializeSettings(getSettings());
instance.analyzeDependency(dependency, null);
assertEquals(3, versions.size());
@@ -206,5 +212,4 @@ public class VersionFilterAnalyzerTest extends BaseTest {
instance.analyzeDependency(dependency, null);
assertEquals(4, versions.size());
}
}

View File

@@ -42,17 +42,20 @@ public class VulnerabilitySuppressionAnalyzerIT extends BaseDBTestCase {
@Test
public void testGetName() {
VulnerabilitySuppressionAnalyzer instance = new VulnerabilitySuppressionAnalyzer();
instance.initializeSettings(getSettings());
String expResult = "Vulnerability Suppression Analyzer";
String result = instance.getName();
assertEquals(expResult, result);
}
/**
* Test of getAnalysisPhase method, of class VulnerabilitySuppressionAnalyzer.
* Test of getAnalysisPhase method, of class
* VulnerabilitySuppressionAnalyzer.
*/
@Test
public void testGetAnalysisPhase() {
VulnerabilitySuppressionAnalyzer instance = new VulnerabilitySuppressionAnalyzer();
instance.initializeSettings(getSettings());
AnalysisPhase expResult = AnalysisPhase.POST_FINDING_ANALYSIS;
AnalysisPhase result = instance.getAnalysisPhase();
assertEquals(expResult, result);
@@ -68,10 +71,10 @@ public class VulnerabilitySuppressionAnalyzerIT extends BaseDBTestCase {
File file = BaseTest.getResourceAsFile(this, "commons-fileupload-1.2.1.jar");
//File suppression = new File(this.getClass().getClassLoader().getResource("commons-fileupload-1.2.1.suppression.xml").getPath());
File suppression = BaseTest.getResourceAsFile(this, "commons-fileupload-1.2.1.suppression.xml");
Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false);
Settings.setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false);
Settings.setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false);
Engine engine = new Engine();
getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED, false);
getSettings().setBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED, false);
Engine engine = new Engine(getSettings());
engine.scan(file);
engine.analyzeDependencies();
Dependency dependency = getDependency(engine, file);
@@ -79,9 +82,10 @@ public class VulnerabilitySuppressionAnalyzerIT extends BaseDBTestCase {
int cpeSize = dependency.getIdentifiers().size();
assertTrue(cveSize > 0);
assertTrue(cpeSize > 0);
Settings.setString(Settings.KEYS.SUPPRESSION_FILE, suppression.getAbsolutePath());
getSettings().setString(Settings.KEYS.SUPPRESSION_FILE, suppression.getAbsolutePath());
VulnerabilitySuppressionAnalyzer instance = new VulnerabilitySuppressionAnalyzer();
instance.initialize();
instance.initializeSettings(getSettings());
instance.initialize(engine);
instance.analyze(dependency, engine);
cveSize = cveSize > 1 ? cveSize - 2 : 0;
cpeSize = cpeSize > 0 ? cpeSize - 1 : 0;

View File

@@ -22,10 +22,10 @@ public class CentralSearchTest extends BaseTest {
private CentralSearch searcher;
@Before
@Override
public void setUp() throws Exception {
String centralUrl = Settings.getString(Settings.KEYS.ANALYZER_CENTRAL_URL);
LOGGER.debug(centralUrl);
searcher = new CentralSearch(new URL(centralUrl));
super.setUp();
searcher = new CentralSearch(getSettings());
}
@Test(expected = IllegalArgumentException.class)

View File

@@ -35,7 +35,9 @@ public class ComposerLockParserTest extends BaseTest {
private InputStream inputStream;
@Before
public void setUp() {
@Override
public void setUp() throws Exception {
super.setUp();
inputStream = this.getClass().getClassLoader().getResourceAsStream("composer.lock");
}

View File

@@ -18,7 +18,6 @@
package org.owasp.dependencycheck.data.nexus;
import java.io.FileNotFoundException;
import java.net.URL;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Assume;
@@ -26,7 +25,6 @@ import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.owasp.dependencycheck.BaseTest;
import org.owasp.dependencycheck.analyzer.NexusAnalyzer;
import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -37,10 +35,12 @@ public class NexusSearchTest extends BaseTest {
private NexusSearch searcher;
@Before
@Override
public void setUp() throws Exception {
String nexusUrl = Settings.getString(Settings.KEYS.ANALYZER_NEXUS_URL);
super.setUp();
String nexusUrl = getSettings().getString(Settings.KEYS.ANALYZER_NEXUS_URL);
LOGGER.debug(nexusUrl);
searcher = new NexusSearch(new URL(nexusUrl), NexusAnalyzer.useProxy());
searcher = new NexusSearch(getSettings(), false);
Assume.assumeTrue(searcher.preflightRequest());
}
@@ -78,5 +78,3 @@ public class NexusSearchTest extends BaseTest {
searcher.searchSha1("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
}
}
// vim: cc=120:sw=4:ts=4:sts=4

View File

@@ -22,7 +22,6 @@ import org.junit.Before;
import org.junit.Test;
import org.owasp.dependencycheck.BaseTest;
import org.owasp.dependencycheck.analyzer.exception.AnalysisException;
import org.owasp.dependencycheck.utils.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.json.Json;
@@ -30,7 +29,6 @@ import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonReader;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import static org.junit.Assume.assumeFalse;
import org.owasp.dependencycheck.utils.URLConnectionFailureException;
@@ -41,10 +39,10 @@ public class NspSearchTest extends BaseTest {
private NspSearch searcher;
@Before
@Override
public void setUp() throws Exception {
String url = Settings.getString(Settings.KEYS.ANALYZER_NSP_URL);
LOGGER.debug(url);
searcher = new NspSearch(new URL(url));
super.setUp();
searcher = new NspSearch(getSettings());
}
@Test

View File

@@ -61,5 +61,4 @@ public class SanitizePackageTest {
Assert.assertFalse(sanitized.containsKey("license"));
Assert.assertFalse(sanitized.containsKey("main"));
}
}

View File

@@ -35,10 +35,11 @@ public class ConnectionFactoryTest extends BaseDBTestCase {
*/
@Test
public void testInitialize() throws DatabaseException, SQLException {
ConnectionFactory.initialize();
try (Connection result = ConnectionFactory.getConnection()) {
ConnectionFactory factory = new ConnectionFactory(getSettings());
factory.initialize();
try (Connection result = factory.getConnection()) {
assertNotNull(result);
}
ConnectionFactory.cleanup();
factory.cleanup();
}
}

View File

@@ -27,51 +27,47 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.junit.After;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Before;
/**
*
* @author Jeremy Long
*/
public class CveDBIT extends BaseDBTestCase {
CveDB instance = null;
@Before
@Override
public void setUp() throws Exception {
super.setUp();
instance = new CveDB(getSettings());
}
@After
@Override
public void tearDown() throws Exception {
instance.close();
super.tearDown();
}
/**
* Pretty useless tests of open, commit, and close methods, of class CveDB.
*/
@Test
public void testOpen() {
CveDB instance = null;
try {
instance = CveDB.getInstance();
instance.commit();
} catch (DatabaseException | SQLException ex) {
fail(ex.getMessage());
} finally {
int start = instance.getUsageCount();
instance.close();
int end = instance.getUsageCount();
assertTrue( end < start);
}
}
@@ -80,12 +76,10 @@ public class CveDBIT extends BaseDBTestCase {
*/
@Test
public void testGetCPEs() throws Exception {
CveDB instance = CveDB.getInstance();
String vendor = "apache";
String product = "struts";
Set<VulnerableSoftware> result = instance.getCPEs(vendor, product);
assertTrue(result.size() > 5);
instance.close();
}
/**
@@ -93,10 +87,8 @@ public class CveDBIT extends BaseDBTestCase {
*/
@Test
public void testgetVulnerability() throws Exception {
CveDB instance = CveDB.getInstance();
Vulnerability result = instance.getVulnerability("CVE-2014-0094");
assertEquals("The ParametersInterceptor in Apache Struts before 2.3.16.1 allows remote attackers to \"manipulate\" the ClassLoader via the class parameter, which is passed to the getClass method.", result.getDescription());
instance.close();
}
/**
@@ -105,7 +97,6 @@ public class CveDBIT extends BaseDBTestCase {
@Test
public void testGetVulnerabilities() throws Exception {
String cpeStr = "cpe:/a:apache:struts:2.1.2";
CveDB instance = CveDB.getInstance();
List<Vulnerability> results;
results = instance.getVulnerabilities(cpeStr);
@@ -133,7 +124,6 @@ public class CveDBIT extends BaseDBTestCase {
}
}
assertTrue("Expected " + expected + ", but was not identified", found);
instance.close();
}
/**
@@ -141,7 +131,6 @@ public class CveDBIT extends BaseDBTestCase {
*/
@Test
public void testGetMatchingSoftware() throws Exception {
CveDB instance = CveDB.getInstance();
Map<String, Boolean> versions = new HashMap<>();
DependencyVersion identifiedVersion = new DependencyVersion("1.0.1o");
versions.put("cpe:/a:openssl:openssl:1.0.1e", Boolean.FALSE);
@@ -189,6 +178,5 @@ public class CveDBIT extends BaseDBTestCase {
identifiedVersion = new DependencyVersion("1.6.3");
results = instance.getMatchingSoftware(versions, "springsource", "spring_framework", identifiedVersion);
assertNotNull(results);
instance.close();
}
}

View File

@@ -17,8 +17,10 @@
*/
package org.owasp.dependencycheck.data.nvdcve;
import java.sql.SQLException;
import java.util.List;
import java.util.Set;
import org.junit.After;
import org.junit.Test;
import org.owasp.dependencycheck.BaseTest;
@@ -26,6 +28,7 @@ import org.owasp.dependencycheck.dependency.Vulnerability;
import org.owasp.dependencycheck.dependency.VulnerableSoftware;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Before;
/**
*
@@ -33,22 +36,32 @@ import static org.junit.Assert.fail;
*/
public class CveDBMySqlIT extends BaseTest {
CveDB instance = null;
@Before
@Override
public void setUp() throws Exception {
super.setUp();
instance = new CveDB(getSettings());
}
@After
@Override
public void tearDown() throws Exception {
instance.close();
super.tearDown();
}
/**
* Pretty useless tests of open, commit, and close methods, of class CveDB.
*/
@Test
public void testOpen() {
CveDB instance = null;
try {
instance = CveDB.getInstance();
} catch (DatabaseException ex) {
instance.commit();
} catch (SQLException | DatabaseException ex) {
System.out.println("Unable to connect to the My SQL database; verify that the db server is running and that the schema has been generated");
fail(ex.getMessage());
} finally {
int start = instance.getUsageCount();
instance.close();
int end = instance.getUsageCount();
assertTrue( end < start);
}
}
@@ -57,7 +70,6 @@ public class CveDBMySqlIT extends BaseTest {
*/
@Test
public void testGetCPEs() throws Exception {
CveDB instance = CveDB.getInstance();
try {
String vendor = "apache";
String product = "struts";
@@ -66,8 +78,6 @@ public class CveDBMySqlIT extends BaseTest {
} catch (Exception ex) {
System.out.println("Unable to access the My SQL database; verify that the db server is running and that the schema has been generated");
throw ex;
} finally {
instance.close();
}
}
@@ -77,15 +87,12 @@ public class CveDBMySqlIT extends BaseTest {
@Test
public void testGetVulnerabilities() throws Exception {
String cpeStr = "cpe:/a:apache:struts:2.1.2";
CveDB instance = CveDB.getInstance();
try {
List<Vulnerability> result = instance.getVulnerabilities(cpeStr);
assertTrue(result.size() > 5);
} catch (Exception ex) {
System.out.println("Unable to access the My SQL database; verify that the db server is running and that the schema has been generated");
throw ex;
} finally {
instance.close();
}
}
}

View File

@@ -19,14 +19,13 @@ package org.owasp.dependencycheck.data.nvdcve;
import org.owasp.dependencycheck.BaseDBTestCase;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.Test;
import org.owasp.dependencycheck.data.update.nvd.NvdCveInfo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
/**
*
@@ -34,17 +33,31 @@ import static org.junit.Assert.assertTrue;
*/
public class DatabasePropertiesIT extends BaseDBTestCase {
CveDB cveDb = null;
@Before
@Override
public void setUp() throws Exception {
super.setUp();
cveDb = new CveDB(getSettings());
}
@After
@Override
public void tearDown() throws Exception {
cveDb.close();
super.tearDown();
}
/**
* Test of isEmpty method, of class DatabaseProperties.
*/
@Test
public void testIsEmpty() throws Exception {
CveDB cveDB = CveDB.getInstance();
DatabaseProperties instance = cveDB.getDatabaseProperties();
assertNotNull(instance);
DatabaseProperties prop = cveDb.getDatabaseProperties();
assertNotNull(prop);
//no exception means the call worked... whether or not it is empty depends on if the db is new
//assertEquals(expResult, result);
cveDB.close();
}
/**
@@ -57,13 +70,11 @@ public class DatabasePropertiesIT extends BaseDBTestCase {
long expected = 1337;
updatedValue.setId(key);
updatedValue.setTimestamp(expected);
CveDB cveDB = CveDB.getInstance();
DatabaseProperties instance = cveDB.getDatabaseProperties();
DatabaseProperties instance = cveDb.getDatabaseProperties();
instance.save(updatedValue);
instance = cveDB.reloadProperties();
instance = cveDb.reloadProperties();
long results = Long.parseLong(instance.getProperty("NVD CVE " + key));
assertEquals(expected, results);
cveDB.close();
}
/**
@@ -73,12 +84,10 @@ public class DatabasePropertiesIT extends BaseDBTestCase {
public void testGetProperty_String_String() throws Exception {
String key = "doesn't exist";
String defaultValue = "default";
CveDB cveDB = CveDB.getInstance();
DatabaseProperties instance = cveDB.getDatabaseProperties();
DatabaseProperties instance = cveDb.getDatabaseProperties();
String expResult = "default";
String result = instance.getProperty(key, defaultValue);
assertEquals(expResult, result);
cveDB.close();
}
/**
@@ -87,13 +96,11 @@ public class DatabasePropertiesIT extends BaseDBTestCase {
@Test
public void testGetProperty_String() throws DatabaseException {
String key = "version";
CveDB cveDB = CveDB.getInstance();
DatabaseProperties instance = cveDB.getDatabaseProperties();
DatabaseProperties instance = cveDb.getDatabaseProperties();
String result = instance.getProperty(key);
double version = Double.parseDouble(result);
assertTrue(version >= 2.8);
assertTrue(version <= 10);
cveDB.close();
}
/**
@@ -101,10 +108,9 @@ public class DatabasePropertiesIT extends BaseDBTestCase {
*/
@Test
public void testGetProperties() throws DatabaseException {
CveDB cveDB = CveDB.getInstance();
DatabaseProperties instance = cveDB.getDatabaseProperties();
DatabaseProperties instance = cveDb.getDatabaseProperties();
Properties result = instance.getProperties();
assertTrue(result.size() > 0);
cveDB.close();
cveDb.close();
}
}

View File

@@ -66,31 +66,31 @@ public class EngineVersionCheckTest extends BaseTest {
public void testShouldUpdate() throws Exception {
DatabaseProperties properties = new MockUp<DatabaseProperties>() {
final private Properties properties = new Properties();
@Mock
public void save(String key, String value) throws UpdateException {
properties.setProperty(key, value);
}
@Mock
public String getProperty(String key) {
return properties.getProperty(key);
}
}.getMockInstance();
String updateToVersion = "1.2.6";
String currentVersion = "1.2.6";
long lastChecked = dateToMilliseconds("2014-12-01");
long now = dateToMilliseconds("2014-12-01");
EngineVersionCheck instance = new EngineVersionCheck();
EngineVersionCheck instance = new EngineVersionCheck(getSettings());
boolean expResult = false;
instance.setUpdateToVersion(updateToVersion);
boolean result = instance.shouldUpdate(lastChecked, now, properties, currentVersion);
assertEquals(expResult, result);
updateToVersion = "1.2.5";
currentVersion = "1.2.5";
lastChecked = dateToMilliseconds("2014-10-01");
@@ -109,7 +109,7 @@ public class EngineVersionCheckTest extends BaseTest {
instance.setUpdateToVersion(updateToVersion);
result = instance.shouldUpdate(lastChecked, now, properties, currentVersion);
assertEquals(expResult, result);
updateToVersion = "1.2.6";
currentVersion = "1.2.5";
lastChecked = dateToMilliseconds("2014-12-01");
@@ -118,7 +118,7 @@ public class EngineVersionCheckTest extends BaseTest {
instance.setUpdateToVersion(updateToVersion);
result = instance.shouldUpdate(lastChecked, now, properties, currentVersion);
assertEquals(expResult, result);
updateToVersion = "1.2.5";
currentVersion = "1.2.6";
lastChecked = dateToMilliseconds("2014-12-01");
@@ -127,7 +127,7 @@ public class EngineVersionCheckTest extends BaseTest {
instance.setUpdateToVersion(updateToVersion);
result = instance.shouldUpdate(lastChecked, now, properties, currentVersion);
assertEquals(expResult, result);
updateToVersion = "";
currentVersion = "1.2.5";
lastChecked = dateToMilliseconds("2014-12-01");
@@ -136,7 +136,7 @@ public class EngineVersionCheckTest extends BaseTest {
instance.setUpdateToVersion(updateToVersion);
result = instance.shouldUpdate(lastChecked, now, properties, currentVersion);
assertEquals(expResult, result);
updateToVersion = "";
currentVersion = "1.2.5";
lastChecked = dateToMilliseconds("2014-12-01");
@@ -152,7 +152,7 @@ public class EngineVersionCheckTest extends BaseTest {
*/
@Test
public void testGetCurrentReleaseVersion() {
EngineVersionCheck instance = new EngineVersionCheck();
EngineVersionCheck instance = new EngineVersionCheck(getSettings());
DependencyVersion minExpResult = new DependencyVersion("1.2.6");
String release = instance.getCurrentReleaseVersion();
DependencyVersion result = new DependencyVersion(release);

View File

@@ -17,14 +17,13 @@
*/
package org.owasp.dependencycheck.data.update;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import org.junit.Test;
import org.owasp.dependencycheck.BaseDBTestCase;
import org.owasp.dependencycheck.data.update.exception.UpdateException;
import org.owasp.dependencycheck.data.update.nvd.UpdateableNvdCve;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import org.owasp.dependencycheck.Engine;
/**
*
@@ -32,31 +31,14 @@ import static org.junit.Assert.fail;
*/
public class NvdCveUpdaterIT extends BaseDBTestCase {
public NvdCveUpdater getUpdater() {
NvdCveUpdater instance = new NvdCveUpdater();
instance.initializeExecutorServices();
return instance;
}
/**
* Test of update method.
*/
@Test
public void testUpdate() {
try {
NvdCveUpdater instance = getUpdater();
instance.update();
} catch (UpdateException ex) {
fail(ex.getMessage());
}
}
/**
* Test of updatesNeeded method.
*/
@Test
public void testUpdatesNeeded() throws Exception {
NvdCveUpdater instance = getUpdater();
NvdCveUpdater instance = new NvdCveUpdater();
instance.setSettings(getSettings());
instance.initializeExecutorServices();
UpdateableNvdCve result = instance.getUpdatesNeeded();
assertNotNull(result);
}

View File

@@ -44,11 +44,11 @@ public class DownloadTaskTest extends BaseTest {
NvdCveInfo cve = new NvdCveInfo();
cve.setId("modified");
cve.setNeedsUpdate(true);
cve.setUrl(Settings.getString(Settings.KEYS.CVE_MODIFIED_20_URL));
cve.setOldSchemaVersionUrl(Settings.getString(Settings.KEYS.CVE_MODIFIED_12_URL));
cve.setUrl(getSettings().getString(Settings.KEYS.CVE_MODIFIED_20_URL));
cve.setOldSchemaVersionUrl(getSettings().getString(Settings.KEYS.CVE_MODIFIED_12_URL));
ExecutorService processExecutor = null;
CveDB cveDB = null;
DownloadTask instance = new DownloadTask(cve, processExecutor, cveDB, Settings.getInstance());
DownloadTask instance = new DownloadTask(cve, processExecutor, cveDB, getSettings());
Future<ProcessTask> result = instance.call();
assertNull(result);
}
@@ -62,6 +62,5 @@ public class DownloadTaskTest extends BaseTest {
assertTrue(DownloadTask.isXml(f));
f = getResourceAsFile(this, "file.tar.gz");
assertFalse(DownloadTask.isXml(f));
}
}

View File

@@ -58,7 +58,7 @@ public class ReportGeneratorIT extends BaseDBTestCase {
File writeTo = new File("target/test-reports/Report.xml");
File suppressionFile = BaseTest.getResourceAsFile(this, "incorrectSuppressions.xml");
Settings.setString(Settings.KEYS.SUPPRESSION_FILE, suppressionFile.getAbsolutePath());
getSettings().setString(Settings.KEYS.SUPPRESSION_FILE, suppressionFile.getAbsolutePath());
//File struts = new File(this.getClass().getClassLoader().getResource("struts2-core-2.1.2.jar").getPath());
File struts = BaseTest.getResourceAsFile(this, "struts2-core-2.1.2.jar");
@@ -67,8 +67,8 @@ public class ReportGeneratorIT extends BaseDBTestCase {
//File jetty = new File(this.getClass().getClassLoader().getResource("org.mortbay.jetty.jar").getPath());
File jetty = BaseTest.getResourceAsFile(this, "org.mortbay.jetty.jar");
Settings.setBoolean(Settings.KEYS.AUTO_UPDATE, false);
Engine engine = new Engine();
getSettings().setBoolean(Settings.KEYS.AUTO_UPDATE, false);
Engine engine = new Engine(getSettings());
engine.scan(struts);
engine.scan(axis);