ApplicationsResourceTest.java 14.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
/*
 * Copyright 2015 Open Networking Laboratory
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.onosproject.rest;

import com.eclipsesource.json.Json;
import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.sun.jersey.api.client.WebResource;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Before;
import org.junit.Test;
import org.onlab.osgi.ServiceDirectory;
import org.onlab.osgi.TestServiceDirectory;
import org.onlab.rest.BaseResource;
import org.onosproject.app.ApplicationAdminService;
import org.onosproject.app.ApplicationService;
import org.onosproject.app.ApplicationState;
import org.onosproject.codec.CodecService;
import org.onosproject.codec.impl.ApplicationCodec;
import org.onosproject.codec.impl.CodecManager;
import org.onosproject.codec.impl.MockCodecContext;
import org.onosproject.core.Application;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.ApplicationRole;
import org.onosproject.core.CoreService;
import org.onosproject.core.DefaultApplication;
import org.onosproject.core.DefaultApplicationId;
import org.onosproject.core.Version;

import java.io.InputStream;
import java.net.URI;
import java.util.Optional;

import static org.easymock.EasyMock.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;

/**
 * Unit tests for applications REST APIs.
 */

public class ApplicationsResourceTest extends ResourceTest {

    private static class MockCodecContextWithAppService extends MockCodecContext {
        private ApplicationAdminService appService;

        MockCodecContextWithAppService(ApplicationAdminService appService) {
            this.appService = appService;
        }

        @Override
        @SuppressWarnings("unchecked")
        public <T> T getService(Class<T> serviceClass) {
            return (T) appService;
        }
    }

    private static class MockCodecContextWithCoreService extends MockCodecContext {
        private CoreService coreService;

        MockCodecContextWithCoreService(CoreService coreService) {
            this.coreService = coreService;
        }

        @Override
        @SuppressWarnings("unchecked")
        public <T> T getService(Class<T> serviceClass) {
            return (T) coreService;
        }
    }

    private ApplicationAdminService appService;
    private CoreService coreService;
    private ApplicationId id1 = new DefaultApplicationId(1, "app1");
    private ApplicationId id2 = new DefaultApplicationId(2, "app2");
    private ApplicationId id3 = new DefaultApplicationId(3, "app3");
    private ApplicationId id4 = new DefaultApplicationId(4, "app4");

    private static final URI FURL = URI.create("mvn:org.foo-features/1.2a/xml/features");
    private static final Version VER = Version.version(1, 2, "a", null);

    private Application app1 =
            new DefaultApplication(id1, VER, "title1",
                                   "desc1", "origin1", "category1", "url1",
                                   "readme1", new byte[0], ApplicationRole.ADMIN,
                                   ImmutableSet.of(), Optional.of(FURL),
                                   ImmutableList.of("My Feature"), ImmutableList.of());
    private Application app2 =
            new DefaultApplication(id2, VER, "title2",
                                   "desc2", "origin2", "category2", "url2",
                                   "readme2", new byte[0], ApplicationRole.ADMIN,
                                   ImmutableSet.of(), Optional.of(FURL),
                                   ImmutableList.of("My Feature"), ImmutableList.of());
    private Application app3 =
            new DefaultApplication(id3, VER, "title3",
                                   "desc3", "origin3", "category3", "url3",
                                   "readme3", new byte[0], ApplicationRole.ADMIN,
                                   ImmutableSet.of(), Optional.of(FURL),
                                   ImmutableList.of("My Feature"), ImmutableList.of());
    private Application app4 =
            new DefaultApplication(id4, VER, "title4",
                                   "desc4", "origin4", "category4", "url4",
                                   "readme4", new byte[0], ApplicationRole.ADMIN,
                                   ImmutableSet.of(), Optional.of(FURL),
                                   ImmutableList.of("My Feature"), ImmutableList.of());

    /**
     * Hamcrest matcher to check that an application representation in JSON matches
     * the actual device.
     */
    private static class AppJsonMatcher extends TypeSafeMatcher<JsonObject> {
        private final Application app;
        private String reason = "";

        public AppJsonMatcher(Application appValue) {
            app = appValue;
        }

        @Override
        public boolean matchesSafely(JsonObject jsonApp) {
            // check id
            short jsonId = (short) jsonApp.get("id").asInt();
            if (jsonId != app.id().id()) {
                reason = "id " + app.id().id();
                return false;
            }

            // check name
            String jsonName = jsonApp.get("name").asString();
            if (!jsonName.equals(app.id().name())) {
                reason = "name " + app.id().name();
                return false;
            }

            // check origin
            String jsonOrigin = jsonApp.get("origin").asString();
            if (!jsonOrigin.equals(app.origin())) {
                reason = "manufacturer " + app.origin();
                return false;
            }

            return true;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText(reason);
        }
    }

    /**
     * Factory to allocate an application matcher.
     *
     * @param app application object we are looking for
     * @return matcher
     */
    private static AppJsonMatcher matchesApp(Application app) {
        return new AppJsonMatcher(app);
    }

    /**
     * Hamcrest matcher to check that an application id representation in JSON.
     */
    private static final class AppIdJsonMatcher extends TypeSafeMatcher<JsonObject> {
        private final ApplicationId appId;
        private String reason = "";

        private AppIdJsonMatcher(ApplicationId appId) {
            this.appId = appId;
        }

        @Override
        protected boolean matchesSafely(JsonObject jsonAppId) {
            // check name
            String jsonName = jsonAppId.get("name").asString();
            if (!jsonName.equals(appId.name())) {
                reason = "name " + appId.name();
                return false;
            }

            return true;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText(reason);
        }
    }

    /**
     * Factory to allocate an application Id matcher.
     *
     * @param appId application Id object we are looking for
     * @return matcher
     */
    private static AppIdJsonMatcher matchesAppId(ApplicationId appId) {
        return new AppIdJsonMatcher(appId);
    }

    /**
     * Initializes test mocks and environment.
     */
    @Before
    public void setUpMocks() {
        appService = createMock(ApplicationAdminService.class);
        coreService = createMock(CoreService.class);

        expect(appService.getId("one"))
                .andReturn(id1)
                .anyTimes();
        expect(appService.getId("two"))
                .andReturn(id2)
                .anyTimes();
        expect(appService.getId("three"))
                .andReturn(id3)
                .anyTimes();
        expect(appService.getId("four"))
                .andReturn(id4)
                .anyTimes();

        expect(appService.getApplication(id3))
                .andReturn(app3)
                .anyTimes();
        expect(appService.getState(isA(ApplicationId.class)))
                .andReturn(ApplicationState.ACTIVE)
                .anyTimes();

        // Register the services needed for the test
        CodecManager codecService = new CodecManager();
        codecService.activate();
        ServiceDirectory testDirectory =
                new TestServiceDirectory()
                        .add(ApplicationAdminService.class, appService)
                        .add(ApplicationService.class, appService)
                        .add(CoreService.class, coreService)
                        .add(CodecService.class, codecService);

        BaseResource.setServiceDirectory(testDirectory);
    }

    /**
     * Tests a GET of all applications when no applications are present.
     */
    @Test
    public void getAllApplicationsEmpty() {
        expect(appService.getApplications())
                .andReturn(ImmutableSet.of());
        replay(appService);

        WebResource rs = resource();
        String response = rs.path("applications").get(String.class);
        assertThat(response, is("{\"applications\":[]}"));
        verify(appService);
    }

    /**
     * Tests a GET of all applications with data.
     */
    @Test
    public void getAllApplicationsPopulated() {
        expect(appService.getApplications())
                .andReturn(ImmutableSet.of(app1, app2, app3, app4));
        replay(appService);

        WebResource rs = resource();
        String response = rs.path("applications").get(String.class);
        assertThat(response, containsString("{\"applications\":["));

        JsonObject result = Json.parse(response).asObject();
        assertThat(result, notNullValue());

        assertThat(result.names(), hasSize(1));
        assertThat(result.names().get(0), is("applications"));

        JsonArray jsonApps = result.get("applications").asArray();
        assertThat(jsonApps, notNullValue());
        assertThat(jsonApps.size(), is(4));

        assertThat(jsonApps.get(0).asObject(), matchesApp(app1));
        assertThat(jsonApps.get(1).asObject(), matchesApp(app2));
        assertThat(jsonApps.get(2).asObject(), matchesApp(app3));
        assertThat(jsonApps.get(3).asObject(), matchesApp(app4));
        verify(appService);
    }

    /**
     * Tests a GET of a single application.
     */
    @Test
    public void getSingleApplication() {
        replay(appService);

        WebResource rs = resource();
        String response = rs.path("applications/three").get(String.class);

        JsonObject result = Json.parse(response).asObject();
        assertThat(result, notNullValue());

        assertThat(result, matchesApp(app3));
        verify(appService);
    }

    /**
     * Tests a DELETE of a single application - this should
     * attempt to uninstall it.
     */
    @Test
    public void deleteApplication() {
        appService.uninstall(id3);
        expectLastCall();

        replay(appService);

        WebResource rs = resource();
        rs.path("applications/three").delete();
        verify(appService);
    }

    /**
     * Tests a DELETE of a single active application - this should
     * attempt to uninstall it.
     */
    @Test
    public void deleteActiveApplication() {
        appService.deactivate(id3);
        expectLastCall();

        replay(appService);

        WebResource rs = resource();
        rs.path("applications/three/active").delete();
        verify(appService);
    }

    /**
     * Tests a POST operation to the "active" URL.  This should attempt to
     * activate the application.
     */
    @Test
    public void postActiveApplication() {
        appService.activate(id3);
        expectLastCall();

        replay(appService);

        WebResource rs = resource();
        rs.path("applications/three/active").post();
        verify(appService);
    }

    /**
     * Tests a POST operation.  This should attempt to
     * install the application.
     */
    @Test
    public void postApplication() {
        expect(appService.install(isA(InputStream.class)))
                .andReturn(app4)
                .once();

        replay(appService);

        ApplicationCodec codec = new ApplicationCodec();
        String app4Json = codec.encode(app4,
                                       new MockCodecContextWithAppService(appService))
                .asText();

        WebResource rs = resource();
        String response = rs.path("applications").post(String.class, app4Json);

        JsonObject result = Json.parse(response).asObject();
        assertThat(result, notNullValue());

        assertThat(result, matchesApp(app4));
        verify(appService);
    }

    /**
     * Tests a POST operation to register appid.
     */
    @Test
    public void postApplicationId() {
        expect(coreService.registerApplication("app1")).andReturn(id1).once();

        replay(coreService);

        WebResource rs = resource();
        rs.path("applications/app1/register").post();
        verify(coreService);
    }

    /**
     * Tests a GET of all application Ids.
     */
    @Test
    public void getAllApplicationIdsPopulated() {
        expect(coreService.getAppIds())
                .andReturn(ImmutableSet.of(id1, id2, id3, id4));
        replay(coreService);

        WebResource rs = resource();
        String response = rs.path("applications/ids").get(String.class);
        assertThat(response, containsString("{\"applicationIds\":["));

        JsonObject result = Json.parse(response).asObject();
        assertThat(result, notNullValue());

        assertThat(result.names(), hasSize(1));
        assertThat(result.names().get(0), is("applicationIds"));

        JsonArray jsonApps = result.get("applicationIds").asArray();
        assertThat(jsonApps, notNullValue());
        assertThat(jsonApps.size(), is(4));

        assertThat(jsonApps.get(0).asObject(), matchesAppId(id1));
        assertThat(jsonApps.get(1).asObject(), matchesAppId(id2));
        assertThat(jsonApps.get(2).asObject(), matchesAppId(id3));
        assertThat(jsonApps.get(3).asObject(), matchesAppId(id4));

        verify(coreService);
    }

}