Ticket #12949: patch-tests-use-rules.patch

File patch-tests-use-rules.patch, 20.0 KB (added by michael2402, 9 years ago)
  • src/org/openstreetmap/josm/actions/AddImageryLayerAction.java

    diff --git a/src/org/openstreetmap/josm/actions/AddImageryLayerAction.java b/src/org/openstreetmap/josm/actions/AddImageryLayerAction.java
    index f857d65..c36973c 100644
    a b public class AddImageryLayerAction extends JosmAction implements AdaptableAction  
    7878            final ImageryInfo infoToAdd = ImageryType.WMS_ENDPOINT.equals(info.getImageryType())
    7979                    ? getWMSLayerInfo() : info;
    8080            if (infoToAdd != null) {
    81                 Main.main.addLayer(ImageryLayer.create(infoToAdd));
     81                Main.getLayerManager().addLayer(ImageryLayer.create(infoToAdd));
    8282                AlignImageryPanel.addNagPanelIfNeeded(infoToAdd);
    8383            }
    8484        } catch (IllegalArgumentException ex) {
  • src/org/openstreetmap/josm/io/OsmApi.java

    diff --git a/src/org/openstreetmap/josm/io/OsmApi.java b/src/org/openstreetmap/josm/io/OsmApi.java
    index d661461..8835df1 100644
    a b public class OsmApi extends OsmConnection {  
    8989        OsmApi api = instances.get(serverUrl);
    9090        if (api == null) {
    9191            api = new OsmApi(serverUrl);
    92             instances.put(serverUrl, api);
     92            cacheInstance(api);
    9393        }
    9494        return api;
    9595    }
    9696
     97    protected static void cacheInstance(OsmApi api) {
     98        instances.put(api.getServerUrl(), api);
     99    }
     100
    97101    private static String getServerUrlFromPref() {
    98102        return Main.pref.get("osm-server.url", DEFAULT_API_URL);
    99103    }
  • test/unit/org/openstreetmap/josm/actions/AddImageryLayerActionTest.java

    diff --git a/test/unit/org/openstreetmap/josm/actions/AddImageryLayerActionTest.java b/test/unit/org/openstreetmap/josm/actions/AddImageryLayerActionTest.java
    index da3a1f8..8a56466 100644
    a b import static org.junit.Assert.assertTrue;  
    77
    88import java.util.List;
    99
    10 import org.junit.BeforeClass;
     10import org.junit.Rule;
    1111import org.junit.Test;
    12 import org.openstreetmap.josm.JOSMFixture;
    1312import org.openstreetmap.josm.Main;
    1413import org.openstreetmap.josm.data.imagery.ImageryInfo;
    1514import org.openstreetmap.josm.gui.layer.TMSLayer;
    1615import org.openstreetmap.josm.gui.layer.WMSLayer;
     16import org.openstreetmap.josm.testutils.JOSMTestRules;
    1717
    1818/**
    1919 * Unit tests for class {@link AddImageryLayerAction}.
    2020 */
    2121public final class AddImageryLayerActionTest {
    22 
    2322    /**
    24      * Setup test.
     23     * We need prefs for this. We need platform for actions and the OSM API for checking blacklist.
     24     * @since xxx
    2525     */
    26     @BeforeClass
    27     public static void setUp() {
    28         JOSMFixture.createUnitTestFixture().init(true);
    29     }
     26    @Rule
     27    public JOSMTestRules test = new JOSMTestRules().preferences().platform().fakeAPI();
    3028
    3129    /**
    3230     * Unit test of {@link AddImageryLayerAction#updateEnabledState}.
    public final class AddImageryLayerActionTest {  
    3432    @Test
    3533    public void testEnabledState() {
    3634        assertFalse(new AddImageryLayerAction(new ImageryInfo()).isEnabled());
    37         assertFalse(new AddImageryLayerAction(new ImageryInfo("google", "http://maps.google.com/api", "tms", null, null)).isEnabled());
    3835        assertTrue(new AddImageryLayerAction(new ImageryInfo("foo_tms", "http://bar", "tms", null, null)).isEnabled());
    3936        assertTrue(new AddImageryLayerAction(new ImageryInfo("foo_bing", "http://bar", "bing", null, null)).isEnabled());
    4037        assertTrue(new AddImageryLayerAction(new ImageryInfo("foo_scanex", "http://bar", "scanex", null, null)).isEnabled());
    public final class AddImageryLayerActionTest {  
    4239    }
    4340
    4441    /**
     42     * Unit test of {@link AddImageryLayerAction#updateEnabledState} respects blacklist.
     43     * @since xxx
     44     */
     45    @Test
     46    public void testEnabledStateBlacklist() {
     47        assertFalse(new AddImageryLayerAction(new ImageryInfo("google", "http://blacklisted", "tms", null, null)).isEnabled());
     48        assertFalse(new AddImageryLayerAction(new ImageryInfo("google", "https://invalid", "tms", null, null)).isEnabled());
     49        assertTrue(new AddImageryLayerAction(new ImageryInfo("google", "https://notinvalid", "tms", null, null)).isEnabled());
     50    }
     51
     52    /**
    4553     * Unit test of {@link AddImageryLayerAction#actionPerformed} - Enabled cases.
    4654     */
    4755    @Test
    4856    public void testActionPerformedEnabled() {
    49         assertTrue(Main.map.mapView.getLayersOfType(TMSLayer.class).isEmpty());
     57        assertTrue(Main.getLayerManager().getLayersOfType(TMSLayer.class).isEmpty());
    5058        new AddImageryLayerAction(new ImageryInfo("foo_tms", "http://bar", "tms", null, null)).actionPerformed(null);
    51         List<TMSLayer> tmsLayers = Main.map.mapView.getLayersOfType(TMSLayer.class);
     59        List<TMSLayer> tmsLayers = Main.getLayerManager().getLayersOfType(TMSLayer.class);
    5260        assertEquals(1, tmsLayers.size());
    5361
    54         try {
    55             new AddImageryLayerAction(new ImageryInfo("wms.openstreetmap.fr", "http://wms.openstreetmap.fr/wms?",
    56                     "wms_endpoint", null, null)).actionPerformed(null);
    57             List<WMSLayer> wmsLayers = Main.map.mapView.getLayersOfType(WMSLayer.class);
    58             assertEquals(1, wmsLayers.size());
    59 
    60             Main.map.mapView.removeLayer(wmsLayers.get(0));
    61         } finally {
    62             Main.map.mapView.removeLayer(tmsLayers.get(0));
    63         }
     62        new AddImageryLayerAction(new ImageryInfo("wms.openstreetmap.fr", "http://wms.openstreetmap.fr/wms?",
     63                "wms_endpoint", null, null)).actionPerformed(null);
     64        List<WMSLayer> wmsLayers = Main.getLayerManager().getLayersOfType(WMSLayer.class);
     65        assertEquals(1, wmsLayers.size());
    6466    }
    6567
    6668    /**
    public final class AddImageryLayerActionTest {  
    6870     */
    6971    @Test
    7072    public void testActionPerformedDisabled() {
    71         assertTrue(Main.map.mapView.getLayersOfType(TMSLayer.class).isEmpty());
     73        assertTrue(Main.getLayerManager().getLayersOfType(TMSLayer.class).isEmpty());
    7274        new AddImageryLayerAction(new ImageryInfo()).actionPerformed(null);
    73         assertTrue(Main.map.mapView.getLayersOfType(TMSLayer.class).isEmpty());
     75        assertTrue(Main.getLayerManager().getLayersOfType(TMSLayer.class).isEmpty());
    7476    }
    7577}
  • test/unit/org/openstreetmap/josm/actions/search/SearchCompilerTest.java

    diff --git a/test/unit/org/openstreetmap/josm/actions/search/SearchCompilerTest.java b/test/unit/org/openstreetmap/josm/actions/search/SearchCompilerTest.java
    index 097d1e3..bb63195 100644
    a b package org.openstreetmap.josm.actions.search;  
    44import static org.junit.Assert.assertEquals;
    55import static org.junit.Assert.assertFalse;
    66import static org.junit.Assert.assertTrue;
     7import static org.junit.Assert.fail;
    78
    8 import org.junit.Before;
     9import org.junit.Rule;
    910import org.junit.Test;
    10 import org.openstreetmap.josm.JOSMFixture;
    1111import org.openstreetmap.josm.actions.search.SearchCompiler.Match;
    1212import org.openstreetmap.josm.actions.search.SearchCompiler.ParseError;
    1313import org.openstreetmap.josm.data.coor.LatLon;
    import org.openstreetmap.josm.data.osm.Tag;  
    2222import org.openstreetmap.josm.data.osm.User;
    2323import org.openstreetmap.josm.data.osm.Way;
    2424import org.openstreetmap.josm.data.osm.WayData;
     25import org.openstreetmap.josm.testutils.JOSMTestRules;
    2526import org.openstreetmap.josm.tools.date.DateUtils;
    2627
    2728/**
    import org.openstreetmap.josm.tools.date.DateUtils;  
    3031public class SearchCompilerTest {
    3132
    3233    /**
    33      * Setup test.
     34     * We need prefs for this. We access preferences when creating OSM primitives.
     35     * @since xxx
    3436     */
    35     @Before
    36     public void setUp() {
    37         JOSMFixture.createUnitTestFixture().init();
    38     }
     37    @Rule
     38    public JOSMTestRules test = new JOSMTestRules().preferences();
    3939
    4040    private static final class SearchContext {
    4141        final DataSet ds = new DataSet();
    public class SearchCompilerTest {  
    389389    public void testFooTypeBar() {
    390390        try {
    391391            SearchCompiler.compile("foo type bar");
    392             throw new RuntimeException();
     392            fail();
    393393        } catch (ParseError parseError) {
    394394            assertEquals("<html>Expecting <code>:</code> after <i>type</i>", parseError.getMessage());
    395395        }
  • new file test/unit/org/openstreetmap/josm/testutils/FakeOsmApi.java

    diff --git a/test/unit/org/openstreetmap/josm/testutils/FakeOsmApi.java b/test/unit/org/openstreetmap/josm/testutils/FakeOsmApi.java
    new file mode 100644
    index 0000000..5d45f85
    - +  
     1// License: GPL. For details, see LICENSE file.
     2package org.openstreetmap.josm.testutils;
     3
     4import org.openstreetmap.josm.data.coor.LatLon;
     5import org.openstreetmap.josm.data.notes.Note;
     6import org.openstreetmap.josm.data.osm.Changeset;
     7import org.openstreetmap.josm.data.osm.IPrimitive;
     8import org.openstreetmap.josm.data.osm.OsmPrimitive;
     9import org.openstreetmap.josm.gui.progress.ProgressMonitor;
     10import org.openstreetmap.josm.io.Capabilities;
     11import org.openstreetmap.josm.io.OsmApi;
     12import org.openstreetmap.josm.io.OsmApiInitializationException;
     13import org.openstreetmap.josm.io.OsmTransferCanceledException;
     14import org.openstreetmap.josm.io.OsmTransferException;
     15
     16/**
     17 * A fake OSM API server. It is used to test again.
     18 * <p>
     19 * It provides only basic features.
     20 * <p>
     21 * These image servers are blacklisted:
     22 * <ul>
     23 * <li>.*blacklisted.*</li>
     24 * <li>^(invalid|bad).*</li>
     25 * </ul>
     26 *
     27 * @author Michael Zangl
     28 * @since xxx
     29 */
     30public class FakeOsmApi extends OsmApi {
     31
     32    private static FakeOsmApi instance;
     33
     34    private boolean initialized = false;
     35
     36    protected FakeOsmApi() {
     37        super("http://fake.xxx/api");
     38    }
     39
     40    @Override
     41    public void initialize(ProgressMonitor monitor, boolean fastFail)
     42            throws OsmTransferCanceledException, OsmApiInitializationException {
     43        // we do not connect to any server so we do not need that.
     44        initialized = true;
     45    }
     46
     47    @Override
     48    public synchronized Capabilities getCapabilities() {
     49        if (!initialized) {
     50            return null;
     51        } else {
     52            Capabilities capabilities = new Capabilities();
     53            capabilities.put("blacklist", "regex", ".*blacklisted.*");
     54            capabilities.put("blacklist", "regex", "^https?://(invalid|bad).*");
     55            capabilities.put("version", "minimum", "0.6");
     56            capabilities.put("version", "maximum", "0.6");
     57            return capabilities;
     58        }
     59    }
     60
     61    @Override
     62    public void createPrimitive(IPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
     63        throw new UnsupportedOperationException("Not implemented");
     64    }
     65
     66    @Override
     67    public void modifyPrimitive(IPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
     68        throw new UnsupportedOperationException("Not implemented");
     69    }
     70
     71    @Override
     72    public void deletePrimitive(OsmPrimitive osm, ProgressMonitor monitor) throws OsmTransferException {
     73        throw new UnsupportedOperationException("Not implemented");
     74    }
     75
     76    @Override
     77    public void openChangeset(Changeset changeset, ProgressMonitor progressMonitor) throws OsmTransferException {
     78        throw new UnsupportedOperationException("Not implemented");
     79    }
     80
     81    @Override
     82    public void updateChangeset(Changeset changeset, ProgressMonitor monitor) throws OsmTransferException {
     83        throw new UnsupportedOperationException("Not implemented");
     84    }
     85
     86    @Override
     87    public void closeChangeset(Changeset changeset, ProgressMonitor monitor) throws OsmTransferException {
     88        throw new UnsupportedOperationException("Not implemented");
     89    }
     90
     91    @Override
     92    public Note createNote(LatLon latlon, String text, ProgressMonitor monitor) throws OsmTransferException {
     93        throw new UnsupportedOperationException("Not implemented");
     94    }
     95
     96    @Override
     97    public Note addCommentToNote(Note note, String comment, ProgressMonitor monitor) throws OsmTransferException {
     98        throw new UnsupportedOperationException("Not implemented");
     99    }
     100
     101    @Override
     102    public Note closeNote(Note note, String closeMessage, ProgressMonitor monitor) throws OsmTransferException {
     103        throw new UnsupportedOperationException("Not implemented");
     104    }
     105
     106    @Override
     107    public Note reopenNote(Note note, String reactivateMessage, ProgressMonitor monitor) throws OsmTransferException {
     108        throw new UnsupportedOperationException("Not implemented");
     109    }
     110
     111    /**
     112     * Gets and caches an instance of this API.
     113     * @return The API intance. Always the same object.
     114     */
     115    public static synchronized FakeOsmApi getInstance() {
     116        if (instance == null) {
     117            instance = new FakeOsmApi();
     118            cacheInstance(instance);
     119        }
     120        return instance;
     121    }
     122}
  • new file test/unit/org/openstreetmap/josm/testutils/JOSMTestRules.java

    diff --git a/test/unit/org/openstreetmap/josm/testutils/JOSMTestRules.java b/test/unit/org/openstreetmap/josm/testutils/JOSMTestRules.java
    new file mode 100644
    index 0000000..47a25ce
    - +  
     1// License: GPL. For details, see LICENSE file.
     2package org.openstreetmap.josm.testutils;
     3
     4import java.io.File;
     5import java.io.IOException;
     6
     7import org.junit.rules.TemporaryFolder;
     8import org.junit.rules.TestRule;
     9import org.junit.rules.Timeout;
     10import org.junit.runner.Description;
     11import org.junit.runners.model.InitializationError;
     12import org.junit.runners.model.Statement;
     13import org.openstreetmap.josm.Main;
     14import org.openstreetmap.josm.gui.layer.MainLayerManager;
     15import org.openstreetmap.josm.gui.util.GuiHelper;
     16import org.openstreetmap.josm.io.OsmApi;
     17import org.openstreetmap.josm.io.OsmApiInitializationException;
     18import org.openstreetmap.josm.io.OsmTransferCanceledException;
     19import org.openstreetmap.josm.tools.I18n;
     20
     21/**
     22 * This class runs a test in an environment that resembles the one used by the JOSM main application.
     23 * <p>
     24 * The environment is reset before every test. You can specify the components to which you need access using the methods of this class.
     25 * For example, invoking {@link #preferences()} gives you access to the (default) preferences.
     26 *
     27 * @author Michael Zangl
     28 * @since xxx
     29 */
     30public class JOSMTestRules implements TestRule {
     31    //We should make this the default when running from ant: Timeout.seconds(10);
     32    private Timeout timeout = null;
     33    private TemporaryFolder josmHome;
     34    private boolean usePreferences = false;
     35    private APIType useAPI = APIType.NONE;
     36    private String i18n = null;
     37    private boolean platform;
     38
     39    /**
     40     * Disable the default timeout for this test. Use with care.
     41     * @return this instance, for easy chaining
     42     */
     43    public JOSMTestRules noTimeout() {
     44        timeout = null;
     45        return this;
     46    }
     47
     48    /**
     49     * Set a timeout for all tests in this class. Local method timeouts may only reduce this timeout.
     50     * @param millis The timeout duration in milliseconds.
     51     * @return this instance, for easy chaining
     52     */
     53    public JOSMTestRules timeout(int millis) {
     54        timeout = Timeout.millis(millis);
     55        return this;
     56    }
     57
     58    /**
     59     * Enable the use of default preferences.
     60     * @return this instance, for easy chaining
     61     */
     62    public JOSMTestRules preferences() {
     63        josmHome();
     64        usePreferences = true;
     65        return this;
     66    }
     67
     68    /**
     69     * Set JOSM home to a valid, empty directory.
     70     * @return this instance, for easy chaining
     71     */
     72    private JOSMTestRules josmHome() {
     73        josmHome = new TemporaryFolder();
     74        return this;
     75    }
     76
     77    /**
     78     * Enables the i18n module for this test in english.
     79     * @return this instance, for easy chaining
     80     */
     81    public JOSMTestRules i18n() {
     82        return i18n("en");
     83    }
     84
     85    /**
     86     * Enables the i18n module for this test.
     87     * @param language The language to use.
     88     * @return this instance, for easy chaining
     89     */
     90    public JOSMTestRules i18n(String language) {
     91        i18n = language;
     92        return this;
     93    }
     94
     95    /**
     96     * Enable {@link Main#platform} global variable.
     97     * @return this instance, for easy chaining
     98     */
     99    public JOSMTestRules platform() {
     100        platform = true;
     101        return this;
     102    }
     103
     104    /**
     105     * Enable the dev.openstreetmap.org API for this test.
     106     * @return this instance, for easy chaining
     107     */
     108    public JOSMTestRules devAPI() {
     109        preferences();
     110        useAPI = APIType.DEV;
     111        return this;
     112    }
     113
     114    /**
     115     * Use the {@link FakeOsmApi} for testing.
     116     * @return this instance, for easy chaining
     117     */
     118    public JOSMTestRules fakeAPI() {
     119        useAPI = APIType.FAKE;
     120        return this;
     121    }
     122
     123    @Override
     124    public Statement apply(final Statement base, Description description) {
     125        Statement statement = new Statement() {
     126            @Override
     127            public void evaluate() throws Throwable {
     128                before();
     129                try {
     130                    base.evaluate();
     131                } finally {
     132                    after();
     133                }
     134            }
     135        };
     136        if (timeout != null) {
     137            statement = timeout.apply(statement, description);
     138        }
     139        if (josmHome != null) {
     140            statement = josmHome.apply(statement, description);
     141        }
     142        return statement;
     143    }
     144
     145    /**
     146     * Set up before running a test
     147     * @throws InitializationError If an error occured while creating the required environment.
     148     */
     149    protected void before() throws InitializationError {
     150        // Tests are running headless by default.
     151        System.setProperty("java.awt.headless", "true");
     152
     153        // Set up i18n
     154        if (i18n != null) {
     155            I18n.set(i18n);
     156        }
     157
     158        // Add JOSM home
     159        if (josmHome != null) {
     160            try {
     161                File home = josmHome.newFolder();
     162                System.setProperty("josm.home", home.getAbsolutePath());
     163            } catch (IOException e) {
     164                throw new InitializationError(e);
     165            }
     166        }
     167
     168        // Add preferences
     169        if (usePreferences) {
     170            Main.initApplicationPreferences();
     171            Main.pref.enableSaveOnPut(false);
     172            // No pref init -> that would only create the preferences file.
     173            // We force the use of a wrong API server, just in case anyone attempts an upload
     174            Main.pref.put("osm-server.url", "http://invalid");
     175        }
     176
     177        // Set API
     178        if (useAPI == APIType.DEV) {
     179            Main.pref.put("osm-server.url", "http://api06.dev.openstreetmap.org/api");
     180        } else if (useAPI == APIType.FAKE) {
     181            FakeOsmApi api = FakeOsmApi.getInstance();
     182            Main.pref.put("osm-server.url", api.getServerUrl());
     183        }
     184
     185        // Initialize API
     186        if (useAPI != APIType.NONE) {
     187            try {
     188                OsmApi.getOsmApi().initialize(null);
     189            } catch (OsmTransferCanceledException | OsmApiInitializationException e) {
     190                throw new InitializationError(e);
     191            }
     192        }
     193
     194        // Set Platform
     195        if (platform) {
     196            Main.determinePlatformHook();
     197        }
     198    }
     199
     200    /**
     201     * Clean up after running a test
     202     */
     203    protected void after() {
     204        // Sync AWT Thread
     205        GuiHelper.runInEDTAndWait(new Runnable() {
     206            @Override
     207            public void run() {
     208            }
     209        });
     210        // Remove all layers
     211        MainLayerManager lm = Main.getLayerManager();
     212        while (!lm.getLayers().isEmpty()) {
     213            lm.removeLayer(lm.getLayers().get(0));
     214        }
     215
     216        // TODO: Remove global listeners and other global state.
     217
     218        Main.pref = null;
     219        Main.platform = null;
     220        // Parts of JOSM uses weak references - destroy them.
     221        System.gc();
     222    }
     223
     224    enum APIType {
     225        NONE, FAKE, DEV
     226    }
     227}