File: PreferenceTest.java

package info (click to toggle)
mauve 20120103-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 28,504 kB
  • sloc: java: 250,155; sh: 2,834; xml: 208; makefile: 66
file content (496 lines) | stat: -rw-r--r-- 14,164 bytes parent folder | download | duplicates (5)
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
/*
 * PreferenceTest.java -- simple test for java.utils.prefs Copyright (C) 2006
 * Lima Software.
 * 
 * This file is part of Mauve.
 * 
 * Mauve is free software; you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2, or (at your option) any later version.
 * 
 * Mauve is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * Mauve; see the file COPYING. If not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 * 
 */

// Tags: JDK1.4
package gnu.testlet.java.util.prefs;

import gnu.testlet.TestHarness;
import gnu.testlet.Testlet;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import java.util.prefs.BackingStoreException;
import java.util.prefs.NodeChangeEvent;
import java.util.prefs.NodeChangeListener;
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import java.util.prefs.Preferences;

/**
 * This simple test just read and write a set of preference. Does not assume a
 * particular backend.
 * 
 * @author Mario Torre <neugens@limasoftware.net>
 */
public class PreferenceTest implements Testlet
{
  /**
   * The expected full name of this preference node. <strong>Note:</strong>
   * change it if you move this class, it always reflects the package name.
   */
  private static final String FULL_PATH = "/gnu/testlet/java/util/prefs";

  /**
   * Default key used for tests.
   */
  private static final String KEY = "AppName";

  /**
   * Default value for the test key.
   */
  private static final String VALUE = "GNU Classpath - Preference API Test Case";

  /**
   * Defines if we want debug information on the default debug log or not.
   * Enable the if you need it or leave disabled for normal tests.
   */
  private static final boolean DEBUG = false;

  /* Test Harness */
  protected TestHarness harness = null;

  /** Preference */
  private Preferences prefs = null;

  public void test(TestHarness harness)
  {
    this.harness = harness;

    // initiliaze tests, call it before any other method of this class
    setup();

    if (DEBUG) printInfo();

    // run tests
    testAbsolutePath();

    // clear the preference tree, to be sure it does not contains
    // keys we will use
    testClear();

    testPut();
    testByte();
    testBoolean();
    testSpecialCharacters();
    
    testListener();
    testChildren();
  }

  /**
   * Setup the preference api backend.
   */
  private void setup()
  {
    // System.setProperty("java.util.prefs.PreferencesFactory",
    // "gnu.java.util.prefs.GConfBasedFactory");

    this.prefs = Preferences.userNodeForPackage(PreferenceTest.class);
  }

  private void testAbsolutePath()
  {
    this.harness.checkPoint("absolutePath()");

    String absolutePath = this.prefs.absolutePath();
    print("Absolute path: " + absolutePath);

    this.harness.check(FULL_PATH.compareTo(absolutePath) == 0);
  }

  private void testClear()
  {
    this.harness.checkPoint("testClear()");

    try
      {
        this.prefs.clear();
      }
    catch (BackingStoreException e)
      {
        print(e.getLocalizedMessage());
        this.harness.fail("testClear()");
      }

    this.harness.check(true);
  }

  /**
   * Put the default key on the preference node, then get it and check the
   * result to see if the preference api is actually capable of storing
   * preferences.
   */
  private void testPut()
  {
    this.harness.checkPoint("testPut()");

    this.prefs.put(KEY, VALUE);

    // suggest a sync to try to avoid memory caching.
    try
      {
        this.prefs.sync();

      }
    catch (BackingStoreException e)
      {
        print(e.getLocalizedMessage());
        this.harness.fail("testPut(), call to sync");
      }

    String value
      = this.prefs.get(KEY,
                       "Wrong value for key: " + KEY + ", expected: " + VALUE);

    print("Key (" + KEY + "): " + value);
    this.harness.check(VALUE.compareTo(value) == 0);
  }

  /**
   * Add a series of children to this node, put some preferences inside them and
   * retrieve everything, checking that the preference backend correctly handles
   * the tree structure of the entries under the current node. <strong>Note</strong>:
   * this test removes the preference node.
   */
  private void testChildren()
  {
    this.harness.checkPoint("testChildren()");

    String absolutePath = null;

    // add 3 new nodes, these will be direct children of the current node

    // node 1
    Preferences pref1 = this.prefs.node("children_1");
    this.harness.check("children_1".compareTo(pref1.name()) == 0);
    absolutePath = pref1.absolutePath();
    this.harness
        .check((FULL_PATH + "/children_1").compareTo(absolutePath) == 0);

    // node 2
    Preferences pref2 = this.prefs.node("children_2");
    this.harness.check("children_2".compareTo(pref2.name()) == 0);
    absolutePath = pref2.absolutePath();
    this.harness
        .check((FULL_PATH + "/children_2").compareTo(absolutePath) == 0);

    // node 3
    Preferences pref3 = this.prefs.node("children_3");
    this.harness.check("children_3".compareTo(pref3.name()) == 0);
    absolutePath = pref3.absolutePath();
    this.harness
        .check((FULL_PATH + "/children_3").compareTo(absolutePath) == 0);

    // now add a preference key to each of these new nodes
    pref1.put("key1", "value1");
    pref2.put("key2", "value2");
    pref3.put("key3", "value3");

    // add a subnode for child #1
    Preferences child1 = pref1.node("subPreference1");
    this.harness.check("subPreference1".compareTo(child1.name()) == 0);
    absolutePath = child1.absolutePath();
    this.harness.check((FULL_PATH + "/children_1/" + "subPreference1")
        .compareTo(absolutePath) == 0);

    child1.put("key1-child1", "some value");

    // retrieve the list of children of the root node
    this.harness.checkPoint("testAddChildren() - check new children");
    String[] expResult = {
        "children_1", "children_2", "children_3"
    };
    if (!listChildren(this.prefs, expResult))
      {
        this.harness.fail("testAddChildren(), children listing error");
      }

    this.harness.checkPoint("testAddChildren() - check subnodes");
    expResult = new String[] {
      "subPreference1"
    };
    if (!listChildren(pref1, expResult))
      {
        this.harness.fail("testAddChildren(), children listing error");
      }

    // clean everything
    try
      {
        this.prefs.removeNode();
        this.prefs.flush();

      }
    catch (BackingStoreException e)
      {
        print(e.getLocalizedMessage());
        this.harness.fail("testAddChildren(), call to clear()");
      }

    // to check that the node is empty we simply call childrenNames on it
    // this operation should fail because the node does not exist anymore
    this.harness.checkPoint("testAddChildren() - checking emptyness");
    try
      {
        this.prefs.childrenNames();
        this.harness.fail("The node should not exist anymore!");
      }
    catch (IllegalStateException e)
      {
        this.harness.check(true);
      }
    catch (BackingStoreException e)
      {
        print(e.getLocalizedMessage());
        this.harness.fail("The node should not exist anymore!");
      }
  }

  private boolean listChildren(Preferences pref, String[] expResult)
  {
    boolean _res = false;

    try
      {
        String[] result = pref.childrenNames();

        print("Resuls length: " + result.length +
              ", expected: " + expResult.length);
      
        this.harness.check(result.length == expResult.length);

        for (int i = 0; i < expResult.length; i++)
          {
            print("result[" + i + "] = " + result[i] +
                  ", expected = " + expResult[i]);
            this.harness.check(result[i], expResult[i]);
          }

        _res = true;

      }
    catch (BackingStoreException e)
      {
        print(e.getLocalizedMessage());
        this.harness.fail("call to childrenNames()");
      }

    return _res;
  }

  private void testByte()
  {
    this.harness.checkPoint("testByte()");

    String string = "an array of bytes value";
    byte[] bytes = null;
    byte[] result = null;

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    ObjectOutputStream oStream;

    try
      {
        oStream = new ObjectOutputStream(stream);
        oStream.writeObject(string);
        bytes = stream.toByteArray();
        
        this.harness.checkPoint("testByte() - put byte array");
        prefs.putByteArray(KEY, bytes);
        
        this.harness.checkPoint("testByte() - get byte array");
        result = prefs.getByteArray(KEY, null);

        // this fails, but the result is correct when restoring the
        // String
        // this.harness.check(result, bytes);

        ByteArrayInputStream iStream = new ByteArrayInputStream(result);
        ObjectInputStream oiStream = new ObjectInputStream(iStream);
        String rString = (String) oiStream.readObject();

        print("Result: " + rString + ", expected: " + string);
        this.harness.check(rString, string);

      }
    catch (IOException e)
      {
        print(e.getLocalizedMessage());
        this.harness.fail("call to testByte() - IO Exception");
      }
    catch (ClassNotFoundException e)
      {
        print(e.getLocalizedMessage());
        this.harness.fail("call to testByte() - ClassNotFoundException");
      }
    }

  private void testBoolean()
  {
    this.harness.checkPoint("testBoolean()");

    String key = "boolean_key";
    String _true = "TrUe";

    // test "normal" booleans
    this.prefs.putBoolean(key, true);
    boolean result = this.prefs.getBoolean(key, false);

    this.harness.check(result, true);

    // test String as boolean
    this.prefs.remove(key);
    try
      {
        this.prefs.flush();
      }
    catch (BackingStoreException e)
      {
        print(e.getLocalizedMessage());
        this.harness.fail("call to testBoolean() - fail to flush");
      }

      this.prefs.put(key, _true);
      result = this.prefs.getBoolean(key, false);

      this.harness.check(result, true);
    }

  /**
   * This test is used by the GConf backend to test if it correctly handles
   * nodes that contains invalid characters.
   */
  private void testSpecialCharacters()
  {
    this.harness.checkPoint("testSpecialCharacters()");
    
    // try an invalid name as path
    Preferences _prefs = this.prefs.node("invalid children node");
    _prefs.put("Invalid Key", "An invalid key, on an invalid subnode");
    _prefs.put("Valid_Key", "A valid key, on an invalid subnode");
    
    String one = _prefs.get("Invalid Key", "unable to get the invalid key");
    String two = _prefs.get("Valid_Key", "unable to get the invalid key");
    
    this.harness.check(one, "An invalid key, on an invalid subnode");
    this.harness.check(two, "A valid key, on an invalid subnode");
    
    try
      {
        _prefs.flush();
        _prefs.removeNode();
      }
    catch (BackingStoreException e)
      {
        print(e.getLocalizedMessage());
        this.harness.fail("call to testSpecialCharacters() fail to removeNode");
      }
  }
  
  private void testListener()
  {
    this.harness.checkPoint("testListener()");

    PreferenceListener listener = new PreferenceListener();

    this.harness.checkPoint("testListener() - adding listeners");
    this.prefs.addNodeChangeListener(listener);
    this.prefs.addPreferenceChangeListener(listener);

    // store this, key, read it then remove it
    this.harness.checkPoint("testListener() - inserting key");

    this.prefs.put("new_key", "some value");
    String key = this.prefs.get("new_key", "Wrong! Wrong! Wrong!");
    this.harness.check(key, "some value");

    this.harness.checkPoint("testListener() - updating key");

    this.prefs.put("new_key", "some other value");
    key = this.prefs.get("new_key", "Wrong! Wrong! Wrong!");
    this.harness.check(key, "some other value");

    this.harness.checkPoint("testListener() - removing listeners");

    this.prefs.removeNodeChangeListener(listener);
    this.prefs.removePreferenceChangeListener(listener);

    this.harness.checkPoint("testListener() - removing key");
    this.prefs.remove("new_key");
  }

  /**
   * Prints on screen some information about the class we are about to test.
   * This can be useful for debugging, ant to check if a particoular backend is
   * enabled.
   */
  private void printInfo()
  {
    String backendName = System.getProperty(
        "java.util.prefs.PreferencesFactory",
        "No backend registered, using default backend");
    String vendor = System.getProperty("java.vendor");

    this.harness.debug(vendor);
    this.harness.debug(backendName);
  }

  private void print(String message)
  {
    if (DEBUG) harness.debug(message);
  }

  private class PreferenceListener implements NodeChangeListener,
      PreferenceChangeListener
  {
    public void childAdded(NodeChangeEvent event)
    {
      PreferenceTest.this.harness.check(true);

      print("Child added!");
      String name = event.getChild().name();
      print("name: " + name);
    }

    public void childRemoved(NodeChangeEvent event)
    {
      PreferenceTest.this.harness.check(true);

      print("Child removed!");
      String name = event.getChild().name();
      print("name: " + name);
    }

    public void preferenceChange(PreferenceChangeEvent event)
    {
      PreferenceTest.this.harness.check(true);

      print("Preference changed!");
      String name = event.getNode().name();
      String value = event.getNewValue();
      print("name: " + name);
      print("value: " + value);
    }
  }
}