Skip to content

Commit 3a9a9b0

Browse files
authored
Added unit tests for PatchFile ARU parsing operations (#151)
* restructured patch download call to enable testing * added WDT enum tests
1 parent 491028f commit 3a9a9b0

File tree

10 files changed

+431
-78
lines changed

10 files changed

+431
-78
lines changed

imagetool/src/main/java/com/oracle/weblogic/imagetool/api/model/CachedFile.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,10 @@
1515
import com.oracle.weblogic.imagetool.installer.InstallerType;
1616
import com.oracle.weblogic.imagetool.logging.LoggingFacade;
1717
import com.oracle.weblogic.imagetool.logging.LoggingFactory;
18+
import com.oracle.weblogic.imagetool.util.HttpUtil;
1819
import com.oracle.weblogic.imagetool.util.Utils;
20+
import org.apache.http.client.fluent.Executor;
21+
import org.apache.http.client.fluent.Request;
1922

2023
/**
2124
* Base class to represent either an installer or a patch file.
@@ -114,4 +117,31 @@ public Path copyFile(CacheStore cacheStore, String buildContextDir) throws IOExc
114117
logger.exiting(result);
115118
return result;
116119
}
120+
121+
122+
/**
123+
* Download a file from the url.
124+
*
125+
* @param url url of the aru server
126+
* @param fileName full path to save the file
127+
* @param username userid for support account
128+
* @param password password for support account
129+
* @throws IOException when it fails to access the url
130+
*/
131+
132+
public void downloadFile(String url, String fileName, String username, String password)
133+
throws IOException {
134+
logger.entering(url);
135+
try {
136+
Executor.newInstance(HttpUtil.getOraClient(username, password))
137+
.execute(Request.Get(url).connectTimeout(30000).socketTimeout(30000))
138+
.saveContent(new File(fileName));
139+
} catch (Exception ex) {
140+
String message = String.format("Failed to download and save file %s from %s: %s", fileName, url,
141+
ex.getLocalizedMessage());
142+
logger.severe(message);
143+
throw new IOException(message, ex);
144+
}
145+
logger.exiting(fileName);
146+
}
117147
}

imagetool/src/main/java/com/oracle/weblogic/imagetool/cachestore/PatchFile.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -251,7 +251,7 @@ private String downloadPatch(CacheStore cacheStore) throws IOException {
251251
String filename = cacheStore.getCacheDir() + File.separator
252252
+ downLoadLink.substring(index + "patch_file=".length());
253253
logger.info("IMG-0018", getBugNumber());
254-
HttpUtil.downloadFile(downLoadHost + downLoadLink, filename, userId, password);
254+
downloadFile(downLoadHost + downLoadLink, filename, userId, password);
255255

256256
// after downloading the file, update the cache metadata
257257
String patchKey = getKey();

imagetool/src/main/java/com/oracle/weblogic/imagetool/util/Constants.java

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@
55

66
public final class Constants {
77

8-
static final String WDT_TAGS_URL = "https://api.github.com/repos/oracle/weblogic-deploy-tooling/tags";
9-
public static final String WDT_URL_FORMAT = "https://github.com/oracle/weblogic-deploy-tooling/releases/download/%s/weblogic-deploy.zip";
108
static final String REL_URL = "https://updates.oracle.com/Orion/Services/metadata?table=aru_releases";
119
static final String LATEST_PSU_URL =
1210
"https://updates.oracle.com/Orion/Services/search?product=%s&release=%s";

imagetool/src/main/java/com/oracle/weblogic/imagetool/util/HttpUtil.java

Lines changed: 18 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,13 @@
33

44
package com.oracle.weblogic.imagetool.util;
55

6-
import java.io.File;
76
import java.io.IOException;
87
import java.io.InterruptedIOException;
98
import java.io.StringReader;
109
import java.net.UnknownHostException;
11-
import java.util.ArrayList;
12-
import java.util.List;
10+
import java.nio.file.Files;
11+
import java.nio.file.Paths;
12+
import java.util.Collections;
1313
import javax.net.ssl.SSLException;
1414
import javax.xml.XMLConstants;
1515
import javax.xml.parsers.DocumentBuilder;
@@ -39,7 +39,6 @@
3939
import org.apache.http.impl.client.CloseableHttpClient;
4040
import org.apache.http.impl.client.HttpClientBuilder;
4141
import org.apache.http.impl.cookie.BasicClientCookie;
42-
import org.json.JSONArray;
4342
import org.w3c.dom.Document;
4443
import org.xml.sax.InputSource;
4544
import org.xml.sax.SAXException;
@@ -48,7 +47,13 @@ public class HttpUtil {
4847

4948
private static final LoggingFacade logger = LoggingFactory.getLogger(HttpUtil.class);
5049

51-
private static Document parseXmlString(String xmlString) throws ClientProtocolException {
50+
/**
51+
* Parse a string into an XML Document.
52+
* @param xmlString well formatted XML
53+
* @return org.w3c.dom.Document built from the provided String
54+
* @throws ClientProtocolException if the String contains malformed XML
55+
*/
56+
public static Document parseXmlString(String xmlString) throws ClientProtocolException {
5257
logger.entering();
5358

5459
try {
@@ -94,11 +99,18 @@ public static Document getXMLContent(String url, String username, String passwor
9499
String xmlString = Executor.newInstance(getOraClient(username, password))
95100
.execute(Request.Get(url).connectTimeout(30000).socketTimeout(30000))
96101
.returnContent().asString();
102+
Files.write(Paths.get("/tmp/test1"), Collections.singleton(xmlString));
97103
logger.exiting();
98104
return parseXmlString(xmlString);
99105
}
100106

101-
private static HttpClient getOraClient(String userId, String password) {
107+
/**
108+
* Create an HTTP client with cookie and credentials for Oracle eDelivery.
109+
* @param userId Oracle credential
110+
* @param password Oracle credential
111+
* @return new HTTP Client ready to access eDelivery
112+
*/
113+
public static HttpClient getOraClient(String userId, String password) {
102114
logger.entering(userId);
103115
RequestConfig.Builder config = RequestConfig.custom();
104116
config.setCircularRedirectsAllowed(true);
@@ -160,32 +172,6 @@ private static HttpRequestRetryHandler retryHandler() {
160172
};
161173
}
162174

163-
/**
164-
* Download a file from the url.
165-
*
166-
* @param url url of the aru server
167-
* @param fileName full path to save the file
168-
* @param username userid for support account
169-
* @param password password for support account
170-
* @throws IOException when it fails to access the url
171-
*/
172-
173-
public static void downloadFile(String url, String fileName, String username, String password)
174-
throws IOException {
175-
logger.entering(url);
176-
try {
177-
Executor.newInstance(getOraClient(username, password))
178-
.execute(Request.Get(url).connectTimeout(30000).socketTimeout(30000))
179-
.saveContent(new File(fileName));
180-
} catch (Exception ex) {
181-
String message = String.format("Failed to download and save file %s from %s: %s", fileName, url,
182-
ex.getLocalizedMessage());
183-
logger.severe(message);
184-
throw new IOException(message, ex);
185-
}
186-
logger.exiting(fileName);
187-
}
188-
189175
/**
190176
* Check conflicts post method.
191177
*
@@ -232,20 +218,4 @@ public static Document postCheckConflictRequest(String url, String payload, Stri
232218
return parseXmlString(xmlString);
233219

234220
}
235-
236-
/**
237-
* Looks at the GitHub repo and retrieves the tags from the source code.
238-
* @return a list of tags found.
239-
* @throws IOException if the HTTP client fails.
240-
*/
241-
public static List<String> getWDTTags() throws IOException {
242-
List<String> retVal = new ArrayList<>();
243-
String results = Executor.newInstance(getOraClient(null, null)).execute(Request.Get(Constants.WDT_TAGS_URL))
244-
.returnContent().asString();
245-
JSONArray jsonArr = new JSONArray(results);
246-
for (int i = 0; i < jsonArr.length(); i++) {
247-
retVal.add(jsonArr.getJSONObject(i).getString("name"));
248-
}
249-
return retVal;
250-
}
251221
}

imagetool/src/test/java/com/oracle/weblogic/imagetool/api/model/CachedFileTest.java

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,12 +30,15 @@
3030
@Tag("unit")
3131
public class CachedFileTest {
3232

33-
private static final CacheStore cacheStore = new CacheStoreTestImpl();
34-
private static final List<String> fileContents = Arrays.asList("A", "B", "C");
35-
private static final String SOME_VERSION = "12.2.1.3.0";
33+
static Path cacheDir;
34+
static CacheStore cacheStore;
35+
static final List<String> fileContents = Arrays.asList("A", "B", "C");
36+
static final String SOME_VERSION = "12.2.1.3.0";
3637

3738
@BeforeAll
38-
static void setup(@TempDir Path tempDir) throws IOException {
39+
static void setup(@TempDir Path tempDir, @TempDir Path cacheDir) throws IOException {
40+
CachedFileTest.cacheDir = cacheDir;
41+
cacheStore = new CacheStoreTestImpl(cacheDir);
3942
// build a fake cache with two installers
4043
String key1 = "wls_" + SOME_VERSION;
4144
Path path1 = tempDir.resolve("installer.file.122130.jar");

imagetool/src/test/java/com/oracle/weblogic/imagetool/cachestore/CacheStoreTestImpl.java

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,22 @@
33

44
package com.oracle.weblogic.imagetool.cachestore;
55

6+
import java.nio.file.Path;
67
import java.util.HashMap;
78
import java.util.Map;
89

910
public class CacheStoreTestImpl implements CacheStore {
1011

11-
HashMap<String, String> cache = new HashMap<>();
12+
private HashMap<String, String> cache = new HashMap<>();
13+
private Path cacheDir;
14+
15+
public CacheStoreTestImpl(Path cacheDir) {
16+
this.cacheDir = cacheDir;
17+
}
1218

1319
@Override
1420
public String getCacheDir() {
15-
return null;
21+
return cacheDir.toString();
1622
}
1723

1824
@Override
@@ -22,12 +28,15 @@ public String getValueFromCache(String key) {
2228

2329
@Override
2430
public boolean hasMatchingKeyValue(String key, String value) {
25-
return false;
31+
if (key == null || value == null) {
32+
return false;
33+
}
34+
return value.equals(cache.get(key.toLowerCase()));
2635
}
2736

2837
@Override
2938
public boolean addToCache(String key, String value) {
30-
cache.put(key, value);
39+
cache.put(key.toLowerCase(), value);
3140
return true;
3241
}
3342

imagetool/src/test/java/com/oracle/weblogic/imagetool/cachestore/PatchFileTest.java

Lines changed: 98 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,33 +3,45 @@
33

44
package com.oracle.weblogic.imagetool.cachestore;
55

6+
import java.io.BufferedReader;
67
import java.io.FileNotFoundException;
78
import java.io.IOException;
9+
import java.io.InputStreamReader;
10+
import java.lang.reflect.Field;
811
import java.nio.file.Files;
912
import java.nio.file.Path;
1013
import java.util.Arrays;
1114
import java.util.List;
1215
import java.util.logging.Level;
16+
import java.util.stream.Collectors;
1317

1418
import com.oracle.weblogic.imagetool.logging.LoggingFacade;
1519
import com.oracle.weblogic.imagetool.logging.LoggingFactory;
20+
import com.oracle.weblogic.imagetool.util.HttpUtil;
21+
import org.junit.jupiter.api.AfterAll;
1622
import org.junit.jupiter.api.BeforeAll;
1723
import org.junit.jupiter.api.Tag;
1824
import org.junit.jupiter.api.Test;
1925
import org.junit.jupiter.api.io.TempDir;
2026

2127
import static org.junit.jupiter.api.Assertions.assertEquals;
28+
import static org.junit.jupiter.api.Assertions.assertNotNull;
29+
import static org.junit.jupiter.api.Assertions.assertNull;
2230
import static org.junit.jupiter.api.Assertions.assertThrows;
2331

2432
@Tag("unit")
2533
public class PatchFileTest {
26-
private static final CacheStore cacheStore = new CacheStoreTestImpl();
27-
private static final List<String> fileContents = Arrays.asList("A", "B", "C");
28-
private static final String BUGNUMBER = "123456";
29-
private static final String SOME_VERSION = "12.2.1.3.0";
34+
static Path cacheDir;
35+
static CacheStore cacheStore;
36+
static final List<String> fileContents = Arrays.asList("A", "B", "C");
37+
static final String BUGNUMBER = "456789";
38+
static final String SOME_VERSION = "12.2.1.3.0";
39+
static Level originalLogLevel;
3040

3141
@BeforeAll
32-
static void setup(@TempDir Path tempDir) throws IOException {
42+
static void setup(@TempDir Path tempDir, @TempDir Path cacheDir) throws IOException {
43+
PatchFileTest.cacheDir = cacheDir;
44+
cacheStore = new CacheStoreTestImpl(cacheDir);
3345
// build a fake cache with two installers
3446
String key1 = BUGNUMBER + "_" + SOME_VERSION;
3547
Path path1 = tempDir.resolve("patch1.zip");
@@ -38,6 +50,18 @@ static void setup(@TempDir Path tempDir) throws IOException {
3850
cacheStore.addToCache(key1, path1.toString());
3951
cacheStore.addToCache(key2, path2.toString());
4052
Files.write(path1, fileContents);
53+
54+
// disable console logging
55+
LoggingFacade logger = LoggingFactory.getLogger(PatchFile.class);
56+
originalLogLevel = logger.getLevel();
57+
logger.setLevel(Level.OFF);
58+
}
59+
60+
@AfterAll
61+
static void teardown() {
62+
// restore original logging level after this test suite completes
63+
LoggingFacade logger = LoggingFactory.getLogger(PatchFile.class);
64+
logger.setLevel(originalLogLevel);
4165
}
4266

4367
@Test
@@ -56,20 +80,75 @@ void derivedVersion() {
5680

5781
@Test
5882
void resolveFile() throws IOException {
59-
LoggingFacade logger = LoggingFactory.getLogger(PatchFile.class);
60-
Level oldLevel = logger.getLevel();
61-
logger.setLevel(Level.OFF);
62-
try {
63-
// resolve should fail for a PatchFile that is not in the store
64-
PatchFile p1 = new PatchFile("99999", SOME_VERSION, null, null);
65-
assertThrows(FileNotFoundException.class, () -> p1.resolve(cacheStore));
66-
67-
// PatchFile resolve should result in the same behavior has getting the path from the cache store
68-
PatchFile patch2 = new PatchFile(BUGNUMBER, SOME_VERSION, null, null);
69-
String expected = cacheStore.getValueFromCache(BUGNUMBER + "_" + SOME_VERSION);
70-
assertEquals(expected, patch2.resolve(cacheStore), "failed to resolve patch in cache");
71-
} finally {
72-
logger.setLevel(oldLevel);
83+
// resolve should fail for a PatchFile that is not in the store
84+
PatchFile p1 = new PatchFile("99999", SOME_VERSION, null, null);
85+
assertThrows(FileNotFoundException.class, () -> p1.resolve(cacheStore));
86+
87+
// PatchFile resolve should result in the same behavior has getting the path from the cache store
88+
PatchFile patch2 = new PatchFile(BUGNUMBER, SOME_VERSION, null, null);
89+
String expected = cacheStore.getValueFromCache(BUGNUMBER + "_" + SOME_VERSION);
90+
assertEquals(expected, patch2.resolve(cacheStore), "failed to resolve patch in cache");
91+
}
92+
93+
94+
private static class TestPatchFile extends PatchFile {
95+
TestPatchFile(String patchId, String version, String userid, String password) {
96+
super(patchId, version, userid, password);
97+
}
98+
99+
@Override
100+
public void downloadFile(String url, String fileName, String username, String password) throws IOException {
101+
Path newFile = cacheDir.resolve(fileName);
102+
Files.write(newFile, fileContents);
103+
}
104+
}
105+
106+
107+
private PatchFile getPatchFileWithAruInfo(String patchId, String version, String aruXml)
108+
throws IOException, NoSuchFieldException, IllegalAccessException {
109+
110+
Field reader = PatchFile.class.getDeclaredField("aruInfo");
111+
reader.setAccessible(true);
112+
assertNull(cacheStore.getValueFromCache(patchId), "ERROR, patch should not exist in cache before test starts");
113+
PatchFile patchFile = new TestPatchFile(patchId, version, "[email protected]", "pass");
114+
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(
115+
this.getClass().getResourceAsStream(aruXml)))) {
116+
117+
String aruInfo = buffer.lines().collect(Collectors.joining("\n"));
118+
reader.set(patchFile, HttpUtil.parseXmlString(aruInfo));
73119
}
120+
return patchFile;
121+
}
122+
123+
@Test
124+
void gettingNewPatch() throws NoSuchFieldException, IllegalAccessException, IOException {
125+
String patchId = "1110001_12.2.1.3.0";
126+
PatchFile patchFile = getPatchFileWithAruInfo(patchId, "12.2.1.3.0", "/patch-1110001.xml");
127+
128+
String filePath = patchFile.resolve(cacheStore);
129+
130+
assertNotNull(filePath, "Patch resolve() failed to get file path from XML");
131+
String filePathFromCache = cacheStore.getValueFromCache(patchId);
132+
assertNotNull(filePathFromCache, "Could not find new patch in cache");
133+
assertEquals(filePath, filePathFromCache, "Patch in cache does not match");
134+
135+
assertEquals("600000000073715", patchFile.getReleaseNumber(), "Patch did not find release number");
136+
}
137+
138+
@Test
139+
void gettingNewPatchWithoutVersion() throws NoSuchFieldException, IllegalAccessException, IOException {
140+
// without the version in the patch ID, the ARU info must contain only one patch
141+
String patchId = "1110002";
142+
// patch version in XML is actually 12.2.1.1.0, code will warn user and reset patch version
143+
PatchFile patchFile = getPatchFileWithAruInfo(patchId, "12.2.1.2.0", "/patch-1110002.xml");
144+
145+
String filePath = patchFile.resolve(cacheStore);
146+
147+
assertNotNull(filePath, "Patch resolve() failed to get file path from XML");
148+
String filePathFromCache = cacheStore.getValueFromCache(patchId + "_12.2.1.1.0");
149+
assertNotNull(filePathFromCache, "Could not find new patch in cache");
150+
assertEquals(filePath, filePathFromCache, "Patch in cache does not match");
151+
152+
assertEquals("600000000055130", patchFile.getReleaseNumber(), "Patch did not find release number");
74153
}
75154
}

0 commit comments

Comments
 (0)