google-code-export / gwt-test-utils

Automatically exported from code.google.com/p/gwt-test-utils
1 stars 0 forks source link

Browser.presskey can't add text at begin of textbox #145

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
1.test a textbox with text as "toto"
2.use Browser.pressKey to obtain "1toto"
3.you can't obtain "1toto" but only "toto1"

GWT2.4.0 with gwttestutil 0.39-SNAPSHOT

So, we can't add text in the begining of the textbox.

It's a big problem for me because I want test a special Datebox which draw 
__h__ and I need test 12h30 but I obtain __h__1230

Original issue reported on code.google.com by philippe...@gmail.com on 19 Jun 2012 at 9:04

GoogleCodeExporter commented 9 years ago

Original comment by gael.laz...@gmail.com on 21 Jun 2012 at 5:09

GoogleCodeExporter commented 9 years ago
I'm adding a Browser.addText(ValueBoxBase<?> valueBox, String text) which 
depends on ValueBoxBase.getCurrentPos() token. Stay tuned ;)

Original comment by gael.laz...@gmail.com on 29 Jun 2012 at 2:53

GoogleCodeExporter commented 9 years ago
In what version? 0.39-SNAPSHOT disappeared and 0.39 does not have this feature 
:(

Original comment by philippe...@gmail.com on 29 Jun 2012 at 3:19

GoogleCodeExporter commented 9 years ago
It is normal, I was actually implementing the feature (= status "started").
It's now available on the lastest 0.40-SNAPSHOT I've just deployed !

Could you please give it a try and let me know if it matches your needs ? 
Thanks !

FYI, the addText method passes the following unit tests : 

 @Test
  public void addText_delete_SelectedText() {
    // Arrange
    TextBox textBox = new TextBox();
    // must be attached to use "addText"
    RootPanel.get().add(textBox);
    textBox.setText("toto titi");
    // select "titi"
    textBox.setSelectionRange(5, 4);
    // Pre-Assert
    assertThat("titi").isEqualTo(textBox.getSelectedText());

    // Act
    Browser.addText(textBox, "tutu");

    // Assert
    assertThat(textBox.getText()).isEqualTo("toto tutu");
    assertThat(textBox.getCursorPos()).isEqualTo(9);
  }

  @Test
  public void addText_DoesNot_Fire_ValueChangeEvent() {
    // Arrange
    TextBox textBox = new TextBox();
    // must be attached to use "addText"
    RootPanel.get().add(textBox);

    textBox.addValueChangeHandler(new ValueChangeHandler<String>() {

      public void onValueChange(ValueChangeEvent<String> event) {
        fail("ValueChangeEvent should not be fired with Browser.addText(..)");
      }
    });

    // Act
    Browser.addText(textBox, "toto");

    // Assert
    assertEquals("toto", textBox.getText());
  }

  @Test
  public void addText_insertAtCursorPos() {
    // Arrange
    TextBox textBox = new TextBox();
    // must be attached to use "addText"
    RootPanel.get().add(textBox);

    textBox.setText("toto");
    // Pre-Assert
    assertThat(textBox.getCursorPos()).isEqualTo(4);

    // change the position
    textBox.setCursorPos(2);
    assertThat(textBox.getCursorPos()).isEqualTo(2);

    // Act
    Browser.addText(textBox, "titi");

    // Assert
    assertThat(textBox.getText()).isEqualTo("totitito");
    assertThat(textBox.getCursorPos()).isEqualTo(6);
  }

Original comment by gael.laz...@gmail.com on 30 Jun 2012 at 4:52

GoogleCodeExporter commented 9 years ago
I tested but it's don't work in my case.

public class HourBox extends MaskTextBox {

    /** The Constant WIDTH. */
    public static final String WIDTH = "6em";

    /** The Constant MASK. */
    protected static final String MASK = "__h__";

    /** The Constant SEPARATOR. */
    private static final String SEPARATOR = "h";

    /**
     * Instantiates a new hour box.
     */
    public HourBox() {
        this.setVisibleLength(5);
        this.setMaxLength(5);
        this.setValue(MASK);
    }

    /**
     * Instantiates a new hour box.
     * @param pTime
     *            the time
     */
    public HourBox(final String pTime) {
        this();
        this.setValue(pTime);
    }

    /**
     * Gets the hour.
     * @return the hour
     */
    public int getHour() {
        try {
            final String s = this.getValue().split(SEPARATOR)[0];
            final int i = Integer.parseInt(s);
            return i;
        } catch (final NumberFormatException e) {
            LoggerMgr.addError(Msgs.ERROR_MSG.invalidHour());
            throw e;
        }
    }

    /**
     * Gets the minutes.
     * @return the minutes
     */
    public int getMinutes() {
        try {
            final String s = this.getValue().split(SEPARATOR)[1];
            final int i = Integer.parseInt(s);
            return i;
        } catch (final NumberFormatException e) {
            LoggerMgr.addError(Msgs.ERROR_MSG.invalidHour());
            throw e;
        }
    }

    /**
     * Sets the value.
     * @param date
     *            the date
     */
    public void setValue(final Date date) {
        if (date == null) {
            this.setValue((String) null);
        } else {
            this.setValue(date.getHours() + SEPARATOR + date.getMinutes());
        }
    }

    /**
     * Sets the value.
     * @param hours
     *            the hours
     * @param minutes
     *            the minutes
     */
    public void setValue(final int hours, final int minutes) {
        this.setValue(hours + SEPARATOR + minutes);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setValue(final String pValue) {
        if (Utils.isEmpty(pValue)) {
            super.setValue(MASK);
        } else {
            super.setValue(pValue);
        }
    }

    /**
     * Update hours and minutes of the given date.
     * @param pDate
     *            the date to update
     */
    public void updateDate(final Date pDate) {
        if (pDate == null) {
            return;
        }

        pDate.setHours(this.getHour());
        pDate.setMinutes(this.getMinutes());
    }

    /**
     * Validate.
     * @return true, if successful
     */
    public boolean validate() {
        try {
            if (Utils.isEmpty(super.getValue())) {
                return true;
            }
            final int hour = this.getHour();
            final int minutes = this.getMinutes();
            return hour >= 0 && hour <= 23 && minutes >= 0 && minutes <= 59;
        } catch (final NumberFormatException e) {
            return false;
        } catch (final ArrayIndexOutOfBoundsException e) {
            return false;
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected String getMask() {
        return MASK;
    }
}

Here the unit test:

public final class HourBoxTest extends GwtTest {

    /** The Constant MODULE. */
    public static final String MODULE = "fr.grouperatp.ratp.applications.ads.Application";

    /** The hourbox. */
    private HourBox hourbox;

    /**
     * Instantiates a new hour box test.
     */
    public HourBoxTest() {
        super();
    }

    /**
     * Check click.
     */
    @Test
    public void checkMask() {
        RootPanel.get().add(this.hourbox);

        // On verifie que le masque est bien initialisé
        Assert.assertEquals(HourBox.MASK, this.hourbox.getText());
        // On vérifie que la valeur dans ce cas est bien vide
        Assert.assertEquals("", this.hourbox.getValue());

        Browser.pressKey(this.hourbox, '1');
        Browser.pressKey(this.hourbox, '2');
        Browser.pressKey(this.hourbox, '3');
        Browser.pressKey(this.hourbox, '4');

        Assert.assertEquals("12h34", this.hourbox.getText());

        System.out.println("Text : " + this.hourbox.getText());
        System.out.println("Value: " + this.hourbox.getValue());

        // A faire marcher lorsque le bug 145 sera résolu
        // http://code.google.com/p/gwt-test-utils/issues/detail?id=145
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getModuleName() {
        return HourBoxTest.MODULE;
    }

    /**
     * Inits the.
     * @throws Exception
     *             the exception
     */
    @Before
    public void init() throws Exception {
        // instanciate the composite
        this.hourbox = new HourBox();
    }
}

The result:

junit.framework.ComparisonFailure: null expected:<[12h]34> but was:<[_h__12]34>

Original comment by philippe...@gmail.com on 3 Jul 2012 at 3:46

GoogleCodeExporter commented 9 years ago
Could you please also post your MaskTextBox code ?

Original comment by gael.laz...@gmail.com on 3 Jul 2012 at 3:53

GoogleCodeExporter commented 9 years ago
/**
 * The Class MaskTextBox.
 * <p>
 * Cette classe gère la saisie utilisateur de manière à garder un masque de saisie. Voir HourBox et
 * son masque 12h30 -> __h__
 * </p>
 */
public abstract class MaskTextBox extends TextBox {

    /**
     * Instantiates a new mask text box.
     */
    public MaskTextBox() {
        this.addKeyDownHandler(new KeyDownHandler() {

            @Override
            public void onKeyDown(final KeyDownEvent event) {
                switch (event.getNativeKeyCode()) {
                case KeyCodes.KEY_BACKSPACE: {
                    final int cursorPos = MaskTextBox.this.getCursorPos();
                    if (cursorPos == 0) {
                        break;
                    }
                    final String paddedValue = MaskTextBox.super.getValue();
                    if (cursorPos <= MaskTextBox.this.getMask().length()) {
                        MaskTextBox.super.setValue(new StringBuilder(paddedValue).insert(cursorPos,
                                MaskTextBox.this.getMask().charAt(cursorPos - 1)).toString());
                        MaskTextBox.this.setCursorPos(cursorPos);
                    }
                }
                    break;
                case KeyCodes.KEY_DELETE: {
                    int cursorPos = MaskTextBox.this.getCursorPos();
                    final String paddedValue = MaskTextBox.super.getValue();
                    if (cursorPos < MaskTextBox.this.getMask().length()) {
                        MaskTextBox.super.setValue(new StringBuilder(paddedValue).insert(cursorPos,
                                MaskTextBox.this.getMask().charAt(cursorPos)).toString());
                        MaskTextBox.this.setCursorPos(++cursorPos);
                    }
                }
                    break;
                default:
                    break;
                }

            }
        });
        this.addKeyPressHandler(new KeyPressHandler() {

            @Override
            public void onKeyPress(final KeyPressEvent event) {
                // fix pour firefox
                // La cible de cette méthode n'est pas les bouton spéciaux
                // ff est le seul à passer par là alors qu'il ne devrait pas en passant un code 0
                // donc si le code est 0 on sort ->
                final char code = event.getCharCode();
                if (code == 0) {
                    return;
                } // fin fix pour firefox
                final String value = MaskTextBox.super.getValue();
                int cursorPos = MaskTextBox.this.getCursorPos();
                while (cursorPos < value.length()
                        && event.getCharCode() != MaskTextBox.this.getMask().charAt(cursorPos)
                        && '_' != MaskTextBox.this.getMask().charAt(cursorPos)) {
                    cursorPos++;
                }
                if (cursorPos < value.length()) {
                    MaskTextBox.super.setValue(new StringBuilder(value).deleteCharAt(cursorPos)
                            .toString());
                }
                MaskTextBox.this.setCursorPos(cursorPos);
            }
        });
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getValue() {
        final String value = super.getValue();
        final int lastEnt = value.indexOf("_");
        if (lastEnt != -1) {
            return value.substring(0, lastEnt);
        }
        return value;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setValue(final String value) {
        if (value.isEmpty()) {
            super.setValue(this.getMask());
        } else {
            super.setValue(value);
        }
    }

    /**
     * Gets the mask.
     * @return the mask
     */
    protected abstract String getMask();

}

Original comment by philippe...@gmail.com on 4 Jul 2012 at 6:35

GoogleCodeExporter commented 9 years ago
I've just deployed a new 0.40-SNAPSHOT with a fix for Browser.pressKey(..), 
which now requires a ValueBoxBase as first parameter. The Browser.addText(..) 
relies on the new implementation of the pressKey method.

Your test case passes well :-)

Before getting the lastest snasphot, you should read this page carefully : 
http://code.google.com/p/gwt-test-utils/wiki/MigrationTo040

Could you please give it a try and post some feedback ?

Original comment by gael.laz...@gmail.com on 8 Jul 2012 at 12:21