Changeset 12557 in josm


Ignore:
Timestamp:
2017-08-02T20:41:01+02:00 (2 weeks ago)
Author:
Don-vip
Message:

see #15102 - first batch of HTTP unit tests mocking, using WireMock 2.7.1

Location:
trunk
Files:
16 added
1 deleted
12 edited

Legend:

Unmodified
Added
Removed
  • trunk/.classpath

    r12503 r12557  
    2222        <classpathentry kind="lib" path="test/lib/unitils-core/unitils-core-3.4.6.jar"/>
    2323        <classpathentry kind="lib" path="test/lib/commons-testing/commons-testing-2.1.0.jar"/>
     24        <classpathentry kind="lib" path="test/lib/wiremock-standalone-2.7.1.jar"/>
    2425        <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
    2526        <classpathentry exported="true" kind="con" path="GROOVY_SUPPORT"/>
  • trunk/netbeans/nbproject/project.properties

    r12516 r12557  
    5858file.reference.unitils-core-3.4.6.jar=../test/lib/unitils-core/unitils-core-3.4.6.jar
    5959file.reference.system-rules-1.16.1.jar=../test/lib/system-rules-1.16.1.jar
     60file.reference.wiremock-standalone-2.7.1.jar=../test/lib/wiremock-standalone-2.7.1.jar
    6061includes=**/*.java
    6162jar.compress=false
     
    9192    ${file.reference.unitils-core-3.4.6.jar}:\
    9293    ${file.reference.system-rules-1.16.1.jar}:\
     94    ${file.reference.wiremock-standalone-2.7.1.jar}:\
    9395    ${file.reference.findbugs.jar}:\
    9496    ${file.reference.commons-testing-2.1.0.jar}
  • trunk/src/org/openstreetmap/josm/io/NameFinder.java

    r11746 r12557  
    1818import org.openstreetmap.josm.data.osm.PrimitiveId;
    1919import org.openstreetmap.josm.data.osm.SimplePrimitiveId;
     20import org.openstreetmap.josm.data.preferences.StringProperty;
    2021import org.openstreetmap.josm.tools.HttpClient;
     22import org.openstreetmap.josm.tools.HttpClient.Response;
    2123import org.openstreetmap.josm.tools.OsmUrlToBounds;
    2224import org.openstreetmap.josm.tools.UncheckedParseException;
     
    3436
    3537    /**
    36      * Nominatim URL.
     38     * Nominatim default URL.
    3739     */
    3840    public static final String NOMINATIM_URL = "https://nominatim.openstreetmap.org/search?format=xml&q=";
     41
     42    /**
     43     * Nominatim URL property.
     44     * @since xxx
     45     */
     46    public static final StringProperty NOMINATIM_URL_PROP = new StringProperty("nominatim-url", NOMINATIM_URL);
    3947
    4048    private NameFinder() {
     
    4856     */
    4957    public static List<SearchResult> queryNominatim(final String searchExpression) throws IOException {
    50         return query(new URL(NOMINATIM_URL + Utils.encodeUrl(searchExpression)));
     58        return query(new URL(NOMINATIM_URL_PROP.get() + Utils.encodeUrl(searchExpression)));
    5159    }
    5260
     
    5967    public static List<SearchResult> query(final URL url) throws IOException {
    6068        final HttpClient connection = HttpClient.create(url);
    61         connection.connect();
    62         try (Reader reader = connection.getResponse().getContentReader()) {
     69        Response response = connection.connect();
     70        if (response.getResponseCode() >= 400) {
     71            throw new IOException(response.getResponseMessage() + ": " + response.fetchContent());
     72        }
     73        try (Reader reader = response.getContentReader()) {
    6374            return parseSearchResults(reader);
    6475        } catch (ParserConfigurationException | SAXException ex) {
  • trunk/src/org/openstreetmap/josm/io/imagery/WMSImagery.java

    r12475 r12557  
    3030import org.openstreetmap.josm.data.projection.Projections;
    3131import org.openstreetmap.josm.tools.HttpClient;
     32import org.openstreetmap.josm.tools.HttpClient.Response;
    3233import org.openstreetmap.josm.tools.Utils;
    3334import org.w3c.dom.Document;
     
    226227        }
    227228
    228         final String incomingData = HttpClient.create(getCapabilitiesUrl).connect().fetchContent();
     229        final Response response = HttpClient.create(getCapabilitiesUrl).connect();
     230        final String incomingData = response.fetchContent();
    229231        Main.debug("Server response to Capabilities request:");
    230232        Main.debug(incomingData);
     233
     234        if (response.getResponseCode() >= 400) {
     235            throw new WMSGetCapabilitiesException(response.getResponseMessage(), incomingData);
     236        }
    231237
    232238        try {
  • trunk/test/unit/org/openstreetmap/josm/actions/AddImageryLayerActionTest.java

    r12444 r12557  
    22package org.openstreetmap.josm.actions;
    33
     4import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
     5import static com.github.tomakehurst.wiremock.client.WireMock.get;
     6import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
     7import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
    48import static org.junit.Assert.assertEquals;
    59import static org.junit.Assert.assertTrue;
     
    1014import org.junit.Test;
    1115import org.openstreetmap.josm.Main;
     16import org.openstreetmap.josm.TestUtils;
    1217import org.openstreetmap.josm.data.imagery.ImageryInfo;
    1318import org.openstreetmap.josm.gui.layer.TMSLayer;
     19import org.openstreetmap.josm.gui.layer.WMSLayer;
    1420import org.openstreetmap.josm.testutils.JOSMTestRules;
     21
     22import com.github.tomakehurst.wiremock.junit.WireMockRule;
    1523
    1624import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
     
    3038
    3139    /**
     40     * HTTP mock.
     41     */
     42    @Rule
     43    public WireMockRule wireMockRule = new WireMockRule(options().dynamicPort().usingFilesUnderDirectory(TestUtils.getTestDataRoot()));
     44
     45    /**
    3246     * Unit test of {@link AddImageryLayerAction#updateEnabledState}.
    3347     */
     
    4559     */
    4660    @Test
    47     public void testActionPerformedEnabled() {
     61    public void testActionPerformedEnabledTms() {
    4862        assertTrue(Main.getLayerManager().getLayersOfType(TMSLayer.class).isEmpty());
    4963        new AddImageryLayerAction(new ImageryInfo("foo_tms", "http://bar", "tms", null, null)).actionPerformed(null);
     
    5165        assertEquals(1, tmsLayers.size());
    5266        Main.getLayerManager().removeLayer(tmsLayers.get(0));
     67    }
     68
     69    /**
     70     * Unit test of {@link AddImageryLayerAction#actionPerformed} - Enabled cases for WMS.
     71     */
     72    @Test
     73    public void testActionPerformedEnabledWms() {
     74        wireMockRule.stubFor(get(urlEqualTo("/wms?VERSION=1.1.1&SERVICE=WMS&REQUEST=GetCapabilities"))
     75                .willReturn(aResponse()
     76                    .withStatus(200)
     77                    .withHeader("Content-Type", "text/xml")
     78                    .withBodyFile("imagery/wms-capabilities.xml")));
     79        new AddImageryLayerAction(new ImageryInfo("localhost", "http://localhost:" + wireMockRule.port() + "/wms?",
     80                "wms_endpoint", null, null)).actionPerformed(null);
     81        List<WMSLayer> wmsLayers = Main.getLayerManager().getLayersOfType(WMSLayer.class);
     82        assertEquals(1, wmsLayers.size());
     83
     84        Main.getLayerManager().removeLayer(wmsLayers.get(0));
    5385    }
    5486
  • trunk/test/unit/org/openstreetmap/josm/actions/downloadtasks/DownloadGpsTaskTest.java

    r12248 r12557  
    88import java.util.concurrent.ExecutionException;
    99
    10 import org.junit.Rule;
    1110import org.junit.Test;
    1211import org.openstreetmap.josm.data.gpx.GpxData;
    13 import org.openstreetmap.josm.testutils.JOSMTestRules;
    14 
    15 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
    1612
    1713/**
    1814 * Unit tests for class {@link DownloadGpsTask}.
    1915 */
    20 public class DownloadGpsTaskTest {
    21 
    22     private static final String REMOTE_FILE = "https://josm.openstreetmap.de/export/head/josm/trunk/data_nodist/munich.gpx";
    23 
    24     /**
    25      * Setup test.
    26      */
    27     @Rule
    28     @SuppressFBWarnings(value = "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD")
    29     public JOSMTestRules test = new JOSMTestRules().https();
     16public class DownloadGpsTaskTest extends AbstractDownloadTaskTest {
    3017
    3118    /**
     
    4532        assertTrue(task.acceptsUrl("https://www.openstreetmap.org/edit?gpx=750057"));
    4633        assertTrue(task.acceptsUrl("http://www.openstreetmap.org/edit?gpx=2277313#map=14/-20.7321/-40.5328"));
    47         assertTrue(task.acceptsUrl(REMOTE_FILE));
     34        assertTrue(task.acceptsUrl(getRemoteFileUrl()));
    4835    }
    4936
     
    5542    @Test
    5643    public void testDownloadExternalFile() throws InterruptedException, ExecutionException {
     44        mockHttp();
    5745        DownloadGpsTask task = new DownloadGpsTask();
    58         task.loadUrl(false, REMOTE_FILE, null).get();
     46        task.loadUrl(false, getRemoteFileUrl(), null).get();
    5947        GpxData data = task.getDownloadedData();
    6048        assertNotNull(data);
     
    6250        assertFalse(data.tracks.isEmpty());
    6351    }
     52
     53    @Override
     54    protected String getRemoteFile() {
     55        return "samples/data.gpx";
     56    }
    6457}
  • trunk/test/unit/org/openstreetmap/josm/actions/downloadtasks/DownloadNotesTaskTest.java

    r12248 r12557  
    88import java.util.concurrent.ExecutionException;
    99
    10 import org.junit.Rule;
    1110import org.junit.Test;
    1211import org.openstreetmap.josm.data.osm.NoteData;
    13 import org.openstreetmap.josm.testutils.JOSMTestRules;
    14 
    15 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
    1612
    1713/**
    1814 * Unit tests for class {@link DownloadNotesTask}.
    1915 */
    20 public class DownloadNotesTaskTest {
    21 
    22     private static final String REMOTE_FILE = "https://josm.openstreetmap.de/export/head/josm/trunk/test/data/planet-notes-extract.osn";
    23 
    24     /**
    25      * Setup test.
    26      */
    27     @Rule
    28     @SuppressFBWarnings(value = "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD")
    29     public JOSMTestRules test = new JOSMTestRules().platform().https();
     16public class DownloadNotesTaskTest extends AbstractDownloadTaskTest {
    3017
    3118    /**
     
    4128        assertTrue(task.acceptsUrl("http://api.openstreetmap.org/api/0.6/notes.xml?bbox=-0.65094,51.312159,0.374908,51.669148"));
    4229        assertTrue(task.acceptsUrl("http://api.openstreetmap.org/api/0.6/notes.gpx?bbox=-0.65094,51.312159,0.374908,51.669148"));
    43         assertTrue(task.acceptsUrl(REMOTE_FILE));
     30        assertTrue(task.acceptsUrl(getRemoteFileUrl()));
    4431    }
    4532
     
    5138    @Test
    5239    public void testDownloadExternalFile() throws InterruptedException, ExecutionException {
     40        mockHttp();
    5341        DownloadNotesTask task = new DownloadNotesTask();
    54         task.loadUrl(false, REMOTE_FILE, null).get();
     42        task.loadUrl(false, getRemoteFileUrl(), null).get();
    5543        NoteData data = task.getDownloadedData();
    5644        assertNotNull(data);
    5745        assertFalse(data.getNotes().isEmpty());
    5846    }
     47
     48    @Override
     49    protected String getRemoteFile() {
     50        return "samples/data.osn";
     51    }
    5952}
  • trunk/test/unit/org/openstreetmap/josm/actions/downloadtasks/DownloadOsmTaskTest.java

    r12248 r12557  
    88import java.util.concurrent.ExecutionException;
    99
    10 import org.junit.Rule;
    1110import org.junit.Test;
    1211import org.openstreetmap.josm.data.osm.DataSet;
    13 import org.openstreetmap.josm.testutils.JOSMTestRules;
    14 
    15 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
    1612
    1713/**
    1814 * Unit tests for class {@link DownloadOsmTask}.
    1915 */
    20 public class DownloadOsmTaskTest {
    21 
    22     private static final String REMOTE_FILE = "https://josm.openstreetmap.de/export/head/josm/trunk/data_nodist/direction-arrows.osm";
    23 
    24     /**
    25      * Setup test.
    26      */
    27     @Rule
    28     @SuppressFBWarnings(value = "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD")
    29     public JOSMTestRules test = new JOSMTestRules().https();
     16public class DownloadOsmTaskTest extends AbstractDownloadTaskTest {
    3017
    3118    /**
     
    4330        assertTrue(task.acceptsUrl("http://api.openstreetmap.org/api/0.6/ways?ways=101,102,103"));
    4431        assertTrue(task.acceptsUrl("http://api.openstreetmap.org/api/0.6/relations?relations=101,102,103"));
    45         assertTrue(task.acceptsUrl(REMOTE_FILE));
     32        assertTrue(task.acceptsUrl(getRemoteFileUrl()));
    4633    }
    4734
     
    5340    @Test
    5441    public void testDownloadExternalFile() throws InterruptedException, ExecutionException {
     42        mockHttp();
    5543        DownloadOsmTask task = new DownloadOsmTask();
    56         task.loadUrl(false, REMOTE_FILE, null).get();
     44        task.loadUrl(false, getRemoteFileUrl(), null).get();
    5745        DataSet ds = task.getDownloadedData();
    5846        assertNotNull(ds);
     
    6048        assertFalse(ds.getWays().isEmpty());
    6149    }
     50
     51    @Override
     52    protected String getRemoteFile() {
     53        return "samples/data.osm";
     54    }
    6255}
  • trunk/test/unit/org/openstreetmap/josm/gui/DefaultNameFormatterTest.java

    r10378 r12557  
    22package org.openstreetmap.josm.gui;
    33
     4import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
     5import static com.github.tomakehurst.wiremock.client.WireMock.get;
     6import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
     7import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
    48import static org.junit.Assert.assertEquals;
    59
     
    1014import java.util.List;
    1115
    12 import org.junit.BeforeClass;
     16import org.junit.Rule;
    1317import org.junit.Test;
    14 import org.openstreetmap.josm.JOSMFixture;
    1518import org.openstreetmap.josm.TestUtils;
    1619import org.openstreetmap.josm.data.osm.DataSet;
     
    2427import org.openstreetmap.josm.io.IllegalDataException;
    2528import org.openstreetmap.josm.io.OsmReader;
     29import org.openstreetmap.josm.testutils.JOSMTestRules;
    2630import org.xml.sax.SAXException;
     31
     32import com.github.tomakehurst.wiremock.junit.WireMockRule;
    2733
    2834import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
     
    3440
    3541    /**
    36      * Setup tests
     42     * Setup test.
    3743     */
    38     @BeforeClass
    39     public static void setUpBeforeClass() {
    40         JOSMFixture.createUnitTestFixture().init();
    41     }
     44    @Rule
     45    @SuppressFBWarnings(value = "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD")
     46    public JOSMTestRules test = new JOSMTestRules().platform();
     47
     48    /**
     49     * HTTP mock.
     50     */
     51    @Rule
     52    public WireMockRule wireMockRule = new WireMockRule(options().dynamicPort().usingFilesUnderDirectory(TestUtils.getTestDataRoot()));
    4253
    4354    /**
     
    5061    @SuppressFBWarnings(value = "ITA_INEFFICIENT_TO_ARRAY")
    5162    public void testTicket9632() throws IllegalDataException, IOException, SAXException {
    52         String source = "http://josm.openstreetmap.de/josmfile?page=Presets/BicycleJunction&amp;preset";
    53         TaggingPresets.addTaggingPresets(TaggingPresetReader.readAll(source, true));
     63        String source = "presets/Presets_BicycleJunction-preset.xml";
     64        wireMockRule.stubFor(get(urlEqualTo("/" + source))
     65                .willReturn(aResponse()
     66                    .withStatus(200)
     67                    .withHeader("Content-Type", "text/xml")
     68                    .withBodyFile(source)));
     69        TaggingPresets.addTaggingPresets(TaggingPresetReader.readAll("http://localhost:" + wireMockRule.port() + "/" + source, true));
    5470
    5571        Comparator<Relation> comparator = DefaultNameFormatter.getInstance().getRelationComparator();
  • trunk/test/unit/org/openstreetmap/josm/gui/preferences/imagery/ImageryPreferenceTest.java

    r10977 r12557  
    44import static org.junit.Assert.assertNotNull;
    55
     6import java.io.File;
     7import java.util.Arrays;
     8
    69import org.junit.Rule;
    710import org.junit.Test;
     11import org.openstreetmap.josm.Main;
     12import org.openstreetmap.josm.TestUtils;
    813import org.openstreetmap.josm.gui.preferences.PreferencesTestUtils;
    914import org.openstreetmap.josm.testutils.JOSMTestRules;
     
    2126    @Rule
    2227    @SuppressFBWarnings(value = "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD")
    23     public JOSMTestRules test = new JOSMTestRules().platform().commands();
     28    public JOSMTestRules test = new JOSMTestRules().platform().mainMenu();
    2429
    2530    /**
     
    3641    @Test
    3742    public void testAddGui() {
     43        String fileUrl = new File(TestUtils.getTestDataRoot()+"__files/imagery/maps.xml").toURI().toString();
     44        Main.pref.putCollection("imagery.layers.sites", Arrays.asList(fileUrl));
    3845        PreferencesTestUtils.doTestPreferenceSettingAddGui(new ImageryPreference.Factory(), null);
    3946    }
  • trunk/test/unit/org/openstreetmap/josm/io/OverpassDownloadReaderTest.java

    r11917 r12557  
    22package org.openstreetmap.josm.io;
    33
     4import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
     5import static com.github.tomakehurst.wiremock.client.WireMock.get;
     6import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
     7import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
    48import static org.junit.Assert.assertEquals;
    59import static org.junit.Assert.assertTrue;
     
    711import java.util.regex.Matcher;
    812
     13import org.junit.Before;
    914import org.junit.Rule;
    1015import org.junit.Test;
     16import org.openstreetmap.josm.TestUtils;
    1117import org.openstreetmap.josm.data.Bounds;
    12 import org.openstreetmap.josm.gui.preferences.server.OverpassServerPreference;
    1318import org.openstreetmap.josm.io.OverpassDownloadReader.OverpassOutpoutFormat;
    1419import org.openstreetmap.josm.testutils.JOSMTestRules;
    1520import org.openstreetmap.josm.tools.OverpassTurboQueryWizard;
    1621import org.openstreetmap.josm.tools.Utils;
     22
     23import com.github.tomakehurst.wiremock.junit.WireMockRule;
    1724
    1825import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
     
    2835    @Rule
    2936    @SuppressFBWarnings(value = "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD")
    30     public JOSMTestRules test = new JOSMTestRules().timeout(15000);
     37    public JOSMTestRules test = new JOSMTestRules().preferences();
     38
     39    /**
     40     * HTTP mock.
     41     */
     42    @Rule
     43    public WireMockRule wireMockRule = new WireMockRule(options().dynamicPort().usingFilesUnderDirectory(TestUtils.getTestDataRoot()));
     44
     45    private static final String NOMINATIM_URL_PATH = "/search?format=xml&q=";
     46
     47    /**
     48     * Setup test.
     49     */
     50    @Before
     51    public void setUp() {
     52        NameFinder.NOMINATIM_URL_PROP.put("http://localhost:" + wireMockRule.port() + NOMINATIM_URL_PATH);
     53    }
    3154
    3255    private String getExpandedQuery(String search) {
    3356        final String query = OverpassTurboQueryWizard.getInstance().constructQuery(search);
    34         final String request = new OverpassDownloadReader(new Bounds(1, 2, 3, 4), OverpassServerPreference.getOverpassServer(), query)
     57        final String request = new OverpassDownloadReader(new Bounds(1, 2, 3, 4), null, query)
    3558                .getRequestForBbox(1, 2, 3, 4)
    3659                .substring("interpreter?data=".length());
     
    5578    }
    5679
     80    private void stubNominatim(String query) {
     81        wireMockRule.stubFor(get(urlEqualTo(NOMINATIM_URL_PATH + query))
     82                .willReturn(aResponse()
     83                    .withStatus(200)
     84                    .withHeader("Content-Type", "text/xml")
     85                    .withBodyFile("nominatim/" + query + ".xml")));
     86    }
     87
    5788    /**
    5889     * Tests evaluating the extended query feature {@code geocodeArea}.
     
    6091    @Test
    6192    public void testGeocodeArea() {
     93        stubNominatim("London");
    6294        final String query = getExpandedQuery("amenity=drinking_water in London");
    6395        assertEquals("" +
     
    78110    @Test
    79111    public void testGeocodeUnknownArea() {
     112        stubNominatim("foo-bar-baz-does-not-exist");
    80113        final String query = OverpassDownloadReader.expandExtendedQueries("{{geocodeArea:foo-bar-baz-does-not-exist}}");
    81114        assertEquals("// Failed to evaluate {{geocodeArea:foo-bar-baz-does-not-exist}}\n", query);
  • trunk/test/unit/org/openstreetmap/josm/testutils/JOSMTestRules.java

    r12556 r12557  
    1717import org.openstreetmap.josm.data.osm.event.SelectionEventManager;
    1818import org.openstreetmap.josm.data.projection.Projections;
     19import org.openstreetmap.josm.gui.MainApplication;
     20import org.openstreetmap.josm.gui.MainMenu;
    1921import org.openstreetmap.josm.gui.mappaint.MapPaintStyles;
    2022import org.openstreetmap.josm.gui.util.GuiHelper;
     
    5557    private boolean territories;
    5658    private boolean rlTraffic;
     59    private boolean main;
     60    private boolean mainMenu;
    5761
    5862    /**
     
    205209    public JOSMTestRules rlTraffic() {
    206210        rlTraffic = true;
     211        return this;
     212    }
     213
     214    /**
     215     * Use the {@link Main#main} application in this test.
     216     * @return this instance, for easy chaining
     217     * @since xxx
     218     */
     219    public JOSMTestRules main() {
     220        main = true;
     221        return this;
     222    }
     223
     224    /**
     225     * Use the {@link Main#menu} in this test.
     226     * @return this instance, for easy chaining
     227     * @since xxx
     228     */
     229    public JOSMTestRules mainMenu() {
     230        main();
     231        mainMenu = true;
    207232        return this;
    208233    }
     
    311336            // TODO: Implement a more selective version of this once Main is restructured.
    312337            JOSMFixture.createUnitTestFixture().init(true);
     338        } else {
     339            if (main) {
     340                new MainApplication();
     341            }
     342
     343            if (mainMenu) {
     344                JOSMFixture.initContentPane();
     345                JOSMFixture.initToolbar();
     346                Main.main.menu = new MainMenu();
     347            }
    313348        }
    314349    }
Note: See TracChangeset for help on using the changeset viewer.