Skip to content

Commit

Permalink
Merge pull request #214 from Countly/views-merger
Browse files Browse the repository at this point in the history
[Java] safe id generator (#213)
  • Loading branch information
arifBurakDemiray authored Jan 9, 2024
2 parents 7a4562b + d450b14 commit 23064cf
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 25 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package ly.count.sdk.java.internal;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class ScenarioUtilsTests {

/**
* "safeRandomVal"
* ### 001_validatingIDGenerator
* <p>
* testing the ID generator function that is used for events and views
* <p>
* Generate 2 values
* <p>
* they should be different.
* They should be 21 chars long.
* They should contain on base64 characters. first 8 one is base64 string and last 13 one is timestamp
*
* @throws NumberFormatException for parsing part 2
*/
@Test
public void _001_validatingIDGenerator() throws NumberFormatException {
String val1 = Utils.safeRandomVal();
String val2 = Utils.safeRandomVal();

Assert.assertNotEquals(val2, val1);

TestUtils.validateSafeRandomVal(val1);
TestUtils.validateSafeRandomVal(val2);
}
}
25 changes: 0 additions & 25 deletions sdk-java/src/test/java/ly/count/sdk/java/internal/UtilsTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import ly.count.sdk.java.Config;
import org.junit.Assert;
import org.junit.Before;
Expand Down Expand Up @@ -561,27 +559,4 @@ public void readStream() {
Assert.assertNull(Utils.readStream(null, logger));
Assert.assertEquals(value, new String(Utils.readStream(new ByteArrayInputStream(value.getBytes()), logger)));
}

/**
* "safeRandomVal"
* An random value is generated and validated by the base64 regex, and consist of 2 parts
* Should return the string value generated by the algorithm and matches with the regex
*
* @throws NumberFormatException for parsing part 2
*/
@Test
public void safeRandomVal() throws NumberFormatException {
String val = Utils.safeRandomVal();
Pattern base64Pattern = Pattern.compile("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$");

String timestampStr = val.substring(val.length() - 13);
String base64Str = val.substring(0, val.length() - 13);

Matcher matcher = base64Pattern.matcher(base64Str);
if (matcher.matches()) {
Assert.assertTrue(Long.parseLong(timestampStr) > 0);
} else {
Assert.fail("No match for " + val);
}
}
}

0 comments on commit 23064cf

Please sign in to comment.