diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 56acd51..7697c89 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,5 +1,5 @@ name: Release-To-OssRh -run-name: Deploy ${{github.event.release.tag_name}} to Sonatype by @${{ github.actor }} +run-name: Release ${{github.ref_name}} by @${{ github.event_name }} on: workflow_dispatch: @@ -16,7 +16,7 @@ on: required: false testVerbose: description: 'test output verbose' - default: true + default: false type: boolean required: false deployOssrh: @@ -44,7 +44,7 @@ jobs: ## chache asdf/, m2/repository - name: Cache Sdk & Repo id: cache-sdk-repo - uses: actions/cache@v3 + uses: actions/cache@v4 with: path: | ~/.asdf/ @@ -53,7 +53,7 @@ jobs: ## install jdk and maven - name: Install asdf & tools - uses: asdf-vm/actions/install@v2 + uses: asdf-vm/actions/install@v3 with: skip_install: ${{steps.cache-sdk-repo.outputs.cache-hit == 'true'}} @@ -76,6 +76,9 @@ jobs: echo $_ver echo "WINGS_VERSION=$_ver" >> "$GITHUB_OUTPUT" + echo "MVN_COVERAGE=${{ inputs.testCoverReport || github.event_name == 'release' }}" >> "$GITHUB_OUTPUT" + echo "MVN_DEPLOYRH=${{ inputs.deployOssrh || github.event_name == 'release' }}" >> "$GITHUB_OUTPUT" + mvn -v git --no-pager log --graph -10 --pretty=format:'%H - %ai %d %s' @@ -95,10 +98,10 @@ jobs: ## report if not release - name: Test Coverage ${{ steps.settings.outputs.WINGS_VERSION }} ${{ steps.settings.outputs.GIT_BRANCH }} - if: inputs.testCoverReport + if: steps.settings.outputs.MVN_COVERAGE run: > mvn - -P test + -P coverage -Dmaven.test.failure.ignore=${{ inputs.testFailureIgnore }} -DrepoToken=${{ secrets.COVERALLS_REPO_TOKEN }} clean test jacoco:report coveralls:report @@ -106,7 +109,7 @@ jobs: JAVA_HOME: ${{ steps.settings.outputs.JAVA_HOME }} ## import gpp private key - name: Import GPG key - if: inputs.deployOssrh + if: steps.settings.outputs.MVN_DEPLOYRH uses: crazy-max/ghaction-import-gpg@v6 with: gpg_private_key: ${{ secrets.MVN_GPG_SKEY }} @@ -114,7 +117,7 @@ jobs: ## maven deploy - name: Deploy ${{ steps.settings.outputs.WINGS_VERSION }} ${{ steps.settings.outputs.GIT_BRANCH }} - if: inputs.deployOssrh + if: steps.settings.outputs.MVN_DEPLOYRH run: > mvn -P ossrh diff --git a/pom.xml b/pom.xml index 9fdc0c5..7313715 100644 --- a/pom.xml +++ b/pom.xml @@ -263,7 +263,7 @@ - test + coverage false @@ -280,16 +280,46 @@ 0.8.11 - **/best/** - **/stat/** - **/flow/** - **/img/** + + **/best/Assert* + **/best/Dummy* + **/best/Param* + **/best/Typed* + + **/data/DataResult.* **/data/Null* - **/data/Q* - **/data/R* - **/data/U* - **/*Assert.* + **/data/Q.* + **/data/Q$* + **/data/R.* + **/data/R$* + **/data/U.* + **/data/U$* + + **/flow/FlowBreak.* + **/evil/*Attention.* + + **/stat/GitStat* + **/stat/LogStat* + + **/img/ImageIoFix* + **/img/StreamJpg* + **/img/Watermark* + **/img/ZoomRotateCrop* + + **/i18n/*Aware.* + + **/io/CompatibleObjectStream* + **/io/DirHasher* + **/io/Exec* + **/io/NonCloseStream* + **/io/Zipper* + + **/netx/SslTrustAll* + **/netx/SslVersion* + **/*Exception.* + **/*Enum.* + **/WhoAmI.* diff --git a/src/main/java/pro/fessional/mirana/cast/BoxedCastUtil.java b/src/main/java/pro/fessional/mirana/cast/BoxedCastUtil.java index 777cc4a..2c42d6d 100644 --- a/src/main/java/pro/fessional/mirana/cast/BoxedCastUtil.java +++ b/src/main/java/pro/fessional/mirana/cast/BoxedCastUtil.java @@ -285,6 +285,9 @@ else if (obj instanceof byte[]) { else if (obj instanceof char[]) { vs = BoxedCastUtil.list((char[]) obj); } + else if (obj instanceof short[]) { + vs = BoxedCastUtil.list((short[]) obj); + } else if (obj instanceof int[]) { vs = BoxedCastUtil.list((int[]) obj); } @@ -297,6 +300,9 @@ else if (obj instanceof float[]) { else if (obj instanceof double[]) { vs = BoxedCastUtil.list((double[]) obj); } + else if (obj instanceof List) { + vs = (List) obj; + } else if (obj instanceof Collection) { vs = new ArrayList<>((Collection) obj); } diff --git a/src/main/java/pro/fessional/mirana/cast/StringCastUtil.java b/src/main/java/pro/fessional/mirana/cast/StringCastUtil.java index 8db9a85..0c7fd3f 100644 --- a/src/main/java/pro/fessional/mirana/cast/StringCastUtil.java +++ b/src/main/java/pro/fessional/mirana/cast/StringCastUtil.java @@ -26,8 +26,9 @@ public static boolean asTrue(@Nullable String str) { } /** - * parse case-insensitive `null`, `empty`, `blank` and `false,f,no,n` to false - * Note, no pass-through relationship with asTrue. + * parse case-insensitive `null`, `empty`, `blank` and `false,f,no,n` to false (BUT return true) + * NOTE1, no pass-through relationship with asTrue. + * NOTE2, return true if asFalse, e.g. "false".equalsIgnoreCase(str) */ public static boolean asFalse(@Nullable String str) { if (str == null) return true; diff --git a/src/main/java/pro/fessional/mirana/data/Arr.java b/src/main/java/pro/fessional/mirana/data/Arr.java index 3d229ec..9369ae6 100644 --- a/src/main/java/pro/fessional/mirana/data/Arr.java +++ b/src/main/java/pro/fessional/mirana/data/Arr.java @@ -11,7 +11,7 @@ public class Arr { @SafeVarargs - public static T[] of(T... ts) { + public static T[] obj(T... ts) { return ts; } @@ -55,7 +55,7 @@ public static boolean[] set(boolean[] arr, int idx, boolean v) { return arr; } else { - boolean[] tmp = new boolean[arr.length * 2]; + boolean[] tmp = new boolean[Math.max(idx, arr.length) + 1]; System.arraycopy(arr, 0, tmp, 0, arr.length); tmp[idx] = v; return tmp; @@ -69,7 +69,7 @@ public static byte[] set(byte[] arr, int idx, byte v) { return arr; } else { - byte[] tmp = new byte[arr.length * 2]; + byte[] tmp = new byte[Math.max(idx, arr.length) + 1]; System.arraycopy(arr, 0, tmp, 0, arr.length); tmp[idx] = v; return tmp; @@ -83,7 +83,7 @@ public static short[] set(short[] arr, int idx, short v) { return arr; } else { - short[] tmp = new short[arr.length * 2]; + short[] tmp = new short[Math.max(idx, arr.length) + 1]; System.arraycopy(arr, 0, tmp, 0, arr.length); tmp[idx] = v; return tmp; @@ -97,7 +97,7 @@ public static char[] set(char[] arr, int idx, char v) { return arr; } else { - char[] tmp = new char[arr.length * 2]; + char[] tmp = new char[Math.max(idx, arr.length) + 1]; System.arraycopy(arr, 0, tmp, 0, arr.length); tmp[idx] = v; return tmp; @@ -111,7 +111,7 @@ public static int[] set(int[] arr, int idx, int v) { return arr; } else { - int[] tmp = new int[arr.length * 2]; + int[] tmp = new int[Math.max(idx, arr.length) + 1]; System.arraycopy(arr, 0, tmp, 0, arr.length); tmp[idx] = v; return tmp; @@ -125,7 +125,7 @@ public static long[] set(long[] arr, int idx, long v) { return arr; } else { - long[] tmp = new long[arr.length * 2]; + long[] tmp = new long[Math.max(idx, arr.length) + 1]; System.arraycopy(arr, 0, tmp, 0, arr.length); tmp[idx] = v; return tmp; @@ -139,7 +139,7 @@ public static float[] set(float[] arr, int idx, float v) { return arr; } else { - float[] tmp = new float[arr.length * 2]; + float[] tmp = new float[Math.max(idx, arr.length) + 1]; System.arraycopy(arr, 0, tmp, 0, arr.length); tmp[idx] = v; return tmp; @@ -153,7 +153,7 @@ public static double[] set(double[] arr, int idx, double v) { return arr; } else { - double[] tmp = new double[arr.length * 2]; + double[] tmp = new double[Math.max(idx, arr.length) + 1]; System.arraycopy(arr, 0, tmp, 0, arr.length); tmp[idx] = v; return tmp; diff --git a/src/main/java/pro/fessional/mirana/data/Diff.java b/src/main/java/pro/fessional/mirana/data/Diff.java index 9ced851..8640cd2 100644 --- a/src/main/java/pro/fessional/mirana/data/Diff.java +++ b/src/main/java/pro/fessional/mirana/data/Diff.java @@ -25,7 +25,7 @@ public static class V { public V() { } - public V(E v1, E v2) { + private V(E v1, E v2) { this.v1 = v1; this.v2 = v2; } @@ -75,16 +75,12 @@ public boolean onlyV2() { public boolean v1EqV2() { return Objects.equals(v1, v2); } + } - public static V of(T t1, T t2) { - return new V<>(t1, t2); - } - public static void diff(Map> map, K key, T t1, T t2) { - if (!Objects.equals(t1, t2)) { - map.put(key, new V<>(t1, t2)); - } - } + @NotNull + public static V v(T t1, T t2) { + return new V<>(t1, t2); } /** @@ -112,10 +108,7 @@ public static LinkedHashMap> of(@Nullable Map m result.put(k, v); } else { - final Object v2 = en.getValue(); - if (!Objects.equals(vs.v1, v2)) { - vs.v2 = v2; - } + vs.v2 = en.getValue(); } } diff --git a/src/main/java/pro/fessional/mirana/evil/TweakingContext.java b/src/main/java/pro/fessional/mirana/evil/TweakingContext.java index 9f6365e..526d69d 100644 --- a/src/main/java/pro/fessional/mirana/evil/TweakingContext.java +++ b/src/main/java/pro/fessional/mirana/evil/TweakingContext.java @@ -56,6 +56,20 @@ public void initDefault(Supplier value) { defaultValue.set(value); } + /** + * init the default value + */ + public void initGlobal(T value) { + tweakGlobal(value); + } + + /** + * init the default value + */ + public void initGlobal(Supplier value) { + tweakGlobal(value); + } + /** * init thread value */ diff --git a/src/main/java/pro/fessional/mirana/i18n/I18nString.java b/src/main/java/pro/fessional/mirana/i18n/I18nString.java index b65bd3e..9416d1c 100644 --- a/src/main/java/pro/fessional/mirana/i18n/I18nString.java +++ b/src/main/java/pro/fessional/mirana/i18n/I18nString.java @@ -15,8 +15,8 @@ * String can be used as i18n template, * * code - template id * * args - template arguments - * * hint - default text or template - * * i18n - i18n text + * * hint - default text or template, not in hash and equals + * * i18n - i18n text, not in hash and equals * * * @author trydofor @@ -28,7 +28,7 @@ public class I18nString implements I18nAware { private final String code; private final Object[] args; - private final String hint; + private String hint; private transient String i18n = null; public I18nString(String code) { @@ -65,6 +65,12 @@ public String getI18n() { return i18n; } + @Contract("_ -> this") + public I18nString setHint(String hint) { + this.hint = hint == null ? "" : hint;; + return this; + } + @Contract("_ -> this") public I18nString setI18n(String i18n) { this.i18n = i18n; diff --git a/src/main/java/pro/fessional/mirana/i18n/LocaleResolver.java b/src/main/java/pro/fessional/mirana/i18n/LocaleResolver.java index 1644c90..a427ade 100644 --- a/src/main/java/pro/fessional/mirana/i18n/LocaleResolver.java +++ b/src/main/java/pro/fessional/mirana/i18n/LocaleResolver.java @@ -5,7 +5,8 @@ import java.util.Locale; /** - * Supports the underscore(en_US) and the kebab(en-US) naming + * Supports the underscore(en_US) and the kebab(en-US) naming, + * return Locale.getDefault() if not found. * * @author trydofor * @since 2019-07-01 @@ -16,14 +17,18 @@ protected LocaleResolver() { @NotNull public static Locale locale(@NotNull String tag) { + return locale(tag, Locale.getDefault()); + } + + @NotNull + public static Locale locale(@NotNull String tag, @NotNull Locale elz) { if (tag.indexOf('_') >= 0) { tag = tag.replace('_', '-'); } - Locale locale = Locale.forLanguageTag(tag); if (locale.getLanguage().isEmpty()) { - return Locale.getDefault(); + return elz; } return locale; diff --git a/src/main/java/pro/fessional/mirana/math/BigDecimalUtil.java b/src/main/java/pro/fessional/mirana/math/BigDecimalUtil.java index 197aa2f..aea873e 100644 --- a/src/main/java/pro/fessional/mirana/math/BigDecimalUtil.java +++ b/src/main/java/pro/fessional/mirana/math/BigDecimalUtil.java @@ -783,36 +783,27 @@ public static BigDecimal scale(Object num, int scale, RoundingMode mode) { } } - /** - * @see #unitUp(Object, BigDecimal, BigDecimal) - */ - @NotNull - public static BigDecimal unitUp(Object num, BigDecimal unit) { - return unitUp(num, unit, ZERO); - } - /** *
-     * The `unit` is round up, null treated as zero, and scale is based on unit.
-     * Take weighing and pricing as an example, weighing accuracy 0.01, every 0.5 pricing
+     * The `unit` is round up, and scale is based on unit.
+     * Take weighing and pricing as an example, pricing unit=0.5, weighing accuracy=0.01
      * When x > 0.1, treated as 0.5, otherwise treated as 0.
      * When x > 0.6, treated as 1, otherwise treated as 0.5.
      * 
* - * @param num the number - * @param unit the unit - * @param down less than or equal to the value is rounded off + * @param num the number + * @param unit the unit + * @param accuracy less than or equal to the value is rounded off */ @NotNull - public static BigDecimal unitUp(Object num, BigDecimal unit, BigDecimal down) { - final int unitScale = unit.scale(); + public static BigDecimal unitUp(Object num, @NotNull BigDecimal unit, @NotNull BigDecimal accuracy) { BigDecimal d = object(num, ZERO); - if (down == null) down = ZERO; BigDecimal[] dr = d.divideAndRemainder(unit); d = dr[0].multiply(unit); - if (compareTo(dr[1], down, unitScale, FLOOR) > 0) { // round up + final int unitScale = unit.scale(); + if (compareTo(dr[1], accuracy, unitScale, FLOOR) > 0) { // round up d = d.add(unit); } @@ -822,36 +813,27 @@ public static BigDecimal unitUp(Object num, BigDecimal unit, BigDecimal down) { return d; } - /** - * @see #unitDown(Object, BigDecimal, BigDecimal) - */ - @NotNull - public static BigDecimal unitDown(Object num, BigDecimal unit) { - return unitDown(num, unit, unit); - } - /** *
-     * The `unit` is round down, null treated as zero, and scale is based on unit.
-     * Take weighing and pricing as an example, weighing accuracy 0.01, every 0.5 pricing
+     * The `unit` is round down, and scale is based on unit.
+     * Take weighing and pricing as an example, pricing unit=0.5, weighing accuracy=0.01
      * When x > 0.4, treated as 0.5, otherwise treated as 0.
      * When x > 0.9, treated as 1, otherwise treated as 0.5.
      * 
* - * @param num the number - * @param unit the unit - * @param upto greater than or equal to the value is rounded up + * @param num the number + * @param unit the unit + * @param accuracy greater than or equal to the value is rounded up */ @NotNull - public static BigDecimal unitDown(Object num, BigDecimal unit, BigDecimal upto) { - final int unitScale = unit.scale(); - + public static BigDecimal unitDown(Object num, @NotNull BigDecimal unit, @NotNull BigDecimal accuracy) { BigDecimal d = object(num, ZERO); BigDecimal[] dr = d.divideAndRemainder(unit); d = dr[0].multiply(unit); - if (compareTo(dr[1], upto, unitScale, FLOOR) >= 0) { // round up + final int unitScale = unit.scale(); + if (compareTo(dr[1], unit.subtract(accuracy), unitScale, FLOOR) > 0) { // round up d = d.add(unit); } @@ -945,18 +927,13 @@ public BigDecimal resultFloor() { } @NotNull - public BigDecimal resultUnitUp(BigDecimal unit) { - return BigDecimalUtil.unitUp(value, unit); - } - - @NotNull - public BigDecimal resultUnitUp(BigDecimal unit, BigDecimal zeroing) { - return BigDecimalUtil.unitUp(value, unit, zeroing); + public BigDecimal resultUnitUp(@NotNull BigDecimal unit, @NotNull BigDecimal accuracy) { + return BigDecimalUtil.unitUp(value, unit, accuracy); } @NotNull - public BigDecimal resultUnitDown(BigDecimal unit) { - return BigDecimalUtil.unitDown(value, unit); + public BigDecimal resultUnitDown(@NotNull BigDecimal unit, @NotNull BigDecimal accuracy) { + return BigDecimalUtil.unitDown(value, unit, accuracy); } @NotNull diff --git a/src/main/java/pro/fessional/mirana/text/BarString.java b/src/main/java/pro/fessional/mirana/text/BarString.java index 1ec45c7..dacab2c 100644 --- a/src/main/java/pro/fessional/mirana/text/BarString.java +++ b/src/main/java/pro/fessional/mirana/text/BarString.java @@ -59,7 +59,8 @@ public class BarString { private int index = 0; private boolean valid = true; - private int count = 0; + private int strLength = 0; + private int keyCount = 0; private final LinkedList values = new LinkedList<>(); private final boolean[] exists = new boolean[Bars.length]; @@ -68,11 +69,12 @@ public BarString() { } private void appendKey() { + keyCount++; values.add(Ent.Bar); } private void appendValue(@NotNull String str, boolean check) { - count += str.length(); + strLength += str.length(); values.add(new Ent(str, check)); if (check && valid && str.indexOf(Bars[index]) >= 0) { @@ -159,7 +161,7 @@ public String toString() { if (values.isEmpty()) return Null.Str; final char bar = Bars[index]; - StringBuilder buff = new StringBuilder(count + values.size()); + StringBuilder buff = new StringBuilder(strLength + values.size()); for (Ent v : values) { if (v == Ent.Bar) { buff.append(bar); @@ -172,6 +174,22 @@ public String toString() { return buff.toString(); } + @NotNull + public ArrayList values(boolean nullToEmpty) { + ArrayList list = new ArrayList<>(keyCount); + Ent lst = null; + for (Ent e : values) { + if (e != Ent.Bar) { + list.add(e.value); + } + else if (lst == Ent.Bar) { + list.add(nullToEmpty ? Null.Str : null); + } + lst = e; + } + return list; + } + private static class Ent { public static final Ent Bar = new Ent(Null.Str, false); @NotNull @@ -199,7 +217,7 @@ public static ArrayList split(String str, int max) { * parse the BarString, item in list is not null. * * @param str BarString - * @param max max size, 0 means auto + * @param max max size, -1 means auto * @param exactly return empty if the size is not equal the max. */ @NotNull diff --git a/src/main/java/pro/fessional/mirana/text/BuilderHelper.java b/src/main/java/pro/fessional/mirana/text/BuilderHelper.java index 8a3b559..6f5aa6c 100644 --- a/src/main/java/pro/fessional/mirana/text/BuilderHelper.java +++ b/src/main/java/pro/fessional/mirana/text/BuilderHelper.java @@ -158,10 +158,11 @@ public static StringBuilder join(@NotNull StringBuilder sb, boolean skipN final int len = sb.length(); for (T t : arr) { - if (t != null) { - sb.append(fn.apply(t)); + R o = fn.apply(t); + if (o != null) { + sb.append(o); } - if (t != null || !skipNull) { + if (o != null || !skipNull) { sb.append(jn); } } diff --git a/src/main/java/pro/fessional/mirana/text/FormatUtil.java b/src/main/java/pro/fessional/mirana/text/FormatUtil.java index ae8df34..b5f0aae 100644 --- a/src/main/java/pro/fessional/mirana/text/FormatUtil.java +++ b/src/main/java/pro/fessional/mirana/text/FormatUtil.java @@ -216,24 +216,28 @@ public static String format(CharSequence fmt, Object... args) { public static Object[] fixArgs(int size, Object... args) { if (size <= 0) return Null.Objects; - Object[] tmp = null; - if (args == null || args.length < size) { - tmp = new Object[size]; - } - else { - for (Object arg : args) { - if (arg == null) { - tmp = new Object[size]; - break; - } + if (args != null && args.length == size) { + for (int i = 0; i < args.length; i++) { + if (args[i] == null) args[i] = Null.Str; } + return args; } - if (tmp == null) return args; - Arrays.fill(tmp, Null.Str); - if (args != null) { + Object[] tmp = new Object[size]; + if (args == null) { + Arrays.fill(tmp, Null.Str); + } + else if (args.length > tmp.length) { + for (int i = 0; i < tmp.length; i++) { + tmp[i] = args[i] == null ? Null.Str : args[i]; + } + } + else { for (int i = 0; i < args.length; i++) { - if (args[i] != null) tmp[i] = args[i]; + tmp[i] = args[i] == null ? Null.Str : args[i]; + } + for (int i = args.length; i < tmp.length; i++) { + tmp[i] = Null.Str; } } return tmp; diff --git a/src/main/java/pro/fessional/mirana/text/FullCharUtil.java b/src/main/java/pro/fessional/mirana/text/FullCharUtil.java index 801986d..3aab89f 100644 --- a/src/main/java/pro/fessional/mirana/text/FullCharUtil.java +++ b/src/main/java/pro/fessional/mirana/text/FullCharUtil.java @@ -32,19 +32,16 @@ public static String leftCut(@Nullable CharSequence str, int count) { @NotNull public static String leftCut(@Nullable CharSequence str, int count, int off) { if (str == null || count < 1) return ""; + StringBuilder sb = new StringBuilder(count); int hzCnt = 0; - final int hfCnt = count * 2; - StringBuilder sb = new StringBuilder(hfCnt); - - int len = str.length(); - for (int i = Math.max(off, 0); i < len; i++) { + for (int i = Math.max(off, 0), len = str.length(); i < len; i++) { char c = str.charAt(i); hzCnt += c <= Byte.MAX_VALUE ? 1 : 2; - if (hzCnt == hfCnt) { + if (hzCnt == count) { sb.append(c); break; } - else if (hzCnt > hfCnt) { + else if (hzCnt > count) { break; } else { @@ -75,17 +72,16 @@ public static String rightCut(@Nullable CharSequence str, int count) { public static String rightCut(@Nullable CharSequence str, int count, int off) { if (str == null || count < 1) return ""; int hzCnt = 0; - final int hfCnt = count * 2; - StringBuilder sb = new StringBuilder(hfCnt); + StringBuilder sb = new StringBuilder(count); for (int i = str.length() - (off < 0 ? 1 : off + 1); i >= 0; i--) { char c = str.charAt(i); hzCnt += c <= Byte.MAX_VALUE ? 1 : 2; - if (hzCnt == hfCnt) { + if (hzCnt == count) { sb.append(c); break; } - else if (hzCnt > hfCnt) { + else if (hzCnt > count) { break; } else { diff --git a/src/main/java/pro/fessional/mirana/time/DateFormatter.java b/src/main/java/pro/fessional/mirana/time/DateFormatter.java index 9ac233b..fa1d37d 100644 --- a/src/main/java/pro/fessional/mirana/time/DateFormatter.java +++ b/src/main/java/pro/fessional/mirana/time/DateFormatter.java @@ -376,7 +376,7 @@ public static String time12(@Nullable LocalTime time) { */ @NotNull public static String date10(@Nullable Date date) { - return full19().format(date).substring(0, 8); + return full19().format(date).substring(0, 10); } /** @@ -416,10 +416,10 @@ public static String full23(@Nullable Date date) { public static String time(@Nullable Date date) { final String ft = full23().format(date); if (ft.endsWith(".000")) { - return ft.substring(9, 19); + return ft.substring(11, 19); } else { - return ft.substring(9); + return ft.substring(11); } } @@ -428,7 +428,7 @@ public static String time(@Nullable Date date) { */ @NotNull public static String time08(@Nullable Date date) { - return full19().format(date).substring(9); + return full19().format(date).substring(11); } /** @@ -436,7 +436,7 @@ public static String time08(@Nullable Date date) { */ @NotNull public static String time12(@Nullable Date date) { - return full23().format(date).substring(9); + return full23().format(date).substring(11); } diff --git a/src/main/java/pro/fessional/mirana/time/DateLocaling.java b/src/main/java/pro/fessional/mirana/time/DateLocaling.java index 542a678..05382b9 100644 --- a/src/main/java/pro/fessional/mirana/time/DateLocaling.java +++ b/src/main/java/pro/fessional/mirana/time/DateLocaling.java @@ -2,9 +2,7 @@ import java.time.DayOfWeek; import java.time.Instant; -import java.time.LocalDate; import java.time.LocalDateTime; -import java.time.LocalTime; import java.time.ZoneId; import java.time.ZonedDateTime; @@ -67,19 +65,6 @@ public static LocalDateTime dateTime(ZoneId at) { return ZonedDateTime.now(at).toLocalDateTime(); } - /** - * current local date at zoneId - */ - public static LocalDate date(ZoneId at) { - return ZonedDateTime.now(at).toLocalDate(); - } - - /** - * current local time at zoneId - */ - public static LocalTime time(ZoneId at) { - return ZonedDateTime.now(at).toLocalTime(); - } /** * current local 0:0:0.0 at zoneId diff --git a/src/main/java/pro/fessional/mirana/time/Sleep.java b/src/main/java/pro/fessional/mirana/time/Sleep.java index 730eae0..b861b53 100644 --- a/src/main/java/pro/fessional/mirana/time/Sleep.java +++ b/src/main/java/pro/fessional/mirana/time/Sleep.java @@ -3,6 +3,7 @@ import org.jetbrains.annotations.NotNull; import java.time.Duration; +import java.util.concurrent.ThreadLocalRandom; /** * Thead.sleep @@ -13,42 +14,56 @@ public class Sleep { /** - * ignore InterruptedException and wake up + * ignore InterruptedException and immediately wake up with interrupted status */ public static void ignoreInterrupt(@NotNull Duration time) { ignoreInterrupt(time.toMillis()); } /** - * ignore InterruptedException and wake up + * ignore InterruptedException and immediately wake up with interrupted status */ public static void ignoreInterrupt(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { - // ignore + Thread.currentThread().interrupt(); } } + + /** + * random sleep between min and max and return slept ms. + * ignore InterruptedException and immediately wake up with interrupted status + */ + public static long ignoreInterrupt(long min, long max) { + long ms = ThreadLocalRandom.current().nextLong(min, max); + long now = System.currentTimeMillis(); + ignoreInterrupt(ms); + return System.currentTimeMillis() - now; + } + /** - * ignore InterruptedException and continue to sleep + * ignore InterruptedException and continue to sleep, at the end wake up with interrupted status */ public static void snoozeInterrupt(@NotNull Duration time) { snoozeInterrupt(time.toMillis()); } /** - * ignore InterruptedException and continue to sleep + * ignore InterruptedException and continue to sleep, at the end wake up with interrupted status */ public static void snoozeInterrupt(long ms) { final long wake = System.currentTimeMillis() + ms; + boolean rup = false; do { try { Thread.sleep(ms); break; } catch (InterruptedException e) { + rup = true; final long now = System.currentTimeMillis(); if (now >= wake) { break; @@ -58,17 +73,33 @@ public static void snoozeInterrupt(long ms) { } } } while (true); + + if (rup) { + Thread.currentThread().interrupt(); + } } + /** - * throw IllegalStateException, and set whether to keep interrupt status + * random sleep between min and max and return slept ms. + * ignore InterruptedException and continue to sleep, at the end wake up with interrupted status + */ + public static long snoozeInterrupt(long min, long max) { + long ms = ThreadLocalRandom.current().nextLong(min, max); + snoozeInterrupt(ms); + return ms; + } + + + /** + * throw IllegalStateException, and set whether to keep interrupted status */ public static void throwsInterrupt(@NotNull Duration time, boolean keep) { throwsInterrupt(time.toMillis(), keep); } /** - * throw IllegalStateException, and set whether to keep interrupt status + * throw IllegalStateException, and set whether to keep interrupted status */ public static void throwsInterrupt(long ms, boolean keep) { try { @@ -81,4 +112,13 @@ public static void throwsInterrupt(long ms, boolean keep) { throw new IllegalStateException(e); } } + + /** + * random sleep between min and max. + * throw IllegalStateException, and set whether to keep interrupted status + */ + public static void throwsInterrupt(long min, long max, boolean keep) { + long ms = ThreadLocalRandom.current().nextLong(min, max); + throwsInterrupt(ms, keep); + } } diff --git a/src/test/java/pro/fessional/mirana/anti/BeanVisitorTest.java b/src/test/java/pro/fessional/mirana/anti/BeanVisitorTest.java index 4b1444b..f9cadce 100644 --- a/src/test/java/pro/fessional/mirana/anti/BeanVisitorTest.java +++ b/src/test/java/pro/fessional/mirana/anti/BeanVisitorTest.java @@ -11,8 +11,10 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; /** * @author trydofor @@ -37,7 +39,9 @@ public Object amend(@NotNull Field field, @NotNull Annotation[] annos, Object ob final BeanVisitor.Vzt ctnz = new BeanVisitor.ContainerVisitor() { @Override protected @Nullable Object amendValue(@NotNull Field field, @NotNull Annotation[] annos, @Nullable Object obj) { - return obj instanceof Long ? 0L : obj; + if (obj instanceof Long) return 0L; + if (obj instanceof String) return ""; + return obj; } @Override public boolean cares(@NotNull Field field, @NotNull Annotation[] annos) { @@ -47,23 +51,41 @@ public Object amend(@NotNull Field field, @NotNull Annotation[] annos, Object ob @Test void visitBean() { - Po po = new Po(); - BeanVisitor.visit(new BeanVisitor.Opt().skipFinal(false), po, vzts); - - Assertions.assertEquals(0L, po.getId()); - Assertions.assertEquals("-10086", po.getTo()); - Assertions.assertEquals(-10086L, po.getTi()); - Assertions.assertEquals("-10086", po.ng); - Assertions.assertNull(po.getName()); - Assertions.assertNull(po.getLst()); - Assertions.assertNull(po.getMap()); - - final Co[] arr = po.getArr(); - Assertions.assertNotNull(arr); - Assertions.assertEquals(0L, arr[0].getId()); - Assertions.assertEquals("-10086", arr[0].getTo()); - Assertions.assertEquals(-10086L, arr[0].getTi()); - Assertions.assertEquals("-10086", arr[0].ng); + Po po1 = new Po(); + BeanVisitor.visit(new BeanVisitor.Opt().skipFinal(false), po1, vzts); + + Assertions.assertEquals(0L, po1.getId()); + Assertions.assertEquals("-10086", po1.getTo()); + Assertions.assertEquals(-10086L, po1.getTi()); + Assertions.assertEquals("-10086", po1.ng); + Assertions.assertNull(po1.getName()); + Assertions.assertNull(po1.getLst()); + Assertions.assertNull(po1.getMap()); + + final Co[] arr1 = po1.getArr(); + Assertions.assertNotNull(arr1); + Assertions.assertEquals(0L, arr1[0].getId()); + Assertions.assertEquals("-10086", arr1[0].getTo()); + Assertions.assertEquals(-10086L, arr1[0].getTi()); + Assertions.assertEquals("-10086", arr1[0].ng); + + Po po2 = new Po(); + BeanVisitor.visit(new BeanVisitor.Opt().skipFinal(false), po2, ctnz); + + Assertions.assertEquals(0L, po2.getId()); + Assertions.assertEquals("-10086", po2.getTo()); // @Transient + Assertions.assertEquals(-10086L, po2.getTi()); // transient + Assertions.assertEquals("-10086", po2.ng); // no getter + Assertions.assertEquals("", po2.getName()); + Assertions.assertNotNull(po2.getLst()); + Assertions.assertNotNull(po2.getMap()); + + final Co[] arr2 = po2.getArr(); + Assertions.assertNotNull(arr2); + Assertions.assertEquals(0L, arr2[0].getId()); + Assertions.assertEquals("-10086", po2.getTo()); // @Transient + Assertions.assertEquals(-10086L, po2.getTi()); // transient + Assertions.assertEquals("-10086", po2.ng); // no getter } @Test @@ -160,6 +182,7 @@ public static class Po extends Co { private final boolean man; private final List lst; private final Map map; + private final Set set; private final Co[] arr; public Po() { @@ -170,6 +193,8 @@ public Po() { map = new HashMap<>(); map.put("this", this); arr = new Co[]{new Co()}; + set = new HashSet<>(); + set.add(this); } public boolean isMan() { @@ -188,6 +213,10 @@ public Map getMap() { return map; } + public Set getSet() { + return set; + } + public Co[] getArr() { return arr; } diff --git a/src/test/java/pro/fessional/mirana/anti/GTest.java b/src/test/java/pro/fessional/mirana/anti/GTest.java new file mode 100644 index 0000000..d441bd9 --- /dev/null +++ b/src/test/java/pro/fessional/mirana/anti/GTest.java @@ -0,0 +1,27 @@ +package pro.fessional.mirana.anti; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +/** + * @author trydofor + * @since 2024-01-26 + */ +class GTest { + + @Test + void globalTest() { + G.globalPut("1", "attr1"); + Assertions.assertEquals("attr1", G.globalGet("1")); + G.globalDel("1"); + Assertions.assertNull(G.globalGet("1")); + } + + @Test + void threadTest() { + G.threadPut("1", "attr1"); + Assertions.assertEquals("attr1", G.threadGet("1")); + G.threadDel("1"); + Assertions.assertNull(G.threadGet("1")); + } +} \ No newline at end of file diff --git a/src/test/java/pro/fessional/mirana/anti/LTest.java b/src/test/java/pro/fessional/mirana/anti/LTest.java index 4f1dd87..573f5a5 100644 --- a/src/test/java/pro/fessional/mirana/anti/LTest.java +++ b/src/test/java/pro/fessional/mirana/anti/LTest.java @@ -1,7 +1,10 @@ package pro.fessional.mirana.anti; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import pro.fessional.mirana.SystemOut; +import pro.fessional.mirana.data.Null; + +import java.util.List; /** * @author trydofor @@ -10,11 +13,56 @@ class LTest { @Test - void parse() { + void normal() { L.error("error message"); - L.error("userid={}", 1); + L.warn("userid={}", 1); L.message("message"); + + List ld = L.inspect(); + Assertions.assertEquals(3, ld.size()); + L.D d0 = ld.get(0); + Assertions.assertEquals("error", d0.cate); + Assertions.assertEquals("error message", d0.message); + + L.D d1 = ld.get(1); + Assertions.assertEquals("warn", d1.cate); + Assertions.assertEquals("userid={}", d1.message); + Assertions.assertEquals(1, d1.args[0]); + + L.D d2 = ld.get(2); + Assertions.assertNull(d2.cate); + Assertions.assertEquals("message", d2.message); + Assertions.assertEquals(Null.Objects, d2.args); + final String rs1 = L.finish(); - SystemOut.println(rs1); + Assertions.assertEquals( + "error:error message\n" + + "warn:userid=1\n" + + "message", + rs1); + + } + + @Test + void remove() { + L.error("error message"); + L.warn("userid={}", 1); + L.message("message"); + + List ld = L.remove(); + Assertions.assertEquals(3, ld.size()); + L.D d0 = ld.get(0); + Assertions.assertEquals("error", d0.cate); + Assertions.assertEquals("error message", d0.message); + + L.D d1 = ld.get(1); + Assertions.assertEquals("warn", d1.cate); + Assertions.assertEquals("userid={}", d1.message); + Assertions.assertEquals(1, d1.args[0]); + + L.D d2 = ld.get(2); + Assertions.assertNull(d2.cate); + Assertions.assertEquals("message", d2.message); + Assertions.assertEquals(Null.Objects, d2.args); } } diff --git a/src/test/java/pro/fessional/mirana/cast/BiConvertorTest.java b/src/test/java/pro/fessional/mirana/cast/BiConvertorTest.java index 2173508..ebba11f 100644 --- a/src/test/java/pro/fessional/mirana/cast/BiConvertorTest.java +++ b/src/test/java/pro/fessional/mirana/cast/BiConvertorTest.java @@ -2,8 +2,13 @@ import org.junit.jupiter.api.Test; +import java.util.Date; + import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author trydofor @@ -20,6 +25,28 @@ class BiConvertorTest { void testSimple() { assertEquals(1, str2Int.toTarget("1")); assertEquals("1", str2Int.toSource(1)); + assertEquals(String.class, str2Int.sourceType()); + assertEquals(Integer.class, str2Int.targetType()); + assertTrue(str2Int.canToTarget("1")); + assertTrue(str2Int.canToSource(1)); + assertFalse(str2Int.canToTarget(1)); + assertFalse(str2Int.canToSource("")); + assertEquals(1, str2Int.tryToTarget("1")); + assertEquals("1", str2Int.tryToSource(1)); + } + + @Test + void testTryDo() { + BiConvertor sup = BiConvertor.of( + String.class, + Number.class, + Integer::valueOf, Object::toString); + + assertEquals(1, sup.tryToTarget(Integer.class, "1")); + assertNull(sup.tryToTarget(Date.class, "1")); + + assertEquals("1", sup.tryToSource(CharSequence.class,1)); + assertNull(sup.tryToSource(Date.class, 1)); } @Test @@ -28,6 +55,8 @@ void testInverse() { assertEquals(1, int2Str.toSource("1")); assertEquals("1", int2Str.toTarget(1)); assertSame(int2Str.reverseBiConvertor(), str2Int); + assertEquals(Integer.class, int2Str.sourceType()); + assertEquals(String.class, int2Str.targetType()); } @Test @@ -35,5 +64,7 @@ void testCompose() { final BiConvertor compose = str2Int.compose(str2Int.reverseBiConvertor()); assertEquals("1", compose.toTarget("1")); assertEquals("1", compose.toSource("1")); + assertEquals(String.class, compose.sourceType()); + assertEquals(String.class, compose.targetType()); } } diff --git a/src/test/java/pro/fessional/mirana/cast/BoxedCastUtilTest.java b/src/test/java/pro/fessional/mirana/cast/BoxedCastUtilTest.java index 62a02b9..6258d0a 100644 --- a/src/test/java/pro/fessional/mirana/cast/BoxedCastUtilTest.java +++ b/src/test/java/pro/fessional/mirana/cast/BoxedCastUtilTest.java @@ -2,7 +2,13 @@ import org.junit.jupiter.api.Test; +import java.math.BigDecimal; import java.util.Arrays; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author trydofor @@ -10,23 +16,222 @@ */ public class BoxedCastUtilTest { + @Test + public void boolOr() { + assertTrue(BoxedCastUtil.orTrue(null)); + assertTrue(BoxedCastUtil.orTrue(true)); + assertFalse(BoxedCastUtil.orTrue(false)); + + assertFalse(BoxedCastUtil.orFalse(null)); + assertTrue(BoxedCastUtil.orFalse(true)); + assertFalse(BoxedCastUtil.orFalse(false)); + } + + @Test + public void charOr() { + Character vn = null; + Character v0 = 0; + assertEquals(v0, BoxedCastUtil.orZero(vn)); + assertEquals(v0, BoxedCastUtil.orElse(vn, v0)); + assertEquals(v0, BoxedCastUtil.orElse(v0, v0)); + } + + @Test + public void byteOr() { + Byte vn = null; + Byte v0 = 0; + assertEquals(v0, BoxedCastUtil.orZero(vn)); + assertEquals(v0, BoxedCastUtil.orElse(vn, v0)); + assertEquals(v0, BoxedCastUtil.orElse(v0, v0)); + } + + @Test + public void shortOr() { + Short vn = null; + Short v0 = 0; + assertEquals(v0, BoxedCastUtil.orZero(vn)); + assertEquals(v0, BoxedCastUtil.orElse(vn, v0)); + assertEquals(v0, BoxedCastUtil.orElse(v0, v0)); + } + + @Test + public void intOr() { + Integer vn = null; + Integer v0 = 0; + assertEquals(v0, BoxedCastUtil.orZero(vn)); + assertEquals(v0, BoxedCastUtil.orElse(vn, v0)); + assertEquals(v0, BoxedCastUtil.orElse(v0, v0)); + } + + @Test + public void longOr() { + Long vn = null; + Long v0 = 0L; + assertEquals(v0, BoxedCastUtil.orZero(vn)); + assertEquals(v0, BoxedCastUtil.orElse(vn, v0)); + assertEquals(v0, BoxedCastUtil.orElse(v0, v0)); + } + + @Test + public void doubleOr() { + Double vn = null; + Double v0 = 0D; + assertEquals(v0, BoxedCastUtil.orZero(vn)); + assertEquals(v0, BoxedCastUtil.orElse(vn, v0)); + assertEquals(v0, BoxedCastUtil.orElse(v0, v0)); + } + + @Test + public void floatOr() { + Float vn = null; + Float v0 = 0F; + assertEquals(v0, BoxedCastUtil.orZero(vn)); + assertEquals(v0, BoxedCastUtil.orElse(vn, v0)); + assertEquals(v0, BoxedCastUtil.orElse(v0, v0)); + } + + @Test + public void decimalOr() { + BigDecimal vn = null; + BigDecimal v0 = BigDecimal.ZERO; + assertEquals(v0, BoxedCastUtil.orZero(vn)); + assertEquals(v0, BoxedCastUtil.orElse(vn, v0)); + assertEquals(v0, BoxedCastUtil.orElse(v0, v0)); + } + + @Test + public void bools() { + Boolean v1 = true; + Boolean v2 = false; + Object obj = new boolean[]{v1, v2}; + List lst = Arrays.asList(v1, v2); + boolean[] arr = BoxedCastUtil.bools(lst); + + assertEquals(0, BoxedCastUtil.bools(null).length); + assertEquals(2, arr.length); + assertEquals(v1, arr[0]); + assertEquals(v2, arr[1]); + assertEquals(lst, BoxedCastUtil.list(obj)); + assertEquals(lst, BoxedCastUtil.list(arr)); + } + + @Test + public void chars() { + Character v1 = '1'; + Character v2 = '0'; + Object obj = new char[]{v1, v2}; + List lst = Arrays.asList(v1, v2); + char[] arr = BoxedCastUtil.chars(lst); + + assertEquals(0, BoxedCastUtil.chars(null).length); + assertEquals(2, arr.length); + assertEquals(v1, arr[0]); + assertEquals(v2, arr[1]); + assertEquals(lst, BoxedCastUtil.list(obj)); + assertEquals(lst, BoxedCastUtil.list(arr)); + } + + @Test + public void bytes() { + Byte v1 = '1'; + Byte v2 = '0'; + Object obj = new byte[]{v1, v2}; + List lst = Arrays.asList(v1, v2); + byte[] arr = BoxedCastUtil.bytes(lst); + + assertEquals(0, BoxedCastUtil.bytes(null).length); + assertEquals(2, arr.length); + assertEquals(v1, arr[0]); + assertEquals(v2, arr[1]); + assertEquals(lst, BoxedCastUtil.list(obj)); + assertEquals(lst, BoxedCastUtil.list(arr)); + } + + @Test + public void shorts() { + Short v1 = '1'; + Short v2 = '0'; + Object obj = new short[]{v1, v2}; + List lst = Arrays.asList(v1, v2); + short[] arr = BoxedCastUtil.shorts(lst); + + assertEquals(0, BoxedCastUtil.shorts(null).length); + assertEquals(2, arr.length); + assertEquals(v1, arr[0]); + assertEquals(v2, arr[1]); + assertEquals(lst, BoxedCastUtil.list(obj)); + assertEquals(lst, BoxedCastUtil.list(arr)); + } + + @Test + public void ints() { + Integer v1 = 1; + Integer v2 = 0; + Object obj = new int[]{v1, v2}; + List lst = Arrays.asList(v1, v2); + int[] arr = BoxedCastUtil.ints(lst); + + assertEquals(0, BoxedCastUtil.ints(null).length); + assertEquals(2, arr.length); + assertEquals(v1, arr[0]); + assertEquals(v2, arr[1]); + assertEquals(lst, BoxedCastUtil.list(obj)); + assertEquals(lst, BoxedCastUtil.list(arr)); + } + + @Test + public void longs() { + Long v1 = 1L; + Long v2 = 0L; + Object obj = new long[]{v1, v2}; + List lst = Arrays.asList(v1, v2); + long[] arr = BoxedCastUtil.longs(lst); + + assertEquals(0, BoxedCastUtil.longs(null).length); + assertEquals(2, arr.length); + assertEquals(v1, arr[0]); + assertEquals(v2, arr[1]); + assertEquals(lst, BoxedCastUtil.list(obj)); + assertEquals(lst, BoxedCastUtil.list(arr)); + } + + @Test + public void floats() { + Float v1 = 1F; + Float v2 = 0F; + Object obj = new float[]{v1, v2}; + List lst = Arrays.asList(v1, v2); + float[] arr = BoxedCastUtil.floats(lst); + + assertEquals(0, BoxedCastUtil.floats(null).length); + assertEquals(2, arr.length); + assertEquals(v1, arr[0]); + assertEquals(v2, arr[1]); + assertEquals(lst, BoxedCastUtil.list(obj)); + assertEquals(lst, BoxedCastUtil.list(arr)); + } + + @Test + public void doubles() { + Double v1 = 1D; + Double v2 = 0D; + Object obj = new double[]{v1, v2}; + List lst = Arrays.asList(v1, v2); + double[] arr = BoxedCastUtil.doubles(lst); + + assertEquals(0, BoxedCastUtil.doubles(null).length); + assertEquals(2, arr.length); + assertEquals(v1, arr[0]); + assertEquals(v2, arr[1]); + assertEquals(lst, BoxedCastUtil.list(obj)); + assertEquals(lst, BoxedCastUtil.list(arr)); + } + @Test public void list() { - { - Object obj = new int[]{1, 2, 3}; - BoxedCastUtil.list(obj); - } - { - Object obj = new long[]{1, 2, 3}; - BoxedCastUtil.list(obj); - } - { - Object obj = Arrays.asList(1, 2, 3); - BoxedCastUtil.list(obj); - } - { - Object obj = 1; - BoxedCastUtil.list(obj); - } + List lst1 = Arrays.asList(1, 2); + assertEquals(lst1, BoxedCastUtil.list(lst1)); + Integer[] arr = new Integer[]{1, 2}; + assertEquals(lst1, BoxedCastUtil.list(arr)); } } \ No newline at end of file diff --git a/src/test/java/pro/fessional/mirana/cast/BoxedTypeUtilTest.java b/src/test/java/pro/fessional/mirana/cast/BoxedTypeUtilTest.java index 2b77008..9430e49 100644 --- a/src/test/java/pro/fessional/mirana/cast/BoxedTypeUtilTest.java +++ b/src/test/java/pro/fessional/mirana/cast/BoxedTypeUtilTest.java @@ -17,6 +17,13 @@ void tryBox() { assertEquals(Boolean.class, BoxedTypeUtil.box(Boolean.class)); assertEquals(Integer.class, BoxedTypeUtil.box(int.class)); assertEquals(Integer.class, BoxedTypeUtil.box(Integer.class)); + assertEquals(Long.class, BoxedTypeUtil.box(long.class)); + assertEquals(Long.class, BoxedTypeUtil.box(Long.class)); + assertEquals(Float.class, BoxedTypeUtil.box(float.class)); + assertEquals(Float.class, BoxedTypeUtil.box(Float.class)); + assertEquals(Double.class, BoxedTypeUtil.box(double.class)); + assertEquals(Double.class, BoxedTypeUtil.box(Double.class)); + assertEquals(Void.class, BoxedTypeUtil.box(void.class)); } @Test diff --git a/src/test/java/pro/fessional/mirana/cast/EnumConvertorTest.java b/src/test/java/pro/fessional/mirana/cast/EnumConvertorTest.java index 56528a3..b2eab22 100644 --- a/src/test/java/pro/fessional/mirana/cast/EnumConvertorTest.java +++ b/src/test/java/pro/fessional/mirana/cast/EnumConvertorTest.java @@ -3,6 +3,7 @@ import org.junit.jupiter.api.Test; import pro.fessional.mirana.SystemOut; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; /** @@ -21,6 +22,13 @@ public enum Tx { ONE } + @Test + public void instanceInvoke() { + EnumConvertor ec = new EnumConvertor<>(Tx.class); + assertEquals(Tx.class, ec.targetType()); + assertEquals("pro.fessional.mirana.cast.EnumConvertorTest$Tx#ONE", ec.toSource(Tx.ONE)); + assertEquals(Tx.ONE, ec.toTarget("ONE")); + } @Test public void staticInvoke() { diff --git a/src/test/java/pro/fessional/mirana/cast/StringCastUtilTest.java b/src/test/java/pro/fessional/mirana/cast/StringCastUtilTest.java new file mode 100644 index 0000000..9948784 --- /dev/null +++ b/src/test/java/pro/fessional/mirana/cast/StringCastUtilTest.java @@ -0,0 +1,79 @@ +package pro.fessional.mirana.cast; + +import org.junit.jupiter.api.Test; + +import java.math.BigDecimal; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * @author trydofor + * @since 2024-01-27 + */ +class StringCastUtilTest { + + @Test + void asTrue() { + assertTrue(StringCastUtil.asTrue("True")); + assertTrue(StringCastUtil.asTrue("T")); + assertTrue(StringCastUtil.asTrue("Yes")); + assertTrue(StringCastUtil.asTrue("Y")); + assertFalse(StringCastUtil.asTrue("")); + assertFalse(StringCastUtil.asTrue(null)); + } + + @Test + void asFalse() { + assertTrue(StringCastUtil.asFalse("false")); + assertTrue(StringCastUtil.asFalse("F")); + assertTrue(StringCastUtil.asFalse("No")); + assertTrue(StringCastUtil.asFalse("N")); + assertTrue(StringCastUtil.asFalse("")); + assertTrue(StringCastUtil.asFalse(null)); + } + + @Test + void asLong() { + assertEquals(1L, StringCastUtil.asLong("1", 0)); + assertEquals(0L, StringCastUtil.asLong("", 0)); + assertEquals(0L, StringCastUtil.asLong(null, 0)); + } + + @Test + void asInt() { + assertEquals(1, StringCastUtil.asInt("1", 0)); + assertEquals(0, StringCastUtil.asInt("", 0)); + assertEquals(0, StringCastUtil.asInt(null, 0)); + } + + @Test + void asFloat() { + assertEquals(1F, StringCastUtil.asFloat("1F", 0F)); + assertEquals(0F, StringCastUtil.asFloat("", 0F)); + assertEquals(0F, StringCastUtil.asFloat(null, 0F)); + } + + @Test + void asDouble() { + assertEquals(1D, StringCastUtil.asDouble("1D", 0D)); + assertEquals(0D, StringCastUtil.asDouble("", 0D)); + assertEquals(0D, StringCastUtil.asDouble(null, 0D)); + } + + @Test + void asDecimal() { + assertEquals(BigDecimal.ONE, StringCastUtil.asDecimal("1", BigDecimal.ZERO)); + assertEquals(BigDecimal.ZERO, StringCastUtil.asDecimal("", BigDecimal.ZERO)); + assertEquals(BigDecimal.ZERO, StringCastUtil.asDecimal(null, BigDecimal.ZERO)); + } + + @Test + void string() { + assertEquals("0", StringCastUtil.string(BigDecimal.ZERO)); + assertEquals("0.10", StringCastUtil.string(new BigDecimal("0.10"))); + BigDecimal vd = null; + assertEquals("0", StringCastUtil.string(vd, "0")); + String vo = null; + assertEquals("0", StringCastUtil.string(vo, "0")); + } +} \ No newline at end of file diff --git a/src/test/java/pro/fessional/mirana/cast/TypedCastUtilTest.java b/src/test/java/pro/fessional/mirana/cast/TypedCastUtilTest.java new file mode 100644 index 0000000..d771705 --- /dev/null +++ b/src/test/java/pro/fessional/mirana/cast/TypedCastUtilTest.java @@ -0,0 +1,88 @@ +package pro.fessional.mirana.cast; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * @author trydofor + * @since 2024-01-27 + */ +class TypedCastUtilTest { + + @Test + void castObject() { + Object v0 = 1L; + Long v1 = TypedCastUtil.castObject(v0); + Assertions.assertEquals(v0, v1); + + Long v2 = TypedCastUtil.castObject(v0, Long.class); + Assertions.assertEquals(v0, v2); + + Number v3 = TypedCastUtil.castObject(v0, Number.class); + Assertions.assertEquals(v0, v3); + + String v4 = TypedCastUtil.castObject(v0, String.class); + Assertions.assertNull(v4); + } + + @Test + void castCollection() { + Assertions.assertTrue(TypedCastUtil.castCollection(null).isEmpty()); + + Collection v0 = Arrays.asList(1L, 2L); + Collection v1 = TypedCastUtil.castCollection(v0); + Assertions.assertEquals(v0, v1); + + Collection v2 = TypedCastUtil.castCollection(v0, Long.class); + Assertions.assertEquals(v0, v2); + + Collection v3 = TypedCastUtil.castCollection(v0, Number.class); + Assertions.assertEquals(v0, v3); + + Collection v4 = TypedCastUtil.castCollection(v0, String.class); + Assertions.assertTrue(v4.isEmpty()); + + } + + @Test + void castList() { + Assertions.assertTrue(TypedCastUtil.castList(null).isEmpty()); + + List v0 = Arrays.asList(1L, 2L); + List v1 = TypedCastUtil.castList(v0); + Assertions.assertEquals(v0, v1); + + List v2 = TypedCastUtil.castList(v0, Long.class); + Assertions.assertEquals(v0, v2); + + List v3 = TypedCastUtil.castList(v0, Number.class); + Assertions.assertEquals(v0, v3); + + List v4 = TypedCastUtil.castList(v0, String.class); + Assertions.assertTrue(v4.isEmpty()); + } + + @Test + void castSet() { + Assertions.assertTrue(TypedCastUtil.castSet(null).isEmpty()); + + Set v0 = new HashSet<>(Arrays.asList(1L, 2L)); + Set v1 = TypedCastUtil.castSet(v0); + Assertions.assertEquals(v0, v1); + + Set v2 = TypedCastUtil.castSet(v0, Long.class); + Assertions.assertEquals(v0, v2); + + Set v3 = TypedCastUtil.castSet(v0, Number.class); + Assertions.assertEquals(v0, v3); + + Set v4 = TypedCastUtil.castSet(v0, String.class); + Assertions.assertTrue(v4.isEmpty()); + } +} \ No newline at end of file diff --git a/src/test/java/pro/fessional/mirana/cond/EqualsUtilTest.java b/src/test/java/pro/fessional/mirana/cond/EqualsUtilTest.java index 261306a..7e0af40 100644 --- a/src/test/java/pro/fessional/mirana/cond/EqualsUtilTest.java +++ b/src/test/java/pro/fessional/mirana/cond/EqualsUtilTest.java @@ -4,8 +4,11 @@ import org.junit.jupiter.api.Test; import java.math.BigDecimal; +import java.math.BigInteger; import java.util.Arrays; +import java.util.concurrent.atomic.AtomicInteger; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; /** @@ -15,7 +18,38 @@ public class EqualsUtilTest { @Test - public void hasVal() { + public void eqVal() { + byte byte1 = 1; + short short1 = 1; + int int1 = 1; + long long1 = 1L; + float float1 = 1F; + double double1 = 1D; + BigDecimal bigDecimal1 = BigDecimal.ONE; + BigInteger bigInteger1 = BigInteger.ONE; + AtomicInteger atomicInteger1 = new AtomicInteger(1); + + Number[] nums = new Number[]{ + byte1, + short1, + int1, + long1, + float1, + double1, + bigDecimal1, + bigInteger1, + atomicInteger1, + }; + + for (Number n1 : nums) { + for (Number n2 : nums) { + assertTrue(EqualsUtil.eqVal(n1, n2)); + } + } + } + + @Test + public void inVal() { assertTrue(EqualsUtil.inVal(1, 1L)); assertTrue(EqualsUtil.inVal(1, new Number[]{1, 2, 3})); assertTrue(EqualsUtil.inVal(1, 1, 2, 3)); @@ -23,15 +57,45 @@ public void hasVal() { assertTrue(EqualsUtil.inVal(1, 1L, 2L, 3)); assertTrue(EqualsUtil.inVal(1, 1, 2L, 3)); assertTrue(EqualsUtil.inVal(1, new BigDecimal(1), 2L, 3)); + assertTrue(EqualsUtil.inVal(new BigDecimal("1.0"), new BigDecimal(1), 2L, 3)); + assertFalse(EqualsUtil.inVal(new BigDecimal("4"), new BigDecimal(1), 2L, 3)); + + { + int[] arr = {1, 2, 3}; + assertTrue(EqualsUtil.inVal(new BigDecimal("1.0"), arr)); + assertFalse(EqualsUtil.inVal(new BigDecimal("4"), arr)); + } + { + long[] arr = {1, 2, 3}; + assertTrue(EqualsUtil.inVal(new BigDecimal("1.0"), arr)); + assertFalse(EqualsUtil.inVal(new BigDecimal("4"), arr)); + } + { + float[] arr = {1, 2, 3}; + assertTrue(EqualsUtil.inVal(new BigDecimal("1.0"), arr)); + assertFalse(EqualsUtil.inVal(new BigDecimal("4"), arr)); + } + { + double[] arr = {1, 2, 3}; + assertTrue(EqualsUtil.inVal(new BigDecimal("1.0"), arr)); + assertFalse(EqualsUtil.inVal(new BigDecimal("4"), arr)); + } } @Test - public void testStr() { + public void inCase() { + assertTrue(EqualsUtil.inCase("1", "1")); assertTrue(EqualsUtil.inCase("1", "1", "2")); + assertTrue(EqualsUtil.inCase("1", new String[]{"1", "2"})); assertTrue(EqualsUtil.inCase("1", Arrays.asList("1", "2"))); + assertFalse(EqualsUtil.inCase("3", Arrays.asList("1", "2"))); + + assertTrue(EqualsUtil.inCaseless("a", "A")); assertTrue(EqualsUtil.inCaseless("a", "A", "2")); + assertTrue(EqualsUtil.inCaseless("a", new String[]{"A", "2"})); assertTrue(EqualsUtil.inCaseless("a", Arrays.asList("A", "2"))); + assertFalse(EqualsUtil.inCaseless("b", Arrays.asList("A", "2"))); } } diff --git a/src/test/java/pro/fessional/mirana/cond/StaticFlagTest.java b/src/test/java/pro/fessional/mirana/cond/StaticFlagTest.java new file mode 100644 index 0000000..363113b --- /dev/null +++ b/src/test/java/pro/fessional/mirana/cond/StaticFlagTest.java @@ -0,0 +1,63 @@ +package pro.fessional.mirana.cond; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +/** + * @author trydofor + * @since 2024-01-27 + */ +class StaticFlagTest { + + enum TestFlag { + Y, + N, + X + } + + @Test + void jvmFlag() { + StaticFlag.setFlag(TestFlag.Y); + Assertions.assertTrue(StaticFlag.hasFlag(TestFlag.Y)); + Assertions.assertFalse(StaticFlag.hasFlag(TestFlag.X)); + + Assertions.assertTrue(StaticFlag.notFlag(TestFlag.X)); + Assertions.assertTrue(StaticFlag.anyFlag(TestFlag.Y, TestFlag.X)); + Assertions.assertFalse(StaticFlag.anyFlag(TestFlag.N, TestFlag.X)); + + StaticFlag.delFlag(TestFlag.Y); + Assertions.assertFalse(StaticFlag.hasFlag(TestFlag.Y)); + Assertions.assertFalse(StaticFlag.anyFlag(TestFlag.Y, TestFlag.X)); + Assertions.assertFalse(StaticFlag.anyFlag(TestFlag.N, TestFlag.X)); + } + + @Test + void keyFlag() { + String key = "key1"; + StaticFlag.setFlag(key, TestFlag.Y); + Assertions.assertTrue(StaticFlag.hasFlag(key, TestFlag.Y)); + Assertions.assertFalse(StaticFlag.hasFlag(key, TestFlag.X)); + + Assertions.assertTrue(StaticFlag.notFlag(key, TestFlag.X)); + Assertions.assertTrue(StaticFlag.anyFlag(key, TestFlag.Y, TestFlag.X)); + Assertions.assertFalse(StaticFlag.anyFlag(key, TestFlag.N, TestFlag.X)); + + StaticFlag.delFlag(key, TestFlag.Y); + Assertions.assertFalse(StaticFlag.hasFlag(key, TestFlag.Y)); + Assertions.assertFalse(StaticFlag.anyFlag(key, TestFlag.Y, TestFlag.X)); + Assertions.assertFalse(StaticFlag.anyFlag(key, TestFlag.N, TestFlag.X)); + + key = "ke2"; + Assertions.assertFalse(StaticFlag.hasFlag(key, TestFlag.Y)); + Assertions.assertFalse(StaticFlag.hasFlag(key, TestFlag.X)); + + Assertions.assertTrue(StaticFlag.notFlag(key, TestFlag.X)); + Assertions.assertFalse(StaticFlag.anyFlag(key, TestFlag.Y, TestFlag.X)); + Assertions.assertFalse(StaticFlag.anyFlag(key, TestFlag.N, TestFlag.X)); + + StaticFlag.delFlag(key, TestFlag.Y); + Assertions.assertFalse(StaticFlag.hasFlag(key, TestFlag.Y)); + Assertions.assertFalse(StaticFlag.anyFlag(key, TestFlag.Y, TestFlag.X)); + Assertions.assertFalse(StaticFlag.anyFlag(key, TestFlag.N, TestFlag.X)); + } +} \ No newline at end of file diff --git a/src/test/java/pro/fessional/mirana/data/ArrTest.java b/src/test/java/pro/fessional/mirana/data/ArrTest.java new file mode 100644 index 0000000..196665d --- /dev/null +++ b/src/test/java/pro/fessional/mirana/data/ArrTest.java @@ -0,0 +1,267 @@ +package pro.fessional.mirana.data; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +/** + * @author trydofor + * @since 2024-01-27 + */ +class ArrTest { + + @Test + void ofBoolean() { + boolean[] b0 = null; + boolean[] b1 = Arr.of(b0); + boolean[] b2 = Arr.of(true, false); + + Assertions.assertNotNull(b1); + Assertions.assertEquals(0, b1.length); + + Assertions.assertEquals(2, b2.length); + Assertions.assertTrue(b2[0]); + Assertions.assertFalse(b2[1]); + } + + @Test + void setBoolean() { + boolean v1 = true; + boolean v2 = false; + boolean[] b1 = {v1, v2}; + boolean[] b2 = Arr.set(b1, 0, v2); + boolean[] b3 = Arr.set(b1, 2, v2); + + Assertions.assertSame(b1, b2); + Assertions.assertEquals(v2, b2[0]); + + Assertions.assertNotSame(b1, b3); + Assertions.assertEquals(3, b3.length); + Assertions.assertEquals(v2, b3[2]); + } + + @Test + void ofByte() { + byte v1 = 'x'; + byte v2 = 'y'; + byte[] b0 = null; + byte[] b1 = Arr.of(b0); + byte[] b2 = Arr.of(v1, v2); + + Assertions.assertNotNull(b1); + Assertions.assertEquals(0, b1.length); + + Assertions.assertEquals(2, b2.length); + Assertions.assertEquals(v1, b2[0]); + Assertions.assertEquals(v2, b2[1]); + } + + @Test + void setByte() { + byte v1 = 'x'; + byte v2 = 'y'; + byte[] b1 = {v1, v2}; + byte[] b2 = Arr.set(b1, 0, v2); + byte[] b3 = Arr.set(b1, 2, v2); + + Assertions.assertSame(b1, b2); + Assertions.assertEquals(v2, b2[0]); + + Assertions.assertNotSame(b1, b3); + Assertions.assertEquals(3, b3.length); + Assertions.assertEquals(v2, b3[2]); + } + + @Test + void ofShort() { + short v1 = 'x'; + short v2 = 'y'; + short[] b0 = null; + short[] b1 = Arr.of(b0); + short[] b2 = Arr.of(v1, v2); + Assertions.assertNotNull(b1); + Assertions.assertEquals(0, b1.length); + + Assertions.assertEquals(2, b2.length); + Assertions.assertEquals(v1, b2[0]); + Assertions.assertEquals(v2, b2[1]); + } + + @Test + void setShort() { + short v1 = 'x'; + short v2 = 'y'; + short[] b1 = {v1, v2}; + short[] b2 = Arr.set(b1, 0, v2); + short[] b3 = Arr.set(b1, 2, v2); + + Assertions.assertSame(b1, b2); + Assertions.assertEquals(v2, b2[0]); + + Assertions.assertNotSame(b1, b3); + Assertions.assertEquals(3, b3.length); + Assertions.assertEquals(v2, b3[2]); + } + + + @Test + void ofChar() { + char v1 = 'x'; + char v2 = 'y'; + char[] b0 = null; + char[] b1 = Arr.of(b0); + char[] b2 = Arr.of(v1, v2); + + Assertions.assertNotNull(b1); + Assertions.assertEquals(0, b1.length); + + Assertions.assertEquals(2, b2.length); + Assertions.assertEquals(v1, b2[0]); + Assertions.assertEquals(v2, b2[1]); + } + + @Test + void setChar() { + char v1 = 'x'; + char v2 = 'y'; + char[] b1 = {v1, v2}; + char[] b2 = Arr.set(b1, 0, v2); + char[] b3 = Arr.set(b1, 2, v2); + + Assertions.assertSame(b1, b2); + Assertions.assertEquals(v2, b2[0]); + + Assertions.assertNotSame(b1, b3); + Assertions.assertEquals(3, b3.length); + Assertions.assertEquals(v2, b3[2]); + } + + + @Test + void ofInt() { + int v1 = 'x'; + int v2 = 'y'; + int[] b0 = null; + int[] b1 = Arr.of(b0); + int[] b2 = Arr.of(v1, v2); + + Assertions.assertNotNull(b1); + Assertions.assertEquals(0, b1.length); + + Assertions.assertEquals(2, b2.length); + Assertions.assertEquals(v1, b2[0]); + Assertions.assertEquals(v2, b2[1]); + } + + @Test + void setInt() { + int v1 = 'x'; + int v2 = 'y'; + int[] b1 = {v1, v2}; + int[] b2 = Arr.set(b1, 0, v2); + int[] b3 = Arr.set(b1, 2, v2); + + Assertions.assertSame(b1, b2); + Assertions.assertEquals(v2, b2[0]); + + Assertions.assertNotSame(b1, b3); + Assertions.assertEquals(3, b3.length); + Assertions.assertEquals(v2, b3[2]); + } + + @Test + void ofLong() { + long v1 = 'x'; + long v2 = 'y'; + long[] b0 = null; + long[] b1 = Arr.of(b0); + long[] b2 = Arr.of(v1, v2); + + Assertions.assertNotNull(b1); + Assertions.assertEquals(0, b1.length); + + Assertions.assertEquals(2, b2.length); + Assertions.assertEquals(v1, b2[0]); + Assertions.assertEquals(v2, b2[1]); + } + + @Test + void setLong() { + long v1 = 'x'; + long v2 = 'y'; + long[] b1 = {v1, v2}; + long[] b2 = Arr.set(b1, 0, v2); + long[] b3 = Arr.set(b1, 2, v2); + + Assertions.assertSame(b1, b2); + Assertions.assertEquals(v2, b2[0]); + + Assertions.assertNotSame(b1, b3); + Assertions.assertEquals(3, b3.length); + Assertions.assertEquals(v2, b3[2]); + } + + @Test + void ofFloat() { + float v1 = 'x'; + float v2 = 'y'; + float[] b0 = null; + float[] b1 = Arr.of(b0); + float[] b2 = Arr.of(v1, v2); + + Assertions.assertNotNull(b1); + Assertions.assertEquals(0, b1.length); + + Assertions.assertEquals(2, b2.length); + Assertions.assertEquals(v1, b2[0]); + Assertions.assertEquals(v2, b2[1]); + } + + @Test + void setFloat() { + float v1 = 'x'; + float v2 = 'y'; + float[] b1 = {v1, v2}; + float[] b2 = Arr.set(b1, 0, v2); + float[] b3 = Arr.set(b1, 2, v2); + + Assertions.assertSame(b1, b2); + Assertions.assertEquals(v2, b2[0]); + + Assertions.assertNotSame(b1, b3); + Assertions.assertEquals(3, b3.length); + Assertions.assertEquals(v2, b3[2]); + } + + @Test + void ofDouble() { + double v1 = 'x'; + double v2 = 'y'; + double[] b0 = null; + double[] b1 = Arr.of(b0); + double[] b2 = Arr.of(v1, v2); + + Assertions.assertNotNull(b1); + Assertions.assertEquals(0, b1.length); + + Assertions.assertEquals(2, b2.length); + Assertions.assertEquals(v1, b2[0]); + Assertions.assertEquals(v2, b2[1]); + } + + @Test + void setDouble() { + double v1 = 'x'; + double v2 = 'y'; + double[] b1 = {v1, v2}; + double[] b2 = Arr.set(b1, 0, v2); + double[] b3 = Arr.set(b1, 2, v2); + + Assertions.assertSame(b1, b2); + Assertions.assertEquals(v2, b2[0]); + + Assertions.assertNotSame(b1, b3); + Assertions.assertEquals(3, b3.length); + Assertions.assertEquals(v2, b3[2]); + } + +} \ No newline at end of file diff --git a/src/test/java/pro/fessional/mirana/data/DiffTest.java b/src/test/java/pro/fessional/mirana/data/DiffTest.java index cf2d3f4..3097198 100644 --- a/src/test/java/pro/fessional/mirana/data/DiffTest.java +++ b/src/test/java/pro/fessional/mirana/data/DiffTest.java @@ -2,10 +2,20 @@ import org.junit.jupiter.api.Test; +import pro.fessional.mirana.SystemOut; import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; +import java.util.function.Function; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** @@ -15,29 +25,108 @@ public class DiffTest { @Test - public void of1() { + public void v() { + Integer v1 = 1; + Integer v2 = 2; + Diff.V dv = new Diff.V<>(); + dv.setV1(v1); + dv.setV2(v2); + assertEquals(v1, dv.getV1()); + assertEquals(v2, dv.getV2()); + + + assertEquals(dv, Diff.v(v1, v2)); + SystemOut.println(dv); + } + + @Test + public void ofList1() { List a = Arrays.asList("A1", "AB"); List b = Arrays.asList("AB", "B1"); - Diff.S s = Diff.of(a, b); + Diff.S s1 = Diff.of(a, b); + Diff.S s2 = Diff.of(Collections.emptyList(), b); + Diff.S s3 = Diff.of(b, Collections.emptyList()); + + assertTrue(s1.aAndB.contains("AB") && s1.aAndB.size() == 1); + assertTrue(s1.aNotB.contains("A1") && s1.aNotB.size() == 1); + assertTrue(s1.bNotA.contains("B1") && s1.bNotA.size() == 1); + + HashSet s4 = new HashSet<>(b); + assertTrue(s2.aAndB.isEmpty()); + assertTrue(s2.aNotB.isEmpty()); + assertEquals(s4, s2.bNotA); + + assertTrue(s3.aAndB.isEmpty()); + assertTrue(s3.bNotA.isEmpty()); + assertEquals(s4, s3.aNotB); - assertTrue(s.aAndB.contains("AB") && s.aAndB.size() == 1); - assertTrue(s.aNotB.contains("A1") && s.aNotB.size() == 1); - assertTrue(s.bNotA.contains("B1") && s.bNotA.size() == 1); } @Test - public void of2() { + public void ofList2() { List a = Arrays.asList("1N", "2N", "3N"); List b = Arrays.asList("4D", "2N", "3O"); - Diff.D d = Diff.of(a, b, id -> { + + Function f1 = id -> { String s = id.substring(0, 1); if (s.equalsIgnoreCase("1")) return null; return s; - }, String::equalsIgnoreCase); - assertTrue(d.newInsert.contains("1N") && d.newInsert.size() == 1); - assertTrue(d.newUpdate.contains("3N") && d.newUpdate.size() == 1); - assertTrue(d.oldDelete.contains("4D") && d.oldDelete.size() == 1); - assertTrue(d.oldUpdate.contains("3O") && d.oldUpdate.size() == 1); - assertTrue(d.oldEqsNew.contains("2N") && d.oldEqsNew.size() == 1); + }; + + Diff.D d1 = Diff.of(a, b, f1, String::equalsIgnoreCase); + Diff.D d2 = Diff.of(Collections.emptyList(), b, f1, String::equalsIgnoreCase); + Diff.D d3 = Diff.of(b, Collections.emptyList(), f1, String::equalsIgnoreCase); + + HashSet d4 = new HashSet<>(b); + + assertTrue(d1.newInsert.contains("1N") && d1.newInsert.size() == 1); + assertTrue(d1.newUpdate.contains("3N") && d1.newUpdate.size() == 1); + assertTrue(d1.oldDelete.contains("4D") && d1.oldDelete.size() == 1); + assertTrue(d1.oldUpdate.contains("3O") && d1.oldUpdate.size() == 1); + assertTrue(d1.oldEqsNew.contains("2N") && d1.oldEqsNew.size() == 1); + + assertEquals(d4, d2.oldDelete); + assertTrue(d2.newInsert.isEmpty()); + assertTrue(d2.newUpdate.isEmpty()); + assertTrue(d2.oldUpdate.isEmpty()); + assertTrue(d2.oldEqsNew.isEmpty()); + + assertEquals(d4, d3.newInsert); + assertTrue(d3.oldDelete.isEmpty()); + assertTrue(d3.newUpdate.isEmpty()); + assertTrue(d3.oldUpdate.isEmpty()); + assertTrue(d3.oldEqsNew.isEmpty()); + } + + @Test + public void ofMap() { + Map a = new HashMap<>(); + a.put(1, "1N"); + a.put(2, "2N"); + a.put(3, "3N"); + + Map b = new HashMap<>(); + b.put(4, "4D"); + b.put(2, "2N"); + b.put(3, "3O"); + + + LinkedHashMap> d = Diff.of(a, b); + + Diff.V v1 = d.get(1); + assertNotNull(v1); + assertTrue(v1.onlyV1()); + + Diff.V v2 = d.get(2); + assertNotNull(v2); + assertTrue(v2.v1EqV2()); + + Diff.V v3 = d.get(3); + assertNotNull(v3); + assertFalse(v3.v1EqV2()); + + Diff.V v4 = d.get(4); + assertNotNull(v4); + assertTrue(v4.onlyV2()); } } \ No newline at end of file diff --git a/src/test/java/pro/fessional/mirana/data/ZTest.java b/src/test/java/pro/fessional/mirana/data/ZTest.java index 49da05f..ff787f1 100644 --- a/src/test/java/pro/fessional/mirana/data/ZTest.java +++ b/src/test/java/pro/fessional/mirana/data/ZTest.java @@ -8,6 +8,8 @@ import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; /** * @author trydofor @@ -23,6 +25,7 @@ public void testUniq() { U.of(1, "A"), U.of(2, "B") ); + assertSame(list, Z.uniq(list)); List> uniq = Z.uniq(list, U.Two::one, U.Two::two); assertEquals(uniq, Arrays.asList( U.of(1, "A"), @@ -35,6 +38,7 @@ public void testFind() { U.of(2, "B"), U.of(1, "A")); assertEquals(u, U.of(1, "A")); + assertNull(Z.find(it -> it.one() == 2, U.of(1, "A"))); } @Test @@ -44,11 +48,36 @@ public void testMake() { } @Test - public void testNotNull() { + public void notNull() { assertEquals("1", Z.notNull(null, "1")); assertEquals(Null.Str, Z.notNull(Null.Str, null, "1")); final String str = null; assertEquals("", Z.notNullSafe(Null.Str, str)); assertEquals("1", Z.notNullSafe(Null.Str, null, "1")); } + + @Test + public void notEmpty() { + assertEquals("1", Z.notEmpty(null, "1")); + assertEquals("1", Z.notEmpty(Null.Str, null, "1")); + final String str = null; + assertEquals("", Z.notEmptySafe(Null.Str, str)); + assertEquals("1", Z.notEmptySafe(Null.Str, null, "1")); + } + + @Test + public void notBlank() { + assertEquals("1", Z.notBlank(null, "1")); + assertEquals("1", Z.notBlank(Null.Str, null, "1")); + final String str = null; + assertEquals("", Z.notBlankSafe(Null.Str, str)); + assertEquals("1", Z.notBlankSafe(Null.Str, null, "1")); + } + + @Test + public void decimal() { + assertEquals(new BigDecimal("1"), Z.decimal(null, "1")); + assertEquals(1, Z.int32(null, "1")); + assertEquals(1L, Z.int64(null, "1")); + } } diff --git a/src/test/java/pro/fessional/mirana/evil/TweakingContextTest.java b/src/test/java/pro/fessional/mirana/evil/TweakingContextTest.java new file mode 100644 index 0000000..d49417f --- /dev/null +++ b/src/test/java/pro/fessional/mirana/evil/TweakingContextTest.java @@ -0,0 +1,45 @@ +package pro.fessional.mirana.evil; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +/** + * @author trydofor + * @since 2024-01-27 + */ +class TweakingContextTest { + + @Test + void resetThread() throws ThreadLocalAttention { + final TweakingContext ctx = new TweakingContext<>(() -> "d"); + + Assertions.assertEquals("d", ctx.defaultValue(false)); + Assertions.assertNull(ctx.globalValue(false)); + Assertions.assertNull(ctx.threadValue(false)); + Assertions.assertEquals("d", ctx.current(true)); + + ctx.initGlobal(() -> "g"); + Assertions.assertEquals("g", ctx.globalValue(false)); + Assertions.assertEquals("g", ctx.current(true)); + + ctx.initThread(new ThreadLocal<>(), true); + ctx.tweakThread(() -> "t"); + Assertions.assertEquals("t", ctx.threadValue(true)); + Assertions.assertEquals("t", ctx.current(true)); + + ctx.resetGlobal(); + Assertions.assertNull(ctx.globalValue(false)); + ctx.resetThread(); + Assertions.assertNull(ctx.threadValue(false)); + Assertions.assertEquals("d", ctx.current(true)); + + ctx.tweakThread("t2"); + Assertions.assertNull(ctx.globalValue(false)); + Assertions.assertEquals("t2", ctx.current(true)); + + ctx.tweakThread((String) null); + Assertions.assertNull(ctx.threadValue(false)); + Assertions.assertEquals("d", ctx.current(true)); + + } +} \ No newline at end of file diff --git a/src/test/java/pro/fessional/mirana/fake/FakeDateTest.java b/src/test/java/pro/fessional/mirana/fake/FakeDateTest.java index 0f25097..aaaea24 100644 --- a/src/test/java/pro/fessional/mirana/fake/FakeDateTest.java +++ b/src/test/java/pro/fessional/mirana/fake/FakeDateTest.java @@ -1,5 +1,6 @@ package pro.fessional.mirana.fake; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import pro.fessional.mirana.SystemOut; @@ -13,13 +14,22 @@ public class FakeDateTest { @Test - public void printDateTime() { + public void fake() { int off = 3; LocalDate min1 = LocalDate.of(2019, 5, 21); LocalDateTime min2 = LocalDateTime.of(2019, 5, 21, 12, 34, 56, 0); + LocalDateTime max = LocalDateTime.of(2019, 5, 21, 13, 0, 0); + for (int i = 0; i < 20; i++) { SystemOut.println(FakeDate.dateTime(min1, off * i)); + SystemOut.println(FakeDate.dateTime(min1, off * i, max.toLocalDate())); SystemOut.println(FakeDate.dateTime(min2, off * i)); } + + LocalDateTime d2 = FakeDate.dateTime(min2, off, max); + for (int i = 0; i < 10; i++) { + LocalDateTime d = FakeDate.dateTime(min2, off, max); + Assertions.assertEquals(d2, d); + } } } \ No newline at end of file diff --git a/src/test/java/pro/fessional/mirana/func/DclTest.java b/src/test/java/pro/fessional/mirana/func/DclTest.java index dc34de6..77b09a0 100644 --- a/src/test/java/pro/fessional/mirana/func/DclTest.java +++ b/src/test/java/pro/fessional/mirana/func/DclTest.java @@ -1,6 +1,11 @@ package pro.fessional.mirana.func; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import pro.fessional.mirana.SystemOut; +import pro.fessional.mirana.func.LazyHolder.Dog; + +import java.util.concurrent.atomic.AtomicInteger; /** * lazy initialization holder class idiom @@ -14,15 +19,41 @@ class DclTest { public void cat() { // no dog LazyHolder.coupleCat(); + Assertions.assertNull(System.getProperty("dog.saying")); } @Test public void dog() { - LazyHolder.singleDog(); + Dog dog = LazyHolder.singleDog(); + Assertions.assertNotNull(dog); + Assertions.assertNotNull(System.getProperty("dog.saying")); } - public static void main(String[] args) { - // no dog - LazyHolder.coupleCat(); + @Test + public void dcl() { + final AtomicInteger c1 = new AtomicInteger(0); + Dcl dcl = Dcl.of(c1::getAndIncrement); + + Assertions.assertTrue(dcl.isDirty()); + Integer l1 = dcl.runIfDirty(); + Assertions.assertEquals(0, l1); + Integer l2 = dcl.runIfDirty(); + Assertions.assertEquals(0, l2); + Assertions.assertFalse(dcl.isDirty()); + + dcl.setDirty(); + Integer l3 = dcl.runIfDirty(); + Assertions.assertEquals(1, l3); + dcl.setDirty(false); + Integer l4 = dcl.runIfDirty(); + Assertions.assertEquals(1, l4); + + final AtomicInteger c2 = new AtomicInteger(0); + Dcl d2 = Dcl.of(() -> { + c2.getAndIncrement(); + SystemOut.println(""); + }); + d2.runIfDirty(); + Assertions.assertEquals(1, c2.get()); } } diff --git a/src/test/java/pro/fessional/mirana/func/LazyHolder.java b/src/test/java/pro/fessional/mirana/func/LazyHolder.java index f81f460..df807a1 100644 --- a/src/test/java/pro/fessional/mirana/func/LazyHolder.java +++ b/src/test/java/pro/fessional/mirana/func/LazyHolder.java @@ -20,12 +20,13 @@ public static LazyHolder.Dog singleDog() { } public static void coupleCat() { - SystemOut.println("cat: miao"); + SystemOut.println("cat.saying: miao"); } public static class Dog { public Dog() { - SystemOut.println("dog: wang "); + System.setProperty("dog.saying","wang"); + SystemOut.println("dog.saying: wang"); } } } diff --git a/src/test/java/pro/fessional/mirana/i18n/I18nStringTest.java b/src/test/java/pro/fessional/mirana/i18n/I18nStringTest.java index 73cb6b4..b27bc28 100644 --- a/src/test/java/pro/fessional/mirana/i18n/I18nStringTest.java +++ b/src/test/java/pro/fessional/mirana/i18n/I18nStringTest.java @@ -1,10 +1,13 @@ package pro.fessional.mirana.i18n; import org.junit.jupiter.api.Test; +import pro.fessional.mirana.SystemOut; import java.util.Locale; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; /** * @author trydofor @@ -14,8 +17,26 @@ class I18nStringTest { @Test void test() { - I18nString is = new I18nString("200", "{0} is ok", "name"); - final String s = is.toString(Locale.ENGLISH); + I18nString s1 = new I18nString("200"); + assertEquals("200", s1.getCode()); + assertEquals("200", s1.getI18nCode()); + assertEquals("", s1.getHint()); + assertEquals("", s1.getI18nHint()); + assertEquals(0, s1.getArgs().length); + assertEquals(0, s1.getI18nArgs().length); + assertNull(s1.getI18n()); + s1.setI18n("i18n"); + assertEquals("i18n", s1.getI18n()); + assertFalse(s1.isEmpty()); + I18nString s2 = new I18nString("200", "name"); + assertEquals(s1, s2); + + SystemOut.println(s1); + SystemOut.println(s2); + + I18nString s3 = new I18nString("200", "{0} is ok", "name"); + final String s = s3.toString(Locale.ENGLISH); + assertEquals("name is ok", s); assertEquals("name is ok", s); } } diff --git a/src/test/java/pro/fessional/mirana/i18n/LocaleResolverTest.java b/src/test/java/pro/fessional/mirana/i18n/LocaleResolverTest.java index c0e1518..570dd9e 100644 --- a/src/test/java/pro/fessional/mirana/i18n/LocaleResolverTest.java +++ b/src/test/java/pro/fessional/mirana/i18n/LocaleResolverTest.java @@ -1,5 +1,7 @@ package pro.fessional.mirana.i18n; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import pro.fessional.mirana.SystemOut; @@ -26,18 +28,23 @@ public void print() { @Test public void resolve() { - SystemOut.println("zh-CN=" + LocaleResolver.locale("zh-CN")); - SystemOut.println("zh-cn=" + LocaleResolver.locale("zh-cn")); - SystemOut.println("ZH-CN=" + LocaleResolver.locale("ZH-CN")); - SystemOut.println("ZH-cn=" + LocaleResolver.locale("ZH-cn")); - SystemOut.println("CN=" + LocaleResolver.locale("CN")); - SystemOut.println("zh=" + LocaleResolver.locale("zh")); - SystemOut.println("zh_CN=" + LocaleResolver.locale("zh_CN")); - SystemOut.println("zh_cn=" + LocaleResolver.locale("zh_cn")); - SystemOut.println("ZH_CN=" + LocaleResolver.locale("ZH_CN")); + Assertions.assertEquals(Locale.SIMPLIFIED_CHINESE, LocaleResolver.locale("zh-CN")); + Assertions.assertEquals(Locale.SIMPLIFIED_CHINESE, LocaleResolver.locale("zh-cn")); + Assertions.assertEquals(Locale.SIMPLIFIED_CHINESE, LocaleResolver.locale("ZH-CN")); + Assertions.assertEquals(Locale.SIMPLIFIED_CHINESE, LocaleResolver.locale("ZH-cn")); + + Assertions.assertEquals(Locale.SIMPLIFIED_CHINESE, LocaleResolver.locale("zh_CN")); + Assertions.assertEquals(Locale.SIMPLIFIED_CHINESE, LocaleResolver.locale("zh_cn")); + Assertions.assertEquals(Locale.SIMPLIFIED_CHINESE, LocaleResolver.locale("ZH_CN")); + Assertions.assertEquals(Locale.SIMPLIFIED_CHINESE, LocaleResolver.locale("ZH_cn")); + Assertions.assertEquals(Locale.CHINESE, LocaleResolver.locale("zh")); + + Assertions.assertEquals(Locale.getDefault(), LocaleResolver.locale("und")); + } @Test + @Disabled("time test") public void loop() { long s1 = System.currentTimeMillis(); for (int i = 0; i < 100_000; i++) { diff --git a/src/test/java/pro/fessional/mirana/i18n/ZoneIdResolverTest.java b/src/test/java/pro/fessional/mirana/i18n/ZoneIdResolverTest.java index e4df1a1..08a793f 100644 --- a/src/test/java/pro/fessional/mirana/i18n/ZoneIdResolverTest.java +++ b/src/test/java/pro/fessional/mirana/i18n/ZoneIdResolverTest.java @@ -1,5 +1,7 @@ package pro.fessional.mirana.i18n; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import pro.fessional.mirana.SystemOut; @@ -23,18 +25,21 @@ public void old() { } @Test - public void print() { - SystemOut.println(ZoneIdResolver.zoneId("Asia/Shanghai")); - SystemOut.println(ZoneIdResolver.zoneId("ASIA/SHANGHAI")); - SystemOut.println(ZoneIdResolver.zoneId("asia/shanghai")); - SystemOut.println(ZoneIdResolver.zoneId("Shanghai")); - SystemOut.println(ZoneIdResolver.zoneId("ShangHai")); - SystemOut.println(ZoneIdResolver.timeZone("Asia/Shanghai")); - SystemOut.println(ZoneIdResolver.timeZone("Shanghai")); - SystemOut.println(ZoneIdResolver.timeZone("ShangHai")); + public void test() { + ZoneId zidSh = ZoneId.of("Asia/Shanghai"); + Assertions.assertEquals(zidSh, ZoneIdResolver.zoneId("Asia/Shanghai")); + Assertions.assertEquals(zidSh, ZoneIdResolver.zoneId("ASIA/SHANGHAI")); + Assertions.assertEquals(zidSh, ZoneIdResolver.zoneId("asia/shanghai")); + Assertions.assertEquals(zidSh, ZoneIdResolver.zoneId("Shanghai")); + Assertions.assertEquals(zidSh, ZoneIdResolver.zoneId("ShangHai")); + TimeZone tzSh = TimeZone.getTimeZone("Asia/Shanghai"); + Assertions.assertEquals(tzSh, ZoneIdResolver.timeZone("Asia/Shanghai")); + Assertions.assertEquals(tzSh, ZoneIdResolver.timeZone("Shanghai")); + Assertions.assertEquals(tzSh, ZoneIdResolver.timeZone("ShangHai")); } @Test + @Disabled("time test") public void loop() { long s0 = System.currentTimeMillis(); for (int i = 0; i < 100_000; i++) { diff --git a/src/test/java/pro/fessional/mirana/math/AnyIntegerUtilTest.java b/src/test/java/pro/fessional/mirana/math/AnyIntegerUtilTest.java index 35e6e2c..1668c5a 100644 --- a/src/test/java/pro/fessional/mirana/math/AnyIntegerUtilTest.java +++ b/src/test/java/pro/fessional/mirana/math/AnyIntegerUtilTest.java @@ -11,24 +11,90 @@ class AnyIntegerUtilTest { @Test - void next32() { + void valAll() { + Assertions.assertEquals(1L, AnyIntegerUtil.val64("1")); + Assertions.assertEquals(1L, AnyIntegerUtil.val64((String) null, 1L)); + Assertions.assertEquals(1L, AnyIntegerUtil.val64("", 1L)); + Assertions.assertEquals(1L, AnyIntegerUtil.val64(1)); + Assertions.assertEquals(1L, AnyIntegerUtil.val64((Integer) null, 1L)); + + Assertions.assertEquals(1, AnyIntegerUtil.val32("1")); + Assertions.assertEquals(1, AnyIntegerUtil.val32((String) null, 1)); + Assertions.assertEquals(1, AnyIntegerUtil.val32("", 1)); + Assertions.assertEquals(1, AnyIntegerUtil.val32(1)); + Assertions.assertEquals(1, AnyIntegerUtil.val32((Long) null, 1)); + + Assertions.assertEquals(1L, AnyIntegerUtil.obj64("1")); + Assertions.assertEquals(1L, AnyIntegerUtil.obj64((String) null, 1L)); + Assertions.assertEquals(1L, AnyIntegerUtil.obj64("", 1L)); + Assertions.assertEquals(1L, AnyIntegerUtil.obj64(1)); + Assertions.assertEquals(1L, AnyIntegerUtil.obj64((Integer) null, 1L)); + + Assertions.assertEquals(1, AnyIntegerUtil.obj32("1")); + Assertions.assertEquals(1, AnyIntegerUtil.obj32((String) null, 1)); + Assertions.assertEquals(1, AnyIntegerUtil.obj32("", 1)); + Assertions.assertEquals(1, AnyIntegerUtil.obj32(1)); + Assertions.assertEquals(1, AnyIntegerUtil.obj32((Long) null, 1)); + + Assertions.assertEquals("-10", AnyIntegerUtil.trimToInteger("-10.1")); + Assertions.assertEquals("10", AnyIntegerUtil.trimToInteger("10.1")); + } + + @Test + void equalsAll() { + Assertions.assertTrue(AnyIntegerUtil.equals(1L, 1L)); + Assertions.assertTrue(AnyIntegerUtil.equals(1, 1)); + Assertions.assertFalse(AnyIntegerUtil.equals((Long) null, 1L)); + Assertions.assertFalse(AnyIntegerUtil.equals((Integer) null, 1)); + } + + @Test + void stringAll() { + Assertions.assertEquals("1", AnyIntegerUtil.string(1L)); + Assertions.assertEquals("1", AnyIntegerUtil.string((Long) null, "1")); + Assertions.assertEquals("1", AnyIntegerUtil.string(1)); + Assertions.assertEquals("1", AnyIntegerUtil.string((Integer) null, "1")); + } + + @Test + void range32() { final int unit = 5; int next = 0; for (int i = 0; i < 100; i++) { if (i % unit == 0) next += unit; if (i <= 20) SystemOut.println("i=" + i + ", next=" + next); Assertions.assertEquals(next, AnyIntegerUtil.next32(i, unit)); + Assertions.assertEquals(next, AnyIntegerUtil.next32((Integer) i, unit)); + Assertions.assertEquals(next, AnyIntegerUtil.next32(String.valueOf(i), unit)); + } + int prev = -unit; + for (int i = 0; i < 100; i++) { + if (i % unit == 1) prev += unit; + if (i <= 20) SystemOut.println("i=" + i + ", prev=" + prev); + Assertions.assertEquals(prev, AnyIntegerUtil.prev32(i, unit)); + Assertions.assertEquals(prev, AnyIntegerUtil.prev32((Integer) i, unit)); + Assertions.assertEquals(prev, AnyIntegerUtil.prev32(String.valueOf(i), unit)); } } @Test - void prev32() { + void range64() { final int unit = 5; + int next = 0; + for (long i = 0; i < 100; i++) { + if (i % unit == 0) next += unit; + if (i <= 20) SystemOut.println("i=" + i + ", next=" + next); + Assertions.assertEquals(next, AnyIntegerUtil.next64(i, unit)); + Assertions.assertEquals(next, AnyIntegerUtil.next64((Long) i, unit)); + Assertions.assertEquals(next, AnyIntegerUtil.next64(String.valueOf(i), unit)); + } int prev = -unit; - for (int i = 0; i < 100; i++) { + for (long i = 0; i < 100; i++) { if (i % unit == 1) prev += unit; if (i <= 20) SystemOut.println("i=" + i + ", prev=" + prev); - Assertions.assertEquals(prev, AnyIntegerUtil.prev32(i, unit)); + Assertions.assertEquals(prev, AnyIntegerUtil.prev64(i, unit)); + Assertions.assertEquals(prev, AnyIntegerUtil.prev64((Long) i, unit)); + Assertions.assertEquals(prev, AnyIntegerUtil.prev64(String.valueOf(i), unit)); } } } diff --git a/src/test/java/pro/fessional/mirana/math/AverageDecimalTest.java b/src/test/java/pro/fessional/mirana/math/AverageDecimalTest.java index 538b803..13ec9a5 100644 --- a/src/test/java/pro/fessional/mirana/math/AverageDecimalTest.java +++ b/src/test/java/pro/fessional/mirana/math/AverageDecimalTest.java @@ -1,5 +1,6 @@ package pro.fessional.mirana.math; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import pro.fessional.mirana.SystemOut; @@ -13,6 +14,25 @@ */ class AverageDecimalTest { + @Test + void avg() { + AverageDecimal avg0 = AverageDecimal.of(BigDecimal.TEN, 5,1); + Assertions.assertEquals(new BigDecimal("2.0"), avg0.getAvgValue()); + Assertions.assertEquals(BigDecimal.TEN, avg0.total()); + Assertions.assertEquals(1, avg0.scale()); + Assertions.assertEquals(5, avg0.size()); + Assertions.assertEquals(new BigDecimal("0.1"), avg0.getPrecision()); + + AverageDecimal avg1 = AverageDecimal.of(BigDecimal.TEN, 3,1); + Assertions.assertEquals(new BigDecimal("3.3"), avg1.getAvgValue()); + Assertions.assertEquals(BigDecimal.TEN, avg1.total()); + Assertions.assertEquals(1, avg1.scale()); + Assertions.assertEquals(3, avg1.size()); + Assertions.assertEquals(new BigDecimal("0.1"), avg1.getPrecision()); + Assertions.assertEquals(new BigDecimal("3.4"), avg1.getFixValue()); + Assertions.assertEquals(1, avg1.getFixCount()); + } + @Test void of() { BigDecimal number = new BigDecimal(100); @@ -45,6 +65,5 @@ void of() { SystemOut.println("] = " + sum + " :" + (sum.compareTo(number) == 0)); assertEquals(0, sum.compareTo(number)); } - } } diff --git a/src/test/java/pro/fessional/mirana/math/BalanceDecimalTest.java b/src/test/java/pro/fessional/mirana/math/BalanceDecimalTest.java index 8a45afa..3ea65f5 100644 --- a/src/test/java/pro/fessional/mirana/math/BalanceDecimalTest.java +++ b/src/test/java/pro/fessional/mirana/math/BalanceDecimalTest.java @@ -1,5 +1,6 @@ package pro.fessional.mirana.math; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import pro.fessional.mirana.SystemOut; @@ -56,9 +57,15 @@ void testTen() { BalanceDecimal avg = BalanceDecimal.of(total, items, 2); final BigDecimal v1 = new BigDecimal("3.34"); final BigDecimal v2 = new BigDecimal("3.33"); - for (BigDecimal v : avg) { + for (int i = 0; i < 3; i++) { + BigDecimal v = avg.get(i); assertTrue(v1.equals(v) || v2.equals(v)); } + + Assertions.assertEquals(3, avg.size()); + Assertions.assertEquals(total, avg.total()); + Assertions.assertEquals(2, avg.scale()); + Assertions.assertEquals(new BigDecimal("0.01"), avg.getPrecision()); } @Test diff --git a/src/test/java/pro/fessional/mirana/math/BigDecimalUtilTest.java b/src/test/java/pro/fessional/mirana/math/BigDecimalUtilTest.java index 6041ddc..17c14ca 100644 --- a/src/test/java/pro/fessional/mirana/math/BigDecimalUtilTest.java +++ b/src/test/java/pro/fessional/mirana/math/BigDecimalUtilTest.java @@ -4,13 +4,17 @@ import org.junit.jupiter.api.Test; import java.math.BigDecimal; +import java.math.BigInteger; import java.math.RoundingMode; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; +import java.util.Objects; import static java.math.BigDecimal.ONE; import static java.math.BigDecimal.TEN; import static java.math.BigDecimal.ZERO; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; @@ -30,6 +34,14 @@ public void add() { assertEquals(ONE, BigDecimalUtil.add(ONE, null, null, null)); assertEquals(TEN, BigDecimalUtil.add(ONE, null, NINE)); assertEquals(TEN, BigDecimalUtil.add(ONE, NINE, null, null)); + + assertEquals(new BigDecimal("16"), BigDecimalUtil.add(1, "10", 5L)); + List list = Arrays.asList(1, "10", 5L); + assertEquals(new BigDecimal("16"), BigDecimalUtil.addMap(list)); + assertEquals(new BigDecimal("16"), BigDecimalUtil.addMap(list, Object::toString)); + + assertEquals(TEN, BigDecimalUtil.addElse(TEN, null, null)); + assertEquals(ZERO, BigDecimalUtil.addElse(TEN, null, ZERO)); } @Test @@ -39,16 +51,29 @@ public void sub() { assertEquals(ZERO, BigDecimalUtil.sub(ONE, ONE, null, null)); assertEquals(NEG1, BigDecimalUtil.sub(ONE, ONE, ONE)); assertEquals(NEG1, BigDecimalUtil.sub(ZERO, null, ONE)); + List lst = Arrays.asList(1, "2", 3L); + assertEquals(new BigDecimal("4"), BigDecimalUtil.subMap("10", lst)); + assertEquals(new BigDecimal("4"), BigDecimalUtil.subMap("10", lst, Object::toString)); } @Test public void mul() { assertNull(BigDecimalUtil.mulNull(null, null, null, null)); + assertEquals(ONE, BigDecimalUtil.mul(ONE, null)); assertEquals(ONE, BigDecimalUtil.mul(ONE, null, null, null)); assertEquals(ONE, BigDecimalUtil.mul(ONE, ONE, null, null)); assertEquals(ONE, BigDecimalUtil.mul(null, ONE, ONE)); assertEquals(ONE, BigDecimalUtil.mul(ONE, null, ONE)); assertEquals(TEN, BigDecimalUtil.mul(ONE, "2", "5")); + assertEquals(TEN, BigDecimalUtil.mulElse(ONE, "2", "5")); + assertEquals(TEN, BigDecimalUtil.mulElse(TEN, null, null)); + + List lst = Arrays.asList(ONE, "2", 5); + assertEquals(TEN, BigDecimalUtil.prd(ONE, "2", "5")); + assertEquals(TEN, BigDecimalUtil.mulMap(lst)); + assertEquals(TEN, BigDecimalUtil.mulMap(lst, Object::toString)); + assertEquals(TEN, BigDecimalUtil.prdMap(lst)); + assertEquals(TEN, BigDecimalUtil.prdMap(lst, Object::toString)); } @Test @@ -57,15 +82,30 @@ public void div() { assertEquals(ONE, BigDecimalUtil.div(ONE, ONE, ONE)); assertEquals(ONE, BigDecimalUtil.div(TEN, "5", "2")); assertEquals(ONE, BigDecimalUtil.div(TEN, "5", null, "2")); + + Iterable list = Arrays.asList("5", null, "2"); + assertEquals(ONE, BigDecimalUtil.divMap(TEN, list)); + assertEquals(ONE, BigDecimalUtil.divMap(TEN, list, it -> it)); + } + + @Test + public void powNeg() { + assertEquals(TEN, BigDecimalUtil.pow(TEN, 1)); + assertNull(BigDecimalUtil.powNull(null, 1)); + assertEquals(TEN, BigDecimalUtil.neg("-10")); + assertNull(BigDecimalUtil.negNull(null)); } @Test public void string() { + assertEquals("0", BigDecimalUtil.string(ZERO)); assertEquals("0", BigDecimalUtil.string(ZERO, 0)); + assertEquals("0", BigDecimalUtil.string(null, "0")); assertEquals("0.0", BigDecimalUtil.string(ZERO, 1)); assertEquals("0.00", BigDecimalUtil.string(ZERO, 2)); assertEquals("1.00", BigDecimalUtil.string(ONE, 2)); assertEquals("10", BigDecimalUtil.string(ONE, -1)); + assertEquals("1", BigDecimalUtil.string(new BigDecimal("1.00"), true)); assertEquals("1", BigDecimalUtil.string(new BigDecimal("1.00"), 1, true)); } @@ -76,16 +116,57 @@ public void testObject() { assertEquals(new BigDecimal("0.00"), BigDecimalUtil.object("0.00")); assertEquals(new BigDecimal("1.00"), BigDecimalUtil.object("1.00")); assertEquals(new BigDecimal("10"), BigDecimalUtil.object("10")); + assertEquals(new BigDecimal("10"), BigDecimalUtil.object(10)); + assertEquals(new BigDecimal("10"), BigDecimalUtil.object(10L)); + assertEquals(new BigDecimal("10"), BigDecimalUtil.object(10F).setScale(0, RoundingMode.FLOOR)); + assertEquals(new BigDecimal("10"), BigDecimalUtil.object(10D).setScale(0, RoundingMode.FLOOR)); + assertEquals(new BigDecimal("10"), BigDecimalUtil.object(BigInteger.TEN)); + + BigDecimal[] arr = BigDecimalUtil.objects(TEN, 1, (Long) null, 0L); + assertArrayEquals(new BigDecimal[]{ONE, TEN, ZERO}, arr); + } + + @Test + public void notNull() { + assertEquals(TEN, BigDecimalUtil.notNull(null, "10")); + assertEquals(TEN, BigDecimalUtil.ifElse(false, null, "10")); + assertEquals(0, BigDecimalUtil.compareTo(10, "10")); } @Test public void avg() { - assertEquals(new BigDecimal("3.33"), BigDecimalUtil.avg(2, "3", 5L).setScale(2, RoundingMode.FLOOR)); - assertEquals(new BigDecimal("3.33"), BigDecimalUtil.avg( + BigDecimal d33 = new BigDecimal("3.33"); + assertEquals(d33, BigDecimalUtil.avg(2, "3", 5L).setScale(2, RoundingMode.FLOOR)); + assertEquals(d33, BigDecimalUtil.avg( new BigDecimal("2"), null, new BigDecimal("3"), null, new BigDecimal("5") ).setScale(2, RoundingMode.FLOOR)); + + List av1 = Arrays.asList(2, "3", 5L); + assertEquals(d33, BigDecimalUtil.avgMap(av1).setScale(2, RoundingMode.FLOOR)); + assertEquals(d33, BigDecimalUtil.avgMap(av1, Object::toString).setScale(2, RoundingMode.FLOOR)); + assertEquals(d33, BigDecimalUtil.avgMapNull(av1, Object::toString).setScale(2, RoundingMode.FLOOR)); + } + + @Test + public void max() { + assertEquals(TEN, BigDecimalUtil.max(2, "10", 5L)); + assertEquals(TEN, BigDecimalUtil.maxNull(2, "10", 5L)); + } + + @Test + public void min() { + assertEquals(ONE, BigDecimalUtil.min(1, "10", 5L)); + assertEquals(ONE, BigDecimalUtil.min(1, "10", 5L)); + } + + @Test + public void sum() { + assertEquals(new BigDecimal("16"), BigDecimalUtil.sum(1, "10", 5L)); + List list = Arrays.asList(1, "10", 5L); + assertEquals(new BigDecimal("16"), BigDecimalUtil.sumMap(list)); + assertEquals(new BigDecimal("16"), BigDecimalUtil.sumMap(list, Object::toString)); } @Test @@ -103,8 +184,18 @@ public void w() { BigDecimal n2 = BigDecimalUtil.w(TEN, 2) .add(ONE) + .mul(ONE) .mul("2.0", null, null, ONE, ONE) + .mulIf(false, ZERO, ONE) + .mulMap(Arrays.asList(null, null, ONE, ONE)) + .mulMap(Arrays.asList(ONE, ONE), Objects::toString) + .div(ONE) .div(ONE, ONE) + .divIf(true, ONE, ZERO) + .divMap(Arrays.asList(ONE, ONE)) + .divMap(Arrays.asList(ONE, ONE),Objects::toString) + .neg() + .neg() .pow(2) .resultFloor(); @@ -127,6 +218,21 @@ public void unitUp() { assertEquals(new BigDecimal("2.00"), BigDecimalUtil.unitUp("1.61", unit, down)); } + @Test + public void unitDown() { + final BigDecimal unit = new BigDecimal("0.50"); + final BigDecimal upto = new BigDecimal("0.10"); + + assertEquals(new BigDecimal("1.00"), BigDecimalUtil.unitDown("1.09", unit, upto)); + assertEquals(new BigDecimal("1.00"), BigDecimalUtil.unitDown("1.4001", unit, upto)); + assertEquals(new BigDecimal("1.00"), BigDecimalUtil.unitDown("1.40", unit, upto)); + assertEquals(new BigDecimal("1.50"), BigDecimalUtil.unitDown("1.41", unit, upto)); + assertEquals(new BigDecimal("1.50"), BigDecimalUtil.unitDown("1.51", unit, upto)); + assertEquals(new BigDecimal("1.50"), BigDecimalUtil.unitDown("1.59", unit, upto)); + assertEquals(new BigDecimal("1.50"), BigDecimalUtil.unitDown("1.90", unit, upto)); + assertEquals(new BigDecimal("2.00"), BigDecimalUtil.unitDown("1.91", unit, upto)); + } + public static class Ins { private String dec; diff --git a/src/test/java/pro/fessional/mirana/stat/GitStatTest.java b/src/test/java/pro/fessional/mirana/stat/GitStatTest.java index 46dc917..13ad358 100644 --- a/src/test/java/pro/fessional/mirana/stat/GitStatTest.java +++ b/src/test/java/pro/fessional/mirana/stat/GitStatTest.java @@ -29,7 +29,7 @@ public void mysql() { dataSource.setPassword("moilioncircle"); dataSource.setServerName("127.0.0.1"); - File workDir = new File("/Users/trydofor/Workspace/github.com/pro.fessional.wings"); + File workDir = new File("/Users/trydofor/Workspace/github-com/professional-wings"); List infos = GitStat.logAll(workDir, "2 weeks ago", "2020-10-01"); GitStat.saveMysql(infos, "git_log_wings", dataSource); } diff --git a/src/test/java/pro/fessional/mirana/stat/JvmStatTest.java b/src/test/java/pro/fessional/mirana/stat/JvmStatTest.java index 53651ab..374823e 100644 --- a/src/test/java/pro/fessional/mirana/stat/JvmStatTest.java +++ b/src/test/java/pro/fessional/mirana/stat/JvmStatTest.java @@ -1,6 +1,9 @@ package pro.fessional.mirana.stat; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import pro.fessional.mirana.SystemOut; +import pro.fessional.mirana.time.Sleep; import java.util.concurrent.atomic.AtomicInteger; @@ -10,8 +13,24 @@ */ class JvmStatTest { - @SuppressWarnings("all") - public static void main(String[] args) throws Exception { + @Test + void infoStat(){ + int pid = JvmStat.jvmPid(); + String jvm = JvmStat.jvmName(); + SystemOut.println(pid); + SystemOut.println(jvm); + + final JvmStat.Stat stat = JvmStat.stat(); + JvmStat.buildCpuLoad(stat); + JvmStat.buildMemory(stat); + JvmStat.buildThread(stat); + JvmStat.buildRuntime(stat); + SystemOut.println(stat); + } + + @Test + @Disabled("pressure") + void pressure() { final int p = Runtime.getRuntime().availableProcessors(); SystemOut.println("Processors=" + p); AtomicInteger count = new AtomicInteger(p); @@ -33,7 +52,7 @@ public static void main(String[] args) throws Exception { + ", free=" + runtime.freeMemory() + ", max=" + runtime.maxMemory() ); - Thread.sleep(1_000L); + Sleep.ignoreInterrupt(1_000L); } } } diff --git a/src/test/java/pro/fessional/mirana/stat/WordStatTest.java b/src/test/java/pro/fessional/mirana/stat/WordStatTest.java index 4aac583..f516813 100644 --- a/src/test/java/pro/fessional/mirana/stat/WordStatTest.java +++ b/src/test/java/pro/fessional/mirana/stat/WordStatTest.java @@ -1,7 +1,6 @@ package pro.fessional.mirana.stat; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.nio.file.Paths; @@ -27,9 +26,8 @@ void statWord() { } @Test - @Disabled - void printRuoYi() { + void infoHere() { WordStat ws = new WordStat(); - ws.printJavax(Paths.get("/Volumes/WORK-CS/Workspace/gitee.com/RuoYi")); + ws.printJavax(Paths.get(".")); } } diff --git a/src/test/java/pro/fessional/mirana/text/BarStringTest.java b/src/test/java/pro/fessional/mirana/text/BarStringTest.java index 6b4dfed..e217d57 100644 --- a/src/test/java/pro/fessional/mirana/text/BarStringTest.java +++ b/src/test/java/pro/fessional/mirana/text/BarStringTest.java @@ -5,6 +5,8 @@ import java.math.BigDecimal; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.Iterator; /** @@ -22,6 +24,32 @@ void split0() { Assertions.assertEquals(0, split.size()); } + @Test + void append() { + BarString bs = new BarString(); + bs.append("str"); + bs.append(BigDecimal.ONE); + bs.append((Object) null); + bs.append(1L); + bs.append(2); + bs.append(true); + bs.append(3F); + bs.append(4D); + String str = bs.toString(); + + ArrayList values = bs.values(true); + Assertions.assertEquals(values, BarString.split(str)); + + String v0 = values.get(0); + String ve = str.substring(v0.length() + 2, str.length() - 1); + Assertions.assertEquals(Arrays.asList(v0, ve), BarString.split(str, 2)); + + String bad = str.substring(0, str.length() - 1); + Assertions.assertEquals(Collections.singletonList(bad), BarString.split(bad, 2, true)); + + Assertions.assertEquals(Collections.emptyList(), BarString.split(str, 50, true)); + } + @Test void split1() { BarString bs = new BarString(); diff --git a/src/test/java/pro/fessional/mirana/text/BuilderHelperTest.java b/src/test/java/pro/fessional/mirana/text/BuilderHelperTest.java index 262ffec..0488646 100644 --- a/src/test/java/pro/fessional/mirana/text/BuilderHelperTest.java +++ b/src/test/java/pro/fessional/mirana/text/BuilderHelperTest.java @@ -3,11 +3,13 @@ import org.junit.jupiter.api.Test; import pro.fessional.mirana.data.Arr; +import pro.fessional.mirana.evil.ThreadLocalAttention; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author trydofor @@ -17,11 +19,47 @@ public class BuilderHelperTest { @Test public void append() { - BuilderHelper.W sb = BuilderHelper.w(); - sb.append(1); - sb.append((String) null); - sb.append(2); - assertEquals("12", sb.toString()); + BuilderHelper.W sbw = BuilderHelper.w(); + sbw.append(true); + sbw.append(1); + sbw.append(2L); + sbw.append(3.0F); + sbw.append(4.0D); + sbw.append('5'); + sbw.append(new StringBuffer("6")); + sbw.append("7".toCharArray(), 0, 1); + sbw.append((Object) null); + sbw.append("8"); + sbw.append("9", 0, 1); + sbw.append("0".toCharArray()); + assertEquals("true123.04.0567890", sbw.toString()); + sbw.delete(1); + sbw.delete(0, 2); + assertEquals("ue123.04.056789", sbw.toString()); + sbw.delete(); + assertEquals("", sbw.toString()); + sbw.join(",", 1, 2); + sbw.join(",", Arrays.asList(3, 4)); + sbw.join(true, ",", 5, null, 6); + sbw.join(true, ",", Arrays.asList(7, null, 8)); + sbw.join(true, ",", Arrays.asList(9, null, 0), it -> it); + sbw.join(",", Arrays.asList("a", null, "b"), it -> it); + String expected = "1,23,45,67,89,0a,,b"; + assertEquals(expected, sbw.toString()); + assertEquals(expected.length(), sbw.length()); + assertEquals(expected.charAt(3), sbw.charAt(3)); + assertEquals(expected.substring(0, 3), sbw.subSequence(0, 3).toString()); + } + + @Test + public void normal() { + StringBuilder sb = new StringBuilder(); + BuilderHelper.append(sb, null); + BuilderHelper.append(sb, "1,".toCharArray()); + BuilderHelper.join(sb, ",", Arrays.asList("a", null, "b"), it -> it); + BuilderHelper.append(sb, ",2,"); + BuilderHelper.join(sb, true, ",", Arrays.asList("a", null, "b"), it -> it); + assertEquals("1,a,,b,2,a,b", sb.toString()); } @Test @@ -41,7 +79,7 @@ public void delete() { @Test public void join() { StringBuilder sb = new StringBuilder(); - Object[] arr = Arr.of(1, "2", 3L, null, '5'); + Object[] arr = Arr.obj(1, "2", 3L, null, '5'); BuilderHelper.join(sb, ",", arr); assertEquals("1,2,3,,5", sb.toString()); @@ -58,4 +96,11 @@ public void join() { BuilderHelper.join(sb, true, ",", lst); assertEquals("1,2,3,5", sb.toString()); } + + @Test + public void holder() throws ThreadLocalAttention { + BuilderHolder hd = new BuilderHolder(1, 10); + StringBuilder sb = new StringBuilder("1234567890abcdefg"); + assertTrue(hd.anewValue(sb)); + } } \ No newline at end of file diff --git a/src/test/java/pro/fessional/mirana/text/CaseSwitcherTest.java b/src/test/java/pro/fessional/mirana/text/CaseSwitcherTest.java index e0c76a0..306b29c 100644 --- a/src/test/java/pro/fessional/mirana/text/CaseSwitcherTest.java +++ b/src/test/java/pro/fessional/mirana/text/CaseSwitcherTest.java @@ -80,6 +80,29 @@ public void testSnake() { assertEquals("hello_world_abc", CaseSwitcher.snake("HelloWORldAbc")); } + @Test + public void testDot() { + assertEquals("hello123", CaseSwitcher.dot("hello123")); + assertEquals("hello.123", CaseSwitcher.dot("hello_123")); + assertEquals("hello.123", CaseSwitcher.dot("HELLO_123")); + assertEquals("hello.123", CaseSwitcher.dot("Hello-123")); + assertEquals("hello.123", CaseSwitcher.dot("hello-123")); + + assertEquals("hello.world", CaseSwitcher.dot("hello_world")); + assertEquals("hello.world", CaseSwitcher.dot("HELLO_WORLD")); + assertEquals("hello.world", CaseSwitcher.dot("Hello-World")); + assertEquals("hello.world", CaseSwitcher.dot("hello-world")); + assertEquals("hello.world", CaseSwitcher.dot("helloWorld")); + assertEquals("hello.world.abc", CaseSwitcher.dot("HelloWorldAbc")); + + assertEquals("hello.world", CaseSwitcher.dot("hello__world")); + assertEquals("hello.world", CaseSwitcher.dot("HELLO__WORLD")); + assertEquals("hello.world", CaseSwitcher.dot("Hello--World")); + assertEquals("hello.world", CaseSwitcher.dot("hello--world")); + assertEquals("hello.world", CaseSwitcher.dot("helloWORld")); + assertEquals("hello.world.abc", CaseSwitcher.dot("HelloWORldAbc")); + } + @Test public void testPascal() { assertEquals("Hello123", CaseSwitcher.pascal("hello123")); diff --git a/src/test/java/pro/fessional/mirana/text/FormatUtilTest.java b/src/test/java/pro/fessional/mirana/text/FormatUtilTest.java index 9be5b91..a1cb61d 100644 --- a/src/test/java/pro/fessional/mirana/text/FormatUtilTest.java +++ b/src/test/java/pro/fessional/mirana/text/FormatUtilTest.java @@ -2,7 +2,14 @@ import org.junit.jupiter.api.Test; import pro.fessional.mirana.SystemOut; +import pro.fessional.mirana.evil.ThreadLocalAttention; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; /** @@ -37,6 +44,8 @@ public void count() { assertEquals(1, r2[1]); assertEquals(1, r2[2]); assertEquals(1, r2[3]); + assertEquals(0, FormatUtil.count(null,"")); + assertEquals(0, FormatUtil.count("", (String) null)); } @Test @@ -161,4 +170,45 @@ public void rightFix() { assertEquals("1234567890", FormatUtil.rightFix("1234567890", 10, '0')); assertEquals("1234567890", FormatUtil.rightFix("123456789012345678", 10, '0')); } + + @Test + public void holder() throws ThreadLocalAttention { + FormatHolder hd = new FormatHolder("%s"); + assertEquals("%s", hd.getPattern()); + } + + @Test + public void mess() { + assertEquals("a,b,c", FormatUtil.join(true, ",", Arrays.asList("a", "b", "c"))); + assertEquals("[true,false]", FormatUtil.toString(new boolean[]{true,false})); + assertEquals("[1,2]", FormatUtil.toString(new short[]{1,2})); + assertEquals("[1,2]", FormatUtil.toString(new int[]{1,2})); + assertEquals("[1,2]", FormatUtil.toString(new long[]{1L,2L})); + assertEquals("[1.0,2.0]", FormatUtil.toString(new float[]{1.0F,2.0F})); + assertEquals("[1.0,2.0]", FormatUtil.toString(new double[]{1.0D,2.0D})); + } + + @Test + public void sortParam() { + Map p1 = new HashMap<>(); + p1.put("k2", "v2"); + p1.put("k1", "v1"); + assertEquals("k1=v1&k2=v2", FormatUtil.sortParam(p1)); + + Map p2 = new TreeMap<>(); + p2.put("k2", "v2"); + p2.put("k1", "v1"); + assertEquals("k1=v1&k2=v2", FormatUtil.sortParam(p2)); + } + + @Test + public void fixArgs() { + assertArrayEquals(new Object[]{}, FormatUtil.fixArgs(0, "a", "b")); + assertArrayEquals(new Object[]{"a"}, FormatUtil.fixArgs(1, "a", "b")); + assertArrayEquals(new Object[]{"a","b"}, FormatUtil.fixArgs(2, "a", "b")); + assertArrayEquals(new Object[]{"a","b",""}, FormatUtil.fixArgs(3, "a", "b")); + assertArrayEquals(new Object[]{"a","",""}, FormatUtil.fixArgs(3, "a", null)); + Object[] args = null; + assertArrayEquals(new Object[]{"","",""}, FormatUtil.fixArgs(3, args)); + } } diff --git a/src/test/java/pro/fessional/mirana/text/FullCharUtilTest.java b/src/test/java/pro/fessional/mirana/text/FullCharUtilTest.java new file mode 100644 index 0000000..5867ba4 --- /dev/null +++ b/src/test/java/pro/fessional/mirana/text/FullCharUtilTest.java @@ -0,0 +1,47 @@ +package pro.fessional.mirana.text; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * @author trydofor + * @since 2024-01-28 + */ +class FullCharUtilTest { + + @Test + void leftCut() { + assertEquals("", FullCharUtil.leftCut("我爱你ivy", 0)); + assertEquals("", FullCharUtil.leftCut("我爱你ivy", 1)); + assertEquals("我", FullCharUtil.leftCut("我爱你ivy", 2)); + assertEquals("我", FullCharUtil.leftCut("我爱你ivy", 3)); + assertEquals("我爱", FullCharUtil.leftCut("我爱你ivy", 4)); + assertEquals("我爱", FullCharUtil.leftCut("我爱你ivy", 5)); + assertEquals("我爱你", FullCharUtil.leftCut("我爱你ivy", 6)); + assertEquals("我爱你i", FullCharUtil.leftCut("我爱你ivy", 7)); + assertEquals("我爱你iv", FullCharUtil.leftCut("我爱你ivy", 8)); + assertEquals("我爱你ivy", FullCharUtil.leftCut("我爱你ivy", 9)); + assertEquals("我爱你ivy", FullCharUtil.leftCut("我爱你ivy", 10)); + } + + @Test + void rightCut() { + assertEquals("", FullCharUtil.rightCut("我爱你ivy", 0)); + assertEquals("y", FullCharUtil.rightCut("我爱你ivy", 1)); + assertEquals("vy", FullCharUtil.rightCut("我爱你ivy", 2)); + assertEquals("ivy", FullCharUtil.rightCut("我爱你ivy", 3)); + assertEquals("ivy", FullCharUtil.rightCut("我爱你ivy", 4)); + assertEquals("你ivy", FullCharUtil.rightCut("我爱你ivy", 5)); + assertEquals("你ivy", FullCharUtil.rightCut("我爱你ivy", 6)); + assertEquals("爱你ivy", FullCharUtil.rightCut("我爱你ivy", 7)); + assertEquals("爱你ivy", FullCharUtil.rightCut("我爱你ivy", 8)); + assertEquals("我爱你ivy", FullCharUtil.rightCut("我爱你ivy", 9)); + assertEquals("我爱你ivy", FullCharUtil.rightCut("我爱你ivy", 10)); + } + + @Test + void countHalf() { + assertEquals(9, FullCharUtil.countHalf("我爱你ivy")); + } +} \ No newline at end of file diff --git a/src/test/java/pro/fessional/mirana/text/JsonTemplateTest.java b/src/test/java/pro/fessional/mirana/text/JsonTemplateTest.java index 70972c4..018de15 100644 --- a/src/test/java/pro/fessional/mirana/text/JsonTemplateTest.java +++ b/src/test/java/pro/fessional/mirana/text/JsonTemplateTest.java @@ -4,6 +4,7 @@ import com.alibaba.fastjson2.JSONObject; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import pro.fessional.mirana.bits.Base64; import java.util.Arrays; import java.util.Collections; @@ -23,6 +24,33 @@ void testEmpty() { Assertions.assertEquals("[]", j2); } + @Test + void testArray() { + byte[] bytes = "ab".getBytes(); + final String j1 = JsonTemplate.obj(obj -> { + obj.putVal("charArray", "ab".toCharArray()); + obj.putVal("byteArray", bytes); + obj.putVal("boolArray", new boolean[]{true, false}); + obj.putVal("shortArray", new short[]{1, 2}); + obj.putVal("intArray", new int[]{3, 4}); + obj.putVal("longArray", new long[]{3, 4}); + obj.putVal("floatArray", new float[]{5.0F, 6.0F}); + obj.putVal("doubleArray", new double[]{7.0D, 8.0D}); + obj.putArr("objArr", new Object[]{1, 2}); + }); + Assertions.assertEquals("{" + + "\"charArray\":\"ab\"," + + "\"byteArray\":\"" + Base64.encode(bytes) + "\"," + + "\"boolArray\":[true,false]," + + "\"shortArray\":[1,2]," + + "\"intArray\":[3,4]," + + "\"longArray\":[3,4]," + + "\"floatArray\":[5.0,6.0]," + + "\"doubleArray\":[7.0,8.0]," + + "\"objArr\":[1,2]" + + "}", j1); + } + @Test void testSimple() { final String j1 = JsonTemplate.obj(obj -> { @@ -33,9 +61,10 @@ void testSimple() { Assertions.assertEquals("{\"msgtype\":\"mar\\\"kd\\\\own\",\"success\":true}", j1); final String j2 = JsonTemplate.arr(arr -> { arr.addVal(true); - arr.addVal(1).addVal("mar\"kd\\own"); + arr.addVal(new Object[]{1, 2}) + .addVal("mar\"kd\\own"); }); - Assertions.assertEquals("[true,1,\"mar\\\"kd\\\\own\"]", j2); + Assertions.assertEquals("[true,1,2,\"mar\\\"kd\\\\own\"]", j2); } @Test @@ -55,14 +84,14 @@ void testNested() { ).replaceAll("[ \n]+", ""); final String j1 = JsonTemplate.obj(top -> top - .putObj("at", ob -> ob - .putArr("atMobiles", ar -> ar - .addVal("180xxxxxx")) - .putVal("isAtAll", false)) - .putObj("text", ob -> ob - .putVal("content", "Look how the prey scatters before us.")) - .putVal("msgtype", "text")) - .replaceAll("[ \n]+", ""); + .putObj("at", ob -> ob + .putArr("atMobiles", ar -> ar + .addVal("180xxxxxx")) + .putVal("isAtAll", false)) + .putObj("text", ob -> ob + .putVal("content", "Look how the prey scatters before us.")) + .putVal("msgtype", "text")) + .replaceAll("[ \n]+", ""); Assertions.assertEquals(r1, j1); final String f1 = new JSONObject() diff --git a/src/test/java/pro/fessional/mirana/text/WhiteUtilTest.java b/src/test/java/pro/fessional/mirana/text/WhiteUtilTest.java index 508ea07..3e91201 100644 --- a/src/test/java/pro/fessional/mirana/text/WhiteUtilTest.java +++ b/src/test/java/pro/fessional/mirana/text/WhiteUtilTest.java @@ -3,6 +3,8 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import java.util.Arrays; + /** * @author trydofor * @since 2023-10-27 @@ -23,6 +25,18 @@ void trim() { Assertions.assertEquals("", WhiteUtil.trim(" \t\n\r ", ' ', '\t', '\n', '\r')); Assertions.assertEquals("", WhiteUtil.trim("a \ta\na\r a", ' ', '\t', 'a', '\n', '\r')); + Assertions.assertEquals("a\na", WhiteUtil.trim(" \ta\na\r ", ' ', '\t', '\n', '\r')); + } + + @Test + void mess() { + Assertions.assertTrue(WhiteUtil.isWhiteSpace('\t')); + Assertions.assertTrue(WhiteUtil.isAllWhite(" \t\n\r ")); + Assertions.assertEquals("", WhiteUtil.delete(" \t\n\r ")); + Assertions.assertEquals("a", WhiteUtil.delete(" \ta\n\r ")); + Assertions.assertTrue(WhiteUtil.equalsWithDeleted(" \ta\n\r ", "a")); + Assertions.assertTrue(WhiteUtil.equalsWithSpaced(" \ta\n\r ", " a ")); + Assertions.assertEquals(Arrays.asList("a", "b"), WhiteUtil.lines("a\nb")); } @Test diff --git a/src/test/java/pro/fessional/mirana/text/WildcardTest.java b/src/test/java/pro/fessional/mirana/text/WildcardTest.java index 42297ef..e868ad3 100644 --- a/src/test/java/pro/fessional/mirana/text/WildcardTest.java +++ b/src/test/java/pro/fessional/mirana/text/WildcardTest.java @@ -17,13 +17,13 @@ public class WildcardTest { @Test public void pattern() { - assertArrayEquals(Arr.of("*", ".doc"), Wildcard.compile("*.doc")); - assertArrayEquals(Arr.of("abc?.doc"), Wildcard.compile("abc?.doc")); - assertArrayEquals(Arr.of("*", ".doc"), Wildcard.compile("**.doc")); - assertArrayEquals(Arr.of("??", "*", ".doc"), Wildcard.compile("??*.doc")); - assertArrayEquals(Arr.of("?", "*", ".doc"), Wildcard.compile("**?**.doc")); - assertArrayEquals(Arr.of("?", "*"), Wildcard.compile("**?**")); - assertArrayEquals(Arr.of("?", "*", ".doc??", "*"), Wildcard.compile("**?**.doc??*")); + assertArrayEquals(Arr.obj("*", ".doc"), Wildcard.compile("*.doc")); + assertArrayEquals(Arr.obj("abc?.doc"), Wildcard.compile("abc?.doc")); + assertArrayEquals(Arr.obj("*", ".doc"), Wildcard.compile("**.doc")); + assertArrayEquals(Arr.obj("??", "*", ".doc"), Wildcard.compile("??*.doc")); + assertArrayEquals(Arr.obj("?", "*", ".doc"), Wildcard.compile("**?**.doc")); + assertArrayEquals(Arr.obj("?", "*"), Wildcard.compile("**?**")); + assertArrayEquals(Arr.obj("?", "*", ".doc??", "*"), Wildcard.compile("**?**.doc??*")); } @Test diff --git a/src/test/java/pro/fessional/mirana/time/DateFormatterTest.java b/src/test/java/pro/fessional/mirana/time/DateFormatterTest.java index faa4ffc..d551a74 100644 --- a/src/test/java/pro/fessional/mirana/time/DateFormatterTest.java +++ b/src/test/java/pro/fessional/mirana/time/DateFormatterTest.java @@ -1,8 +1,10 @@ package pro.fessional.mirana.time; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import pro.fessional.mirana.SystemOut; +import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; @@ -10,41 +12,172 @@ import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; +import java.util.TimeZone; import static org.junit.jupiter.api.Assertions.assertEquals; import static pro.fessional.mirana.time.DateFormatter.FMT_DATE_PSE; import static pro.fessional.mirana.time.DateFormatter.FMT_TIME_PSE; +import static pro.fessional.mirana.time.DateFormatter.PTN_FULL_19; +import static pro.fessional.mirana.time.DateFormatter.PTN_FULL_23; /** * @author trydofor * @since 2019-06-28 */ public class DateFormatterTest { + final ZoneId tz8 = ZoneId.of("GMT+8"); + final ZoneId tz9 = ZoneId.of("GMT+9"); + final LocalDate ld = LocalDate.of(2017, 4, 26); + final LocalTime lm9 = LocalTime.of(12, 34, 56, 789_000_000); + final ZonedDateTime zdt9 = ZonedDateTime.of(ld, lm9, tz8); + final LocalDateTime ldt9 = LocalDateTime.of(ld, lm9); + final Date ud9 = new Date(zdt9.toEpochSecond() * 1000L + 789); + + final LocalTime lm0 = LocalTime.of(12, 34, 56, 0); + final ZonedDateTime zdt0 = ZonedDateTime.of(ld, lm0, tz8); + final LocalDateTime ldt0 = LocalDateTime.of(ld, lm0); + final Date ud0 = new Date(zdt0.toEpochSecond() * 1000L); + + @Test + public void utilDate() { + // SimpleDateFormat, Calendar and util.Date deps on System defaultTimezone + TimeZone df = TimeZone.getDefault(); + try { + TimeZone.setDefault(TimeZone.getTimeZone("GMT+8")); + DateFormatter.DATE_FORMAT_19.remove(); + DateFormatter.DATE_FORMAT_23.remove(); + + Assertions.assertEquals("2017-04-26 12:34:56.789", DateFormatter.full(ud9)); + Assertions.assertEquals("2017-04-26 13:34:56.789", DateFormatter.full(ud9, tz9)); + Assertions.assertEquals("2017-04-26 12:34:56", DateFormatter.full19(ud9)); + Assertions.assertEquals("2017-04-26 13:34:56", DateFormatter.full19(ud9, tz9)); + Assertions.assertEquals("2017-04-26 12:34:56.789", DateFormatter.full23(ud9)); + Assertions.assertEquals("2017-04-26 13:34:56.789", DateFormatter.full23(ud9, tz9)); + Assertions.assertEquals("2017-04-26 12:34:56.000", DateFormatter.full23(ud0)); + Assertions.assertEquals("2017-04-26 13:34:56.000", DateFormatter.full23(ud0, tz9)); + Assertions.assertEquals("2017-04-26", DateFormatter.date10(ud9)); + Assertions.assertEquals("2017-04-26", DateFormatter.date10(ud9, tz9)); + Assertions.assertEquals("12:34:56", DateFormatter.time08(ud9)); + Assertions.assertEquals("13:34:56", DateFormatter.time08(ud9, tz9)); + Assertions.assertEquals("12:34:56", DateFormatter.time08(ud0)); + Assertions.assertEquals("13:34:56", DateFormatter.time08(ud0, tz9)); + Assertions.assertEquals("12:34:56.789", DateFormatter.time(ud9)); + Assertions.assertEquals("13:34:56.789", DateFormatter.time(ud9, tz9)); + Assertions.assertEquals("12:34:56", DateFormatter.time(ud0)); + Assertions.assertEquals("13:34:56", DateFormatter.time(ud0, tz9)); + Assertions.assertEquals("12:34:56.789", DateFormatter.time12(ud9)); + Assertions.assertEquals("13:34:56.789", DateFormatter.time12(ud9, tz9)); + Assertions.assertEquals("12:34:56.000", DateFormatter.time12(ud0)); + Assertions.assertEquals("13:34:56.000", DateFormatter.time12(ud0, tz9)); + } + finally { + TimeZone.setDefault(df); + } + } + + @Test + public void full19() { + Assertions.assertEquals("2017-04-26 14:38:22", DateFormatter.fixFull19("2017-04-26")); + Assertions.assertEquals("2017-04-26 12:25:17", DateFormatter.fixFull19("2017-04-26 12")); + Assertions.assertEquals("2017-04-26 12:34:55", DateFormatter.fixFull19("2017-04-26 12:34")); + Assertions.assertEquals("2017-04-26 12:34:56", DateFormatter.fixFull19("2017-04-26 12:34:56")); + Assertions.assertEquals("2017-04-26 01:54:14", DateFormatter.fixFull19("2017-04-26 1")); + Assertions.assertEquals("2017-04-26 12:03:07", DateFormatter.fixFull19("2017-04-26 12:3")); + Assertions.assertEquals("2017-04-26 12:34:05", DateFormatter.fixFull19("2017-04-26 12:34:5")); + + Assertions.assertEquals(new SimpleDateFormat(PTN_FULL_19), DateFormatter.full19()); + Assertions.assertEquals("2017-04-26 12:34:56", DateFormatter.full19(ldt9)); + Assertions.assertEquals("2017-04-26 12:34:56", DateFormatter.full19(zdt9)); + Assertions.assertEquals("2017-04-26 13:34:56", DateFormatter.full19(zdt9, tz9)); + } @Test - public void printDateTime() { - SystemOut.println("------"); - SystemOut.println(DateFormatter.fixFull19("2017-04-26")); - SystemOut.println(DateFormatter.fixFull19("2017-04-26 12")); - SystemOut.println(DateFormatter.fixFull19("2017-04-26 12:34")); - SystemOut.println(DateFormatter.fixFull19("2017-04-26 12:34:56")); - SystemOut.println(DateFormatter.fixFull19("2017-04-26 1")); - SystemOut.println(DateFormatter.fixFull19("2017-04-26 12:3")); - SystemOut.println(DateFormatter.fixFull19("2017-04-26 12:34:5")); + public void full23() { + Assertions.assertEquals(new SimpleDateFormat(PTN_FULL_23), DateFormatter.full23()); + Assertions.assertEquals("2017-04-26 12:34:56.789", DateFormatter.full23(ldt9)); + Assertions.assertEquals("2017-04-26 12:34:56.789", DateFormatter.full23(zdt9)); + Assertions.assertEquals("2017-04-26 13:34:56.789", DateFormatter.full23(zdt9, tz9)); + + Assertions.assertEquals("2017-04-26 12:34:56.000", DateFormatter.full23(ldt0)); + Assertions.assertEquals("2017-04-26 12:34:56.000", DateFormatter.full23(zdt0)); + Assertions.assertEquals("2017-04-26 13:34:56.000", DateFormatter.full23(zdt0, tz9)); } + @Test - public void printFull23() { - SystemOut.println("------"); + public void full() { + Assertions.assertEquals("2017-04-26 12:34:56.789", DateFormatter.full(ldt9)); + Assertions.assertEquals("2017-04-26 12:34:56.789", DateFormatter.full(zdt9)); + Assertions.assertEquals("2017-04-26 13:34:56.789", DateFormatter.full(zdt9, tz9)); - Date d = new Date(); + Assertions.assertEquals("2017-04-26 12:34:56", DateFormatter.full(ldt0)); + Assertions.assertEquals("2017-04-26 12:34:56", DateFormatter.full(zdt0)); + Assertions.assertEquals("2017-04-26 13:34:56", DateFormatter.full(zdt0, tz9)); + } - SystemOut.println(DateFormatter.full23().format(d)); - SystemOut.println(DateFormatter.full23(d)); + @Test + public void date10() { + Assertions.assertEquals("2017-04-26", DateFormatter.date10(ld)); + Assertions.assertEquals("2017-04-26", DateFormatter.date10(ldt9)); + Assertions.assertEquals("2017-04-26", DateFormatter.date10(zdt9)); + Assertions.assertEquals("2017-04-26", DateFormatter.date10(zdt9, tz9)); + } - LocalDateTime n = LocalDateTime.now(); - SystemOut.println(DateFormatter.FMT_FULL_23.format(n)); - SystemOut.println(DateFormatter.full23(n)); + + @Test + public void time() { + Assertions.assertEquals("12:34:56", DateFormatter.time(lm0)); + Assertions.assertEquals("12:34:56.789", DateFormatter.time(lm9)); + + Assertions.assertEquals("12:34:56.789", DateFormatter.time(ldt9)); + Assertions.assertEquals("12:34:56.789", DateFormatter.time(zdt9)); + Assertions.assertEquals("13:34:56.789", DateFormatter.time(zdt9, tz9)); + + Assertions.assertEquals("12:34:56", DateFormatter.time(ldt0)); + Assertions.assertEquals("12:34:56", DateFormatter.time(zdt0)); + Assertions.assertEquals("13:34:56", DateFormatter.time(zdt0, tz9)); + } + + @Test + public void time08() { + Assertions.assertEquals("12:34:56", DateFormatter.time08(lm0)); + Assertions.assertEquals("12:34:56", DateFormatter.time08(lm9)); + + Assertions.assertEquals("12:34:56", DateFormatter.time08(ldt9)); + Assertions.assertEquals("12:34:56", DateFormatter.time08(zdt9)); + Assertions.assertEquals("13:34:56", DateFormatter.time08(zdt9, tz9)); + + Assertions.assertEquals("12:34:56", DateFormatter.time08(ldt0)); + Assertions.assertEquals("12:34:56", DateFormatter.time08(zdt0)); + Assertions.assertEquals("13:34:56", DateFormatter.time08(zdt0, tz9)); + } + + @Test + public void time12() { + Assertions.assertEquals("12:34:56.000", DateFormatter.time12(lm0)); + Assertions.assertEquals("12:34:56.789", DateFormatter.time12(lm9)); + + Assertions.assertEquals("12:34:56.789", DateFormatter.time12(ldt9)); + Assertions.assertEquals("12:34:56.789", DateFormatter.time12(zdt9)); + Assertions.assertEquals("13:34:56.789", DateFormatter.time12(zdt9, tz9)); + + Assertions.assertEquals("12:34:56.000", DateFormatter.time12(ldt0)); + Assertions.assertEquals("12:34:56.000", DateFormatter.time12(zdt0)); + Assertions.assertEquals("13:34:56.000", DateFormatter.time12(zdt0, tz9)); + } + + @Test + public void zone() { + try { + ThreadNow.TweakZone.tweakGlobal(TimeZone.getTimeZone("GMT+8")); + ZoneId zoneId = ThreadNow.sysZoneId(); + Assertions.assertEquals(tz8, zoneId); + ZonedDateTime zoned = DateFormatter.zoned(ud0, null); + Assertions.assertEquals(zdt0, zoned); + } + finally { + ThreadNow.TweakZone.resetGlobal(); + } } /** @@ -55,7 +188,7 @@ public void printFull23() { * Z zone-offset offset-Z +0000; -0800; -08:00; */ @Test - public void printZone() { + public void infoZone() { // 2021-05-06 20:27:04.633 Asia/Shanghai DateTimeFormatter d1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS VV"); // 2021-05-06 20:28:26.883 +0800 Asia/Shanghai diff --git a/src/test/java/pro/fessional/mirana/time/DateLocalingTest.java b/src/test/java/pro/fessional/mirana/time/DateLocalingTest.java index 8f7bfc5..275299d 100644 --- a/src/test/java/pro/fessional/mirana/time/DateLocalingTest.java +++ b/src/test/java/pro/fessional/mirana/time/DateLocalingTest.java @@ -1,20 +1,18 @@ package pro.fessional.mirana.time; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import pro.fessional.mirana.SystemOut; import java.time.LocalDate; import java.time.LocalDateTime; +import java.time.LocalTime; import java.time.ZoneId; import java.time.ZonedDateTime; +import java.util.TimeZone; import static org.junit.jupiter.api.Assertions.assertEquals; -import static pro.fessional.mirana.time.DateLocaling.dateTime; -import static pro.fessional.mirana.time.DateLocaling.monday; -import static pro.fessional.mirana.time.DateLocaling.month; -import static pro.fessional.mirana.time.DateLocaling.sunday; -import static pro.fessional.mirana.time.DateLocaling.sysLdt; -import static pro.fessional.mirana.time.DateLocaling.today; + /** * @author trydofor @@ -22,23 +20,31 @@ */ public class DateLocalingTest { - final ZoneId jp = ZoneId.of("Asia/Tokyo"); - final ZoneId cn = ZoneId.of("Asia/Shanghai"); - final LocalDateTime ln = LocalDateTime.now(); - final ZonedDateTime zn = ZonedDateTime.now(); + final ZoneId jpZid = ZoneId.of("Asia/Tokyo"); + final ZoneId cnZid = ZoneId.of("Asia/Shanghai"); + final LocalDate ld = LocalDate.of(2017, 4, 26); + final LocalTime jpLt = LocalTime.of(12, 34, 56, 0); + + final LocalDateTime jpLdt = LocalDateTime.of(ld, jpLt); + final ZonedDateTime jpZdt = ZonedDateTime.of(jpLdt, jpZid); + final LocalDateTime cnLdt = jpLdt.plusHours(-1); + final ZonedDateTime cnZdt = ZonedDateTime.of(cnLdt, cnZid); + + final LocalDateTime utcLdt = jpLdt.plusHours(-9); + final long utcMs = cnZdt.toEpochSecond() * 1000; @Test - public void testPrint() { - SystemOut.println(ln); - SystemOut.println(DateLocaling.useLdt(ln, cn)); - SystemOut.println(DateLocaling.local(jp, ln, cn)); - SystemOut.println(DateLocaling.local(zn, cn)); - SystemOut.println(dateTime(cn)); - SystemOut.println(dateTime(jp)); - SystemOut.println("thisMonday=" + monday(jp)); - SystemOut.println("thisSunday=" + sunday(jp)); - SystemOut.println("thisMonth=" + month(jp)); - SystemOut.println("today=" + today(jp)); + public void infoPrint() { + SystemOut.println(jpLdt); + SystemOut.println(DateLocaling.useLdt(jpLdt, cnZid)); + SystemOut.println(DateLocaling.local(jpZid, jpLdt, cnZid)); + SystemOut.println(DateLocaling.local(jpZdt, cnZid)); + SystemOut.println(DateLocaling.dateTime(cnZid)); + SystemOut.println(DateLocaling.dateTime(jpZid)); + SystemOut.println("thisMonday=" + DateLocaling.monday(jpZid)); + SystemOut.println("thisSunday=" + DateLocaling.sunday(jpZid)); + SystemOut.println("thisMonth=" + DateLocaling.month(jpZid)); + SystemOut.println("today=" + DateLocaling.today(jpZid)); // SystemOut.println("2020-01-31@2=" + LocalDate.of(2020, 1, 31).withMonth(2)); SystemOut.println("2020-01-31+1M=" + LocalDate.of(2020, 1, 31).plusMonths(1)); @@ -47,16 +53,66 @@ public void testPrint() { } @Test - public void testFromZone() { - LocalDateTime ldtJp = sysLdt(jp, DateLocaling.local(zn, jp)); - LocalDateTime ldtCn = sysLdt(cn, DateLocaling.local(zn, cn)); - assertEquals(ldtCn, ldtJp); + public void sysAll() { + try { + TimeZone tz7 = TimeZone.getTimeZone("GMT+7"); + ThreadNow.TweakZone.tweakGlobal(tz7); + Assertions.assertEquals(tz7, ThreadNow.sysTimeZone()); + + LocalDateTime ldt7 = cnLdt.plusHours(-1); + assertEquals(ldt7, DateLocaling.sysLdt(utcMs)); + assertEquals(ldt7, DateLocaling.sysLdt(cnZdt)); + assertEquals(ldt7, DateLocaling.sysLdt(cnZid, cnLdt)); + + assertEquals(utcMs, DateLocaling.sysEpoch(ldt7)); + + ZonedDateTime zdt7 = ZonedDateTime.of(ldt7, tz7.toZoneId()); + assertEquals(zdt7, DateLocaling.sysZdt(ldt7)); + assertEquals(zdt7, DateLocaling.sysZdt(cnZdt)); + assertEquals(zdt7, DateLocaling.sysZdt(cnZid, cnLdt)); + } + finally { + ThreadNow.TweakZone.resetGlobal(); + } + } + + @Test + public void useAll() { + assertEquals(utcMs, DateLocaling.useEpoch(cnLdt, cnZid)); + assertEquals(utcMs, DateLocaling.useEpoch(jpLdt, jpZid)); + assertEquals(cnZdt, DateLocaling.useZdt(jpZdt, cnZid)); + assertEquals(cnLdt, DateLocaling.useLdt(jpZdt, cnZid)); + assertEquals(cnLdt, DateLocaling.useLdt(utcMs, cnZid)); + + try { + // cnLdt default timezone is UTC+8 + ThreadNow.TweakZone.tweakGlobal(TimeZone.getTimeZone("GMT+8")); + assertEquals(cnZdt, DateLocaling.useZdt(cnLdt, cnZid)); + assertEquals(cnLdt, DateLocaling.useLdt(cnLdt, cnZid)); + } + finally { + ThreadNow.TweakZone.resetGlobal(); + } + } + + @Test + public void utcAll() { + assertEquals(utcLdt, DateLocaling.utcLdt(utcMs)); + assertEquals(utcMs, DateLocaling.utcEpoch(utcLdt)); } @Test - public void testToZone() { - LocalDateTime ldtJp = DateLocaling.useLdt(ln, jp); - LocalDateTime ldtCn = DateLocaling.useLdt(ln, cn); - assertEquals(ldtCn.plusHours(1), ldtJp); + public void testZoned() { + ZonedDateTime z1 = DateLocaling.zoned(jpZdt, cnZid); + assertEquals(cnZdt, z1); + + ZonedDateTime z2 = DateLocaling.zoned(jpZdt, jpZid); + assertEquals(jpZdt, z2); + + ZonedDateTime z3 = DateLocaling.zoned(jpZid, jpLdt, cnZid); + assertEquals(cnZdt, z3); + + ZonedDateTime z4 = DateLocaling.zoned(jpZid, jpLdt, jpZid); + assertEquals(jpZdt, z4); } } diff --git a/src/test/java/pro/fessional/mirana/time/DateNumberTest.java b/src/test/java/pro/fessional/mirana/time/DateNumberTest.java index 96a29b0..cc547ae 100644 --- a/src/test/java/pro/fessional/mirana/time/DateNumberTest.java +++ b/src/test/java/pro/fessional/mirana/time/DateNumberTest.java @@ -5,6 +5,8 @@ import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -14,37 +16,48 @@ */ public class DateNumberTest { + final LocalDate ld = LocalDate.of(2019, 5, 21); + final LocalTime lt = LocalTime.of(12, 34, 56, 789_000_000); + final LocalDateTime ldt = LocalDateTime.of(ld, lt); + final ZonedDateTime zdt = ZonedDateTime.of(ld, lt, ZoneId.systemDefault()); + @Test public void date8() { - LocalDate ld = LocalDate.of(2019, 5, 21); assertEquals(20190521, DateNumber.date8(ld)); + assertEquals(20190521, DateNumber.date8(ldt)); + assertEquals(20190521, DateNumber.date8(zdt)); } @Test public void dateTime14() { - LocalDate ld = LocalDate.of(2019, 5, 21); - LocalTime lt = LocalTime.of(12, 34, 56, 789_000_000); - LocalDateTime ldt = LocalDateTime.of(ld, lt); assertEquals(20190521123456L, DateNumber.dateTime14(ldt)); + assertEquals(20190521123456L, DateNumber.dateTime14(zdt)); } @Test public void dateTime17() { - LocalDate ld = LocalDate.of(2019, 5, 21); - LocalTime lt = LocalTime.of(12, 34, 56, 789_000_000); - LocalDateTime ldt = LocalDateTime.of(ld, lt); assertEquals(20190521123456789L, DateNumber.dateTime17(ldt)); + assertEquals(20190521123456789L, DateNumber.dateTime17(zdt)); } @Test public void time6() { - LocalTime lt = LocalTime.of(12, 34, 56, 789_000_000); assertEquals(123456, DateNumber.time6(lt)); + assertEquals(123456, DateNumber.time6(ldt)); + assertEquals(123456, DateNumber.time6(zdt)); } @Test public void time9() { - LocalTime lt = LocalTime.of(12, 34, 56, 789_000_000); assertEquals(123456789, DateNumber.time9(lt)); + assertEquals(123456789, DateNumber.time9(ldt)); + assertEquals(123456789, DateNumber.time9(zdt)); + } + + @Test + public void parse() { + assertEquals(lt, DateNumber.parseTime(123456789)); + assertEquals(ld, DateNumber.parseDate(20190521)); + assertEquals(ldt, DateNumber.parseDateTime(20190521123456789L)); } } \ No newline at end of file diff --git a/src/test/java/pro/fessional/mirana/time/DateParserTest.java b/src/test/java/pro/fessional/mirana/time/DateParserTest.java index eac49d4..d903ffb 100644 --- a/src/test/java/pro/fessional/mirana/time/DateParserTest.java +++ b/src/test/java/pro/fessional/mirana/time/DateParserTest.java @@ -8,7 +8,9 @@ import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; +import java.time.OffsetDateTime; import java.time.ZoneId; +import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalAccessor; @@ -69,6 +71,9 @@ public void parseZone() { assertEquals(ZoneId.of("+0800"), DateParser.parseZoned(str1).getZone()); assertEquals(ZoneId.of("GMT+8"), DateParser.parseZoned(str2).getZone()); assertEquals(ZoneId.of("Europe/Paris"), DateParser.parseZoned(str3).getZone()); + + assertEquals(ld1, DateParser.parseZoned(ld1, zid)); + assertEquals(ld1, DateParser.parseZoned(OffsetDateTime.of(ld1.toLocalDateTime(), ld1.getOffset()), zid)); } @Test @@ -191,6 +196,15 @@ public void parseJ8Date() { assertEquals(LocalDate.of(2021, 1, 1), DateParser.parseDate("21", f1)); } + @Test + public void parseOffset() { + ZoneId zid = ZoneId.of("+0800"); + OffsetDateTime odt = OffsetDateTime.of(2024, 1, 28, 20, 19, 49, 0, ZoneOffset.ofHours(8)); + System.out.println(DateFormatter.FMT_FULL_OZ.format(odt)); + assertEquals(odt, DateParser.parseOffset("2024-01-28 20:19:49 +08:00", zid, DateFormatter.FMT_FULL_OZ)); + + } + @Test public void parseJ8DateTime() { final DateTimeFormatter f1 = DateTimeFormatter.ofPattern("[yyyy][yy][-M][-d][ ][H][:m][:s]"); diff --git a/src/test/java/pro/fessional/mirana/time/SleepTest.java b/src/test/java/pro/fessional/mirana/time/SleepTest.java new file mode 100644 index 0000000..b66913d --- /dev/null +++ b/src/test/java/pro/fessional/mirana/time/SleepTest.java @@ -0,0 +1,88 @@ +package pro.fessional.mirana.time; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import pro.fessional.mirana.best.DummyBlock; + +import java.time.Duration; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; + +/** + * @author trydofor + * @since 2024-01-26 + */ +class SleepTest { + + @Test + void ignoreInterrupt() throws InterruptedException { + Sleep.ignoreInterrupt(Duration.ofMillis(100)); // fix never call + + final AtomicBoolean done = new AtomicBoolean(false); + final AtomicBoolean loop = new AtomicBoolean(true); + final Thread td = new Thread(() -> { + Sleep.ignoreInterrupt(2000, 4000); + done.set(true); + while (loop.get()) { + // busy wait to alive + DummyBlock.empty(); + } + }); + td.start(); + Thread.sleep(500); + td.interrupt(); + Thread.sleep(500); + Assertions.assertTrue(td.isInterrupted()); + Assertions.assertTrue(td.isAlive()); + loop.set(false); + Assertions.assertTrue(done.get()); + } + + @Test + void snoozeInterrupt() throws InterruptedException { + Sleep.snoozeInterrupt(Duration.ofMillis(100)); // fix never call + + final AtomicBoolean done = new AtomicBoolean(false); + final Thread td = new Thread(() -> { + Sleep.snoozeInterrupt(2000, 4000); + done.set(true); + }); + td.start(); + Thread.sleep(500); + td.interrupt(); + Thread.sleep(500); + Assertions.assertFalse(done.get()); + td.join(); + Assertions.assertTrue(done.get()); + } + + @Test + void throwsInterrupt() throws InterruptedException { + Sleep.throwsInterrupt(Duration.ofMillis(100),true); // fix never call + + final AtomicReference ex = new AtomicReference<>(); + final AtomicBoolean loop = new AtomicBoolean(true); + final Thread td = new Thread(() -> { + try { + Sleep.throwsInterrupt(2000, 4000, true); + } + catch (Exception e) { + ex.set(e); + } + + while (loop.get()) { + // busy wait to alive + DummyBlock.empty(); + } + }); + + td.start(); + Thread.sleep(500); + td.interrupt(); + Thread.sleep(500); + Assertions.assertTrue(td.isInterrupted()); + Assertions.assertTrue(td.isAlive()); + loop.set(false); + Assertions.assertInstanceOf(IllegalStateException.class, ex.get()); + } +} \ No newline at end of file diff --git a/src/test/java/pro/fessional/mirana/time/SlideDateTest.java b/src/test/java/pro/fessional/mirana/time/SlideDateTest.java index a4d5ceb..462c2b6 100644 --- a/src/test/java/pro/fessional/mirana/time/SlideDateTest.java +++ b/src/test/java/pro/fessional/mirana/time/SlideDateTest.java @@ -1,5 +1,6 @@ package pro.fessional.mirana.time; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import pro.fessional.mirana.SystemOut; @@ -8,6 +9,7 @@ import java.time.LocalDateTime; import java.time.LocalTime; import java.util.Date; +import java.util.concurrent.TimeUnit; /** * @author trydofor @@ -16,19 +18,42 @@ class SlideDateTest { @Test - void testPrint() { - final SlideDate sd = SlideDate.of(Duration.ofHours(-72)); + void infoPrint() { + Duration os1 = Duration.ofMinutes(-5); + final SlideDate sd = SlideDate.of(os1); + + SystemOut.println("=== LocalDate"); SystemOut.println(LocalDate.now()); SystemOut.println(sd.localDate()); - SystemOut.println("=== LocalDateTime"); - SystemOut.println(LocalDateTime.now()); - SystemOut.println(sd.localDateTime()); + SystemOut.println("=== LocalTime"); SystemOut.println(LocalTime.now()); SystemOut.println(sd.localTime()); SystemOut.println("=== UtilDate"); SystemOut.println(new Date()); SystemOut.println(sd.utilDate()); + + Assertions.assertEquals(os1, sd.getOffset()); + + SystemOut.println("=== LocalDateTime"); + LocalDateTime ldt0 = LocalDateTime.now(); + LocalDateTime ldt1 = sd.localDateTime(); + SystemOut.println(ldt0); + SystemOut.println(ldt1); + Assertions.assertTrue(Duration.between(ldt1, ldt0).toMinutes() >= 4); + + long ms0 = System.currentTimeMillis(); + long ms1 = sd.currentMillis(); + Assertions.assertTrue(Duration.ofMillis(ms0 - ms1).toMinutes() >= 4); + + long s1 = sd.currentSeconds(); + Assertions.assertTrue(Duration.ofSeconds(ms0 / 1000 - s1).toMinutes() >= 4); + + long s2 = sd.current(TimeUnit.SECONDS); + Assertions.assertTrue(Duration.ofSeconds(ms0 / 1000 - s2).toMinutes() >= 4); + + Assertions.assertNotNull(sd.getClock()); + } } diff --git a/src/test/java/pro/fessional/mirana/time/StopWatchTest.java b/src/test/java/pro/fessional/mirana/time/StopWatchTest.java index 3410751..0655201 100644 --- a/src/test/java/pro/fessional/mirana/time/StopWatchTest.java +++ b/src/test/java/pro/fessional/mirana/time/StopWatchTest.java @@ -1,5 +1,6 @@ package pro.fessional.mirana.time; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import pro.fessional.mirana.SystemOut; @@ -35,9 +36,22 @@ void start() throws InterruptedException { { final StopWatch.Watch watch = stopWatch.start("flat2"); Thread.sleep(500); + + watch.setMark("mark"); + Assertions.assertEquals("mark", watch.getMark()); + Assertions.assertTrue(watch.isRunning()); watch.close(); + Assertions.assertFalse(watch.isRunning()); + Assertions.assertTrue(watch.getElapse() > 0); + Assertions.assertTrue(watch.getElapseMs() > 0); } + + // nothing but coverage + Assertions.assertTrue(stopWatch.totalElapse() > 0); + Assertions.assertFalse(stopWatch.getWatches().isEmpty()); + Assertions.assertFalse(stopWatch.isRunning()); SystemOut.println(stopWatch); + stopWatch.clear(); } void tree1(int tm) throws InterruptedException { diff --git a/src/test/java/pro/fessional/mirana/time/ThreadNowTest.java b/src/test/java/pro/fessional/mirana/time/ThreadNowTest.java index 37992df..8385496 100644 --- a/src/test/java/pro/fessional/mirana/time/ThreadNowTest.java +++ b/src/test/java/pro/fessional/mirana/time/ThreadNowTest.java @@ -5,7 +5,13 @@ import java.time.Clock; import java.time.Instant; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.Date; +import java.util.TimeZone; import static pro.fessional.mirana.time.ThreadNow.TweakClock; @@ -15,20 +21,56 @@ */ class ThreadNowTest { + final ZoneId cnZid = ZoneId.of("Asia/Shanghai"); + final ZoneId jpZid = ZoneId.of("Asia/Tokyo"); + @Test void test1() { - final Instant n = Instant.now(); - final ZoneId CN = ZoneId.of("Asia/Shanghai"); - final ZoneId JP = ZoneId.of("Asia/Tokyo"); try { - TweakClock.tweakThread(Clock.fixed(n, CN)); + final Instant n = Instant.now(); + TweakClock.tweakThread(Clock.fixed(n, cnZid)); // 2022-10-10T04:33:39.180Z Assertions.assertEquals(n, ThreadNow.instant()); // 2022-10-10T13:33:39.180+09:00[Asia/Tokyo] - Assertions.assertEquals(n.atZone(JP), ThreadNow.zonedDateTime(JP)); + Assertions.assertEquals(n.atZone(jpZid), ThreadNow.zonedDateTime(jpZid)); } finally { TweakClock.resetThread(); } } + + @Test + void clock() { + Instant now = Instant.now(); + LocalDateTime ldt = LocalDateTime.ofInstant(now, cnZid); + ZoneOffset offset = cnZid.getRules().getOffset(now); + try { + TweakClock.tweakGlobal(Clock.fixed(now, cnZid)); + Assertions.assertEquals(TimeZone.getTimeZone("UTC"), ThreadNow.utcTimeZone()); + + Assertions.assertEquals(ZonedDateTime.of(ldt, cnZid), ThreadNow.zonedDateTime()); + Assertions.assertEquals(ZonedDateTime.of(ldt, cnZid), ThreadNow.zonedDateTime(cnZid)); + + Assertions.assertEquals(OffsetDateTime.of(ldt, offset), ThreadNow.offsetDateTime()); + Assertions.assertEquals(OffsetDateTime.of(ldt, offset), ThreadNow.offsetDateTime(cnZid)); + + Assertions.assertEquals(new Date(now.toEpochMilli()), ThreadNow.utilDate()); + Assertions.assertEquals(new Date(now.toEpochMilli()), ThreadNow.utilDate(cnZid)); + + Assertions.assertEquals(now, ThreadNow.instant()); + Assertions.assertEquals(now, ThreadNow.instant(cnZid)); + + Assertions.assertEquals(ldt.toLocalDate(), ThreadNow.localDate()); + Assertions.assertEquals(ldt.toLocalDate(), ThreadNow.localDate(cnZid)); + + Assertions.assertEquals(ldt.toLocalTime(), ThreadNow.localTime()); + Assertions.assertEquals(ldt.toLocalTime(), ThreadNow.localTime(cnZid)); + + Assertions.assertEquals(ldt, ThreadNow.localDateTime()); + Assertions.assertEquals(ldt, ThreadNow.localDateTime(cnZid)); + } + finally { + TweakClock.resetGlobal(); + } + } }