package nxm.sys.test.junit.lib;

import nxm.sys.lib.*;
import nxm.sys.test.junit.NMTestCase;

/** This will test the Dictionary class.
    @author Neon Ngo
    @since NeXtMidas 2.9.0
    @version $Id: DictionaryTest.java,v 1.9 2015/12/22 16:36:00 ntn Exp $
 */
public final class DictionaryTest extends NMTestCase {
  private Midas M;
  private static final String NON_EXISTENT_DIR = "/temp/NON_EXISTENT_PATH/";

  /** public constructor to allow running this test case directly with JUnit. */
  public DictionaryTest (String methodName) { this(methodName, null); }

  /** This constructor is required by NeXtMidas Unit Testing framework.
      @param methodName The name of the method being called.
      @param midas      The midas context to use when running the tests.
   */
  public DictionaryTest(String methodName, Midas midas) {
    super(methodName, midas);
    M = midas;
  }

  public void testFindPercentMacros () {
    // test BUG 2281 MENU: ERROR when listing percent macros and HOMEPATH points to nonExisting directory
    if (M == null) {
      warn("SKIPPING find percent macros test since there is no Midas context.");
      return;
    }
    final String origHomePath = M.getResults().getS("AUX.HOMEPATH");
    M.getResults().put("AUX.HOMEPATH", NON_EXISTENT_DIR);

    try {
      info("!!!!! It is ok to see a warning below: Unable to find percent macros... !!!!!");
      String[] retStrArray = Dictionary.findPercentMacros(M);

      M.getResults().put("AUX.HOMEPATH", origHomePath); // restore old homepath
      assertNotNull("Returned array should not be null", retStrArray); // check not null for BUG 2281
      assertEquals("Returned array should be empty (length==0) for invalid HOMEPATH", 0, retStrArray.length);
    } catch (SecurityException se) {
      // NTN: this is OK, it happens under Java Web Start where the JVM sandbox is more restricting
      info("Unable to test find percent macros from invalid HOMEPATH: "+se);
    }
    // end of BUG 2281 test case
  }

  /**
     Test that the Dictionary entry array is resized properly.

     Test the case where the new entry that should trigger resizing will be the last alphabetically
     (Since 3.5.2 - for bug 2844, which was fixed in 3.5.1)
   */
  public void testInsert () {
    try {
      Dictionary testDictionary = new Dictionary();
      String[] smallEntryTable = {null, null};
      testDictionary.fromArray(smallEntryTable);
      testDictionary.insert("FASTCORRELATE;DSP:5,P,3,IN=,FIR=,OUT=,");
      testDictionary.insert("FDFILTER;DSP:6,P,3,IN=,FIR=,OUT=");
      testDictionary.insert("MORPHDEMO;DSP:9,M,2,IN=USCONT(500:+1),OUT=MORPHOUT");
    } catch (ArrayIndexOutOfBoundsException aiobe){
      fail("insert(Srting) - entry table did not expand properly: " + aiobe);
    }
  }
}
