Skip to content

Commit

Permalink
fix: Always make sure we put valid utf8-encoded strings into attribut…
Browse files Browse the repository at this point in the history
…e values (#661)
  • Loading branch information
mykola-mokhnach authored Sep 3, 2024
1 parent 5dc68da commit 1151461
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
14 changes: 13 additions & 1 deletion app/src/main/java/io/appium/uiautomator2/utils/XMLHelpers.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import androidx.annotation.Nullable;

import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;

public abstract class XMLHelpers {
Expand Down Expand Up @@ -50,7 +51,18 @@ public static String toNodeName(String str) {
@Nullable
public static String toSafeString(@Nullable Object source, String replacement) {
return source == null ? null : XML10_PATTERN
.matcher(String.valueOf(source))
.matcher(toSafeUtf8String(String.valueOf(source)))
.replaceAll(replacement);
}

@Nullable
public static String toSafeUtf8String(@Nullable String source) {
if (source == null) {
return null;
}

// This method always replaces malformed-input and unmappable-character sequences
// with this charset's default replacement byte array.
return new String(source.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@

import static org.junit.Assert.assertEquals;

import static io.appium.uiautomator2.utils.XMLHelpers.toSafeString;

import android.os.SystemClock;

import java.io.ByteArrayInputStream;
Expand Down Expand Up @@ -238,6 +240,12 @@ private static List<Element> findNodesUsingXpath1(String xml, String xpathSelect
}
}

@Test
public void createsSafeXmlString() {
String text = toSafeString("°C\u000b", "?");
assertEquals(text, "°C?");
}

@Test
public void parsesComplexXpath1() {
String query = "(//android.widget.TextView[@text='some, text']/following::android.widget.ImageButton)[1]";
Expand Down

0 comments on commit 1151461

Please sign in to comment.