json/src/test/java/net/java/html/json/ModelTest.java
author Jaroslav Tulach <jtulach@netbeans.org>
Wed, 09 Dec 2015 23:58:27 +0100
changeset 1025 1122c615fffd
parent 951 5ce0aab2c03c
child 1026 cda94194f901
permissions -rw-r--r--
#257086: Use inPckName to propertly specify the name of the static method
     1 /**
     2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
     3  *
     4  * Copyright 2013-2014 Oracle and/or its affiliates. All rights reserved.
     5  *
     6  * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
     7  * Other names may be trademarks of their respective owners.
     8  *
     9  * The contents of this file are subject to the terms of either the GNU
    10  * General Public License Version 2 only ("GPL") or the Common
    11  * Development and Distribution License("CDDL") (collectively, the
    12  * "License"). You may not use this file except in compliance with the
    13  * License. You can obtain a copy of the License at
    14  * http://www.netbeans.org/cddl-gplv2.html
    15  * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
    16  * specific language governing permissions and limitations under the
    17  * License.  When distributing the software, include this License Header
    18  * Notice in each file and include the License file at
    19  * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
    20  * particular file as subject to the "Classpath" exception as provided
    21  * by Oracle in the GPL Version 2 section of the License file that
    22  * accompanied this code. If applicable, add the following below the
    23  * License Header, with the fields enclosed by brackets [] replaced by
    24  * your own identifying information:
    25  * "Portions Copyrighted [year] [name of copyright owner]"
    26  *
    27  * Contributor(s):
    28  *
    29  * The Original Software is NetBeans. The Initial Developer of the Original
    30  * Software is Oracle. Portions Copyright 2013-2014 Oracle. All Rights Reserved.
    31  *
    32  * If you wish your version of this file to be governed by only the CDDL
    33  * or only the GPL Version 2, indicate your decision by adding
    34  * "[Contributor] elects to include this software in this distribution
    35  * under the [CDDL or GPL Version 2] license." If you do not indicate a
    36  * single choice of license, a recipient has the option to distribute
    37  * your version of this file under either the CDDL, the GPL Version 2 or
    38  * to extend the choice of license to its licensees as provided above.
    39  * However, if you add GPL Version 2 code and therefore, elected the GPL
    40  * Version 2 license, then the option applies only if the new code is
    41  * made subject to such option by the copyright holder.
    42  */
    43 package net.java.html.json;
    44 
    45 import java.util.ArrayList;
    46 import java.util.Collections;
    47 import java.util.Iterator;
    48 import java.util.List;
    49 import java.util.ListIterator;
    50 import net.java.html.BrwsrCtx;
    51 import org.netbeans.html.context.spi.Contexts;
    52 import org.netbeans.html.json.spi.FunctionBinding;
    53 import org.netbeans.html.json.spi.PropertyBinding;
    54 import org.netbeans.html.json.spi.Technology;
    55 import static org.testng.Assert.assertEquals;
    56 import static org.testng.Assert.assertFalse;
    57 import static org.testng.Assert.assertNotNull;
    58 import static org.testng.Assert.assertNull;
    59 import static org.testng.Assert.assertTrue;
    60 import static org.testng.Assert.fail;
    61 import org.testng.annotations.BeforeMethod;
    62 import org.testng.annotations.Test;
    63 
    64 /**
    65  *
    66  * @author Jaroslav Tulach
    67  */
    68 @Model(className = "Modelik", targetId = "", properties = {
    69     @Property(name = "value", type = int.class),
    70     @Property(name = "count", type = int.class),
    71     @Property(name = "unrelated", type = long.class),
    72     @Property(name = "names", type = String.class, array = true),
    73     @Property(name = "values", type = int.class, array = true),
    74     @Property(name = "people", type = Person.class, array = true),
    75     @Property(name = "changedProperty", type=String.class)
    76 })
    77 public class ModelTest {
    78     private MockTechnology my;
    79     private Modelik model;
    80     private static Modelik leakedModel;
    81 
    82     @BeforeMethod
    83     public void createModel() {
    84         my = new MockTechnology();
    85         final BrwsrCtx c = Contexts.newBuilder().register(Technology.class, my, 1).build();
    86         model = Models.bind(new Modelik(), c);
    87     }
    88 
    89     @Test public void classGeneratedWithSetterGetter() {
    90         model.setValue(10);
    91         assertEquals(10, model.getValue(), "Value changed");
    92     }
    93 
    94     @Test public void computedMethod() {
    95         model.setValue(4);
    96         assertEquals(16, model.getPowerValue());
    97     }
    98 
    99     @Test public void equalsAndHashCode() {
   100         Modelik m1 = new Modelik(10, 20, 30, "changed", "firstName");
   101         Modelik m2 = new Modelik(10, 20, 30, "changed", "firstName");
   102 
   103         assertTrue(m1.equals(m2), "They are the same");
   104         assertEquals(m1.hashCode(), m2.hashCode(), "Hashcode is the same");
   105 
   106         m1.setCount(33);
   107 
   108         assertFalse(m1.equals(m2), "No longer the same");
   109         assertFalse(m1.hashCode() == m2.hashCode(), "No longe is hashcode is the same");
   110     }
   111 
   112     @Test public void arrayIsMutable() {
   113         assertEquals(model.getNames().size(), 0, "Is empty");
   114         model.getNames().add("Jarda");
   115         assertEquals(model.getNames().size(), 1, "One element");
   116     }
   117 
   118     @Test public void arrayChangesNotNotifiedUntilInitied() {
   119         model.getNames().add("Hello");
   120         assertTrue(my.mutated.isEmpty(), "No change now " + my.mutated);
   121         model.getNames().remove("Hello");
   122         assertTrue(my.mutated.isEmpty(), "No change still " + my.mutated);
   123         assertTrue(model.getNames().isEmpty(), "No empty");
   124     }
   125 
   126     @Test public void arrayChangesNotified() {
   127         Models.applyBindings(model);
   128         model.getNames().add("Hello");
   129 
   130         assertFalse(my.mutated.isEmpty(), "There was a change" + my.mutated);
   131         assertTrue(my.mutated.contains("names"), "Change in names property: " + my.mutated);
   132 
   133         my.mutated.clear();
   134 
   135         Iterator<String> it = model.getNames().iterator();
   136         assertEquals(it.next(), "Hello");
   137         it.remove();
   138 
   139         assertFalse(my.mutated.isEmpty(), "There was a change" + my.mutated);
   140         assertTrue(my.mutated.contains("names"), "Change in names property: " + my.mutated);
   141 
   142         my.mutated.clear();
   143 
   144         ListIterator<String> lit = model.getNames().listIterator();
   145         lit.add("Jarda");
   146 
   147         assertFalse(my.mutated.isEmpty(), "There was a change" + my.mutated);
   148         assertTrue(my.mutated.contains("names"), "Change in names property: " + my.mutated);
   149     }
   150 
   151     @Test public void autoboxedArray() {
   152         model.getValues().add(10);
   153 
   154         assertEquals(model.getValues().get(0), Integer.valueOf(10), "Really ten");
   155     }
   156 
   157     @Test public void derivedArrayProp() {
   158         model.applyBindings();
   159         model.setCount(10);
   160 
   161         List<String> arr = model.getRepeat();
   162         assertEquals(arr.size(), 10, "Ten items: " + arr);
   163 
   164         my.mutated.clear();
   165 
   166         model.setCount(5);
   167 
   168         arr = model.getRepeat();
   169         assertEquals(arr.size(), 5, "Five items: " + arr);
   170 
   171         assertEquals(my.mutated.size(), 2, "Two properties changed: " + my.mutated);
   172         assertTrue(my.mutated.contains("repeat"), "Array is in there: " + my.mutated);
   173         assertTrue(my.mutated.contains("count"), "Count is in there: " + my.mutated);
   174     }
   175 
   176     @Test public void derivedArrayPropChange() {
   177         model.applyBindings();
   178         model.setCount(5);
   179 
   180         List<String> arr = model.getRepeat();
   181         assertEquals(arr.size(), 5, "Five items: " + arr);
   182 
   183         model.setRepeat(10);
   184         assertEquals(model.getCount(), 10, "Changing repeat changes count");
   185     }
   186 
   187     @Test public void derivedPropertiesAreNotified() {
   188         model.applyBindings();
   189 
   190         model.setValue(33);
   191 
   192         // not interested in change of this property
   193         my.mutated.remove("changedProperty");
   194 
   195         assertEquals(my.mutated.size(), 2, "Two properties changed: " + my.mutated);
   196         assertTrue(my.mutated.contains("powerValue"), "Power value is in there: " + my.mutated);
   197         assertTrue(my.mutated.contains("value"), "Simple value is in there: " + my.mutated);
   198 
   199         my.mutated.clear();
   200 
   201         model.setUnrelated(44);
   202 
   203 
   204         // not interested in change of this property
   205         my.mutated.remove("changedProperty");
   206         assertEquals(my.mutated.size(), 1, "One property changed: " + my.mutated);
   207         assertTrue(my.mutated.contains("unrelated"), "Its name is unrelated");
   208     }
   209 
   210     @Test public void computedPropertyCannotWriteToModel() {
   211         leakedModel = model;
   212         try {
   213             String res = model.getNotAllowedWrite();
   214             fail("We should not be allowed to write to the model: " + res);
   215         } catch (IllegalStateException ex) {
   216             // OK, we can't read
   217         }
   218     }
   219 
   220     @Test public void computedPropertyCannotReadToModel() {
   221         leakedModel = model;
   222         try {
   223             String res = model.getNotAllowedRead();
   224             fail("We should not be allowed to read from the model: " + res);
   225         } catch (IllegalStateException ex) {
   226             // OK, we can't read
   227         }
   228     }
   229 
   230     @OnReceive(url = "{protocol}://{host}?query={query}", data = Person.class, onError = "errorState")
   231     static void loadPeople(Modelik thiz, People p) {
   232         Modelik m = null;
   233         m.applyBindings();
   234         m.loadPeople("http", "apidesign.org", "query", new Person());
   235     }
   236 
   237     static void errorState(Modelik thiz, Exception ex) {
   238 
   239     }
   240 
   241     @OnReceive(url="{url}", headers={
   242         "Easy: {easy}",
   243         "H-a+r!d?e.r: {harder}",
   244         "H-a+r!d?e's\"t: {harder}",
   245         "Repeat-ed: {rep}",
   246         "Repeat+ed: {rep}",
   247         "Same-URL: {url}"
   248     })
   249     static void fetchPeopleWithHeaders(Modelik model, People p) {
   250         model.fetchPeopleWithHeaders("url", "easy", "harder", "rep");
   251     }
   252 
   253     @OnReceive(url = "{protocol}://{host}?callback={back}&query={query}", jsonp = "back")
   254     static void loadPeopleViaJSONP(Modelik thiz, People p) {
   255         Modelik m = null;
   256         m.applyBindings();
   257         m.loadPeopleViaJSONP("http", "apidesign.org", "query");
   258     }
   259 
   260     @OnReceive(url = "{rep}://{rep}")
   261     static void repeatedTest(Modelik thiz, People p) {
   262         thiz.repeatedTest("justOneParameterRep");
   263     }
   264 
   265     @Function
   266     static void doSomething() {
   267     }
   268 
   269     @ComputedProperty(write = "setPowerValue")
   270     static int powerValue(int value) {
   271         return value * value;
   272     }
   273 
   274     static void setPowerValue(Modelik m, int value) {
   275         m.setValue((int)Math.sqrt(value));
   276     }
   277 
   278     @OnPropertyChange({ "powerValue", "unrelated" })
   279     static void aPropertyChanged(Modelik m, String name) {
   280         m.setChangedProperty(name);
   281     }
   282 
   283     @OnPropertyChange({ "values" })
   284     static void anArrayPropertyChanged(String name, Modelik m) {
   285         m.setChangedProperty(name);
   286     }
   287 
   288     @Test public void changeAnything() {
   289         model.setCount(44);
   290         assertNull(model.getChangedProperty(), "No observed value change");
   291     }
   292     @Test public void changeValue() {
   293         model.setValue(33);
   294         assertEquals(model.getChangedProperty(), "powerValue", "power property changed");
   295     }
   296     @Test public void changePowerValue() {
   297         model.setValue(3);
   298         assertEquals(model.getPowerValue(), 9, "Square");
   299         model.setPowerValue(16);
   300         assertEquals(model.getValue(), 4, "Square root");
   301         assertEquals(model.getPowerValue(), 16, "Square changed");
   302     }
   303     @Test public void changeUnrelated() {
   304         model.setUnrelated(333);
   305         assertEquals(model.getChangedProperty(), "unrelated", "unrelated changed");
   306     }
   307 
   308     @Test public void changeInArray() {
   309         model.getValues().add(10);
   310         assertNull(model.getChangedProperty(), "No change before applyBindings");
   311         model.applyBindings();
   312         model.getValues().add(10);
   313         assertEquals(model.getChangedProperty(), "values", "Something added into the array");
   314     }
   315 
   316     @ComputedProperty
   317     static String notAllowedRead() {
   318         return "Not allowed callback: " + leakedModel.getUnrelated();
   319     }
   320 
   321     @ComputedProperty
   322     static String notAllowedWrite() {
   323         leakedModel.setUnrelated(11);
   324         return "Not allowed callback!";
   325     }
   326 
   327     @ComputedProperty(write="parseRepeat")
   328     static List<String> repeat(int count) {
   329         return Collections.nCopies(count, "Hello");
   330     }
   331     static void parseRepeat(Modelik m, Object v) {
   332         m.setCount((Integer)v);
   333     }
   334 
   335     public @Test void hasPersonPropertyAndComputedFullName() {
   336         List<Person> arr = model.getPeople();
   337         assertEquals(arr.size(), 0, "By default empty");
   338         Person p = null;
   339         if (p != null) {
   340             String fullNameGenerated = p.getFullName();
   341             assertNotNull(fullNameGenerated);
   342         }
   343     }
   344 
   345     public @Test void computedListIsOfTypeString() {
   346         Person p = new Person("1st", "2nd", Sex.MALE);
   347         String first = p.getBothNames().get(0);
   348         String last = p.getBothNames().get(1);
   349         assertEquals(first, "1st");
   350         assertEquals(last, "2nd");
   351     }
   352     
   353     @Model(className = "Inner", properties = {
   354         @Property(name = "x", type = int.class)
   355     })
   356     static final class InnerCntrl {
   357         @OnPropertyChange("x")
   358         static void increment(Inner model) {
   359             model.setX(model.getX() + 1);
   360         }
   361     }
   362 
   363     private static class MockTechnology implements Technology<Object> {
   364         private final List<String> mutated = new ArrayList<String>();
   365 
   366         @Override
   367         public Object wrapModel(Object model) {
   368             return this;
   369         }
   370 
   371         @Override
   372         public void valueHasMutated(Object data, String propertyName) {
   373             mutated.add(propertyName);
   374         }
   375 
   376         @Override
   377         public void bind(PropertyBinding b, Object model, Object data) {
   378         }
   379 
   380         @Override
   381         public void expose(FunctionBinding fb, Object model, Object d) {
   382         }
   383 
   384         @Override
   385         public void applyBindings(Object data) {
   386         }
   387 
   388         @Override
   389         public Object wrapArray(Object[] arr) {
   390             return arr;
   391         }
   392 
   393         @Override
   394         public <M> M toModel(Class<M> modelClass, Object data) {
   395             return modelClass.cast(data);
   396         }
   397 
   398         @Override
   399         public void runSafe(Runnable r) {
   400             throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
   401         }
   402     }
   403 }