|
| 1 | +package serpapi; |
| 2 | + |
| 3 | +import org.junit.Test; |
| 4 | + |
| 5 | +import java.util.HashMap; |
| 6 | +import java.util.Map; |
| 7 | + |
| 8 | +import static org.junit.Assert.*; |
| 9 | + |
| 10 | +/** |
| 11 | + * Test SerpApi.html() method. |
| 12 | + * |
| 13 | + * Offline: the HTTP client is stubbed, so no network call and no SERPAPI_KEY |
| 14 | + * are needed. What matters here is the request this client builds, which can |
| 15 | + * be asserted without a live backend. |
| 16 | + */ |
| 17 | +public class HtmlApiTest { |
| 18 | + |
| 19 | + /** |
| 20 | + * Stubbed HTTP client that records the query it was asked to send. |
| 21 | + */ |
| 22 | + private static class RecordingHttp extends SerpApiHttp { |
| 23 | + Map<String, String> recorded; |
| 24 | + |
| 25 | + RecordingHttp() { |
| 26 | + super("/search"); |
| 27 | + } |
| 28 | + |
| 29 | + @Override |
| 30 | + public String get(Map<String, String> parameter) { |
| 31 | + this.recorded = parameter; |
| 32 | + return "<html><body>coffee</body></html>"; |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + @Test |
| 37 | + public void htmlRequestsHtmlOutputFromSearchEndpoint() throws SerpApiException { |
| 38 | + SerpApi serpapi = new SerpApi(new HashMap<>()); |
| 39 | + RecordingHttp http = new RecordingHttp(); |
| 40 | + serpapi.client = http; |
| 41 | + |
| 42 | + Map<String, String> parameter = new HashMap<>(); |
| 43 | + parameter.put("q", "coffee"); |
| 44 | + String content = serpapi.html(parameter); |
| 45 | + |
| 46 | + assertEquals("html", http.recorded.get("output")); |
| 47 | + assertEquals("coffee", http.recorded.get("q")); |
| 48 | + assertEquals("/search", http.path); |
| 49 | + assertTrue(content.startsWith("<html>")); |
| 50 | + } |
| 51 | + |
| 52 | + @Test |
| 53 | + public void htmlMergesDefaultParameter() throws SerpApiException { |
| 54 | + Map<String, String> auth = new HashMap<>(); |
| 55 | + auth.put("api_key", "secret"); |
| 56 | + auth.put("engine", "google"); |
| 57 | + SerpApi serpapi = new SerpApi(auth); |
| 58 | + RecordingHttp http = new RecordingHttp(); |
| 59 | + serpapi.client = http; |
| 60 | + |
| 61 | + serpapi.html(new HashMap<>()); |
| 62 | + |
| 63 | + assertEquals("secret", http.recorded.get("api_key")); |
| 64 | + assertEquals("google", http.recorded.get("engine")); |
| 65 | + assertEquals("html", http.recorded.get("output")); |
| 66 | + } |
| 67 | +} |
0 commit comments