提交 7295937c 编写于 作者: 杜庆泉's avatar 杜庆泉

手动同步dev 分支到alpha

上级 f3a4d305
## 1.0.23
* update 4.28.2024092105-alpha
## 1.0.22
* update 4.27.2024091308-alpha
## 1.0.21
* update 4.26.2024082213-alpha
## 1.0.20
* update 4.25.2024081703-alpha
## 1.0.19
* update 4.23.2024070309-alpha
## 1.0.17
* update 4.22.2024062415-alpha
......
......@@ -15,6 +15,6 @@
</head>
<body>
<div id="app"><!--app-html--></div>
<script type="module" src="/main.js"></script>
<script type="module" src="/main"></script>
</body>
</html>
......@@ -2,7 +2,7 @@
"id": "hello-uts-alpha",
"name": "hello-uts-alpha",
"displayName": "hello-uts-alpha",
"version": "1.0.23",
"version": "1.0.18",
"description": "UTS插件示例项目",
"repository": "https://gitcode.net/dcloud/hello-uts",
"keywords": [
......
......@@ -164,10 +164,17 @@
"enablePullDownRefresh": false
}
}
},
// {
// "path": "pages/SyntaxCase/defaultValueTest",
// "style": {
// "navigationBarTitleText": "",
// "enablePullDownRefresh": false
// }
// },
// #endif
// #ifdef APP
,
{
"path": "pages/SyntaxCase/utsAndroid",
"style": {
......
......@@ -5,19 +5,24 @@
// #ifdef APP-ANDROID && UNI-APP-X
<button @tap="callKotlinMethodGetInfoTest">调用kotlin方法</button>
<button @tap="callJavaMethodGetInfoTest">调用java方法(需自定义基座)</button>
<view style="height: 10px;width: 100%;"></view>
<button @tap="kotlinMemListenTest">kotlin监听内存并持续回调UTS</button>
<button @tap="kotlinStopMemListenTest">停止监听</button>
<text>{{memInfo}}</text>
// #endif
</view>
</view>
</template>
<script>
// #ifdef APP-ANDROID && UNI-APP-X
import { callKotlinMethodGetInfo, callJavaMethodGetInfo} from "../../uni_modules/uts-syntaxcase";
import { callKotlinMethodGetInfo, callJavaMethodGetInfo,callKotlinCallbackUTS,callKotlinStopCallbackUTS} from "../../uni_modules/uts-syntaxcase";
// #endif
export default {
data() {
return {
title: 'UTS混编示例',
memInfo:''
}
},
......@@ -36,6 +41,16 @@
title:javaInfo
})
},
kotlinMemListenTest: function () {
callKotlinCallbackUTS(function(ret:string){
this.memInfo = ret
})
},
kotlinStopMemListenTest:function () {
callKotlinStopCallbackUTS()
},
// #endif
}
......
......@@ -4,16 +4,21 @@
<view class="uni-btn-v uni-common-mt">
<button @tap="callKotlinMethodGetInfoTest">调用kotlin方法</button>
<button @tap="callJavaMethodGetInfoTest">调用java方法(需自定义基座)</button>
<view style="height: 10px;width: 100%;"></view>
<button @tap="kotlinMemListenTest">kotlin监听内存并持续回调</button>
<button @tap="kotlinStopMemListenTest">停止监听</button>
<text>{{memInfo}}</text>
</view>
</view>
</template>
<script>
import { callKotlinMethodGetInfo, callJavaMethodGetInfo} from "../../uni_modules/uts-syntaxcase";
import { callKotlinMethodGetInfo, callJavaMethodGetInfo,callKotlinCallbackUTS,callKotlinStopCallbackUTS} from "../../uni_modules/uts-syntaxcase";
export default {
data() {
return {
title: 'UTS混编示例',
memInfo:''
}
},
......@@ -31,6 +36,15 @@
title:javaInfo
})
},
kotlinMemListenTest: function () {
callKotlinCallbackUTS((ret) =>{
this.memInfo = ret
})
},
kotlinStopMemListenTest:function () {
callKotlinStopCallbackUTS()
},
}
}
......
<template>
<view class="buttons">
<button @click="testClick">测试全部</button>
<text>{{testRet}}</text>
</view>
</template>
<script setup>
import {
Scan,
Scan1,
Scan2,
myClass
} from "@/uni_modules/uts-syntaxcase";
import { ref } from 'vue'
const myClassInit = new myClass();
let testRet = ref("1");
const testClick = function(){
testRet.value = "success"
// #ifdef APP-ANDROID
if(Scan() != 60000){
testRet = "error1"
console.log("error1")
}
if(Scan(100) != 100){
testRet = "error2"
console.log("error2")
}
// #endif
if(Scan1() != "null"){
testRet = "error3"
console.log("error3")
}
if(Scan1(100) != 100){
testRet = "error4"
console.log("error4")
}
if(Scan2() != "null"){
testRet = "error5"
console.log("error5")
}
if(Scan2(100) != 100){
testRet = "error6"
console.log("error6")
}
if(myClassInit.to('123') != "123"){
testRet = "error7"
console.log("error7")
}
}
</script>
<style lang="scss">
.buttons{
padding: 20rpx 20rpx 460rpx;
button{
margin-bottom: 20rpx;
font-size: 28rpx;
padding: 3px;
}
}
</style>
......@@ -53,7 +53,10 @@
<view>测试callback:{{ format(testUtsClassInstanceResult['callback']) }}</view>
<button @click="testUtsClassSetter">点击测试class 示例setter方法</button>
<view>测试setter:{{ format(testUtsClassSetterResult) }}</view>
<button @click="testAll">点击测试所有</button>
<button @click="testAll">点击测试所有</button>
<!-- #ifdef APP-IOS -->
<button @click="testPromiseStaticMethod">点击测试promise静态方法</button>
<!-- #endif -->
</view>
<view style="height: 20px;"></view>
</scroll-view>
......@@ -73,6 +76,11 @@
request,
SetterTest,
} from "../../uni_modules/uts-syntaxcase";
// #endif
// #ifdef APP-IOS
import {
testPromiseStaticMethod
} from "@/uni_modules/uts-syntaxcase"
// #endif
let test:Test|null = null
let id = 0
......@@ -441,7 +449,12 @@
} catch (e) {
console.error("testUtsClassSetter", e);
}
},
},
// #ifdef APP-IOS
testPromiseStaticMethod() {
testPromiseStaticMethod()
}
// #endif
}
}
</script>
\ No newline at end of file
......@@ -2,6 +2,7 @@
<div>
{{ret}}
<button @click="instanceCreate">多实例创建测试</button>
<button @click="defaultValueTest">默认值测试</button>
</div>
</template>
......@@ -11,7 +12,12 @@
User
} from '@/uni_modules/uts-advance'
import {
Scan,
Scan1,
Scan2,
myClass
} from "@/uni_modules/uts-syntaxcase";
export default {
data() {
......@@ -21,6 +27,34 @@
},
methods: {
defaultValueTest() {
const myClassInit = new myClass();
// 默认值测试
if(Scan() != 60000){
this.ret = "测试失败1"
}
if(Scan(100) != 100){
this.ret = "测试失败2"
}
if(Scan1() != null){
this.ret = "测试失败3"
}
if(Scan1(100) != 100){
this.ret = "测试失败4"
}
let ret5 = Scan2()
if(ret5 != "null"){
console.log(ret5)
this.ret = "测试失败5"
}
if(Scan2(100) != 100){
this.ret = "测试失败6"
}
if(myClassInit.to('123') != 123){
this.ret = "测试失败7"
}
},
instanceCreate() {
const user1 = new User("张三", 20);
......
......@@ -18,7 +18,7 @@
</view>
</template>
<script lang="ts">
import { gotoDemoActivity,sayHelloFromJar } from "@/uni_modules/uts-nativepage";
import { gotoDemoActivity,sayHelloFromJar,sayHelloFromSO } from "@/uni_modules/uts-nativepage";
import { getBatteryInfo, GetBatteryInfoOptions } from "@/uni_modules/uts-getbatteryinfo";
// #ifdef APP-ANDROID
import {
......@@ -95,6 +95,9 @@
},{
name: "调用jar中的方法",
function: "testNativeJar"
},{
name: "调用so中的方法",
function: "testNativeSO"
}] as Page[]
}
] as ListItem[],
......@@ -127,9 +130,13 @@
break
case 'testGotoDemoActivity':
this.testGotoDemoActivity()
break
case 'testNativeJar':
this.testNativeJar()
break
case 'testNativeSO':
this.testNativeSO()
break
}
return
}
......@@ -226,7 +233,16 @@
icon: 'none',
title: '来自jar中的返回值:' + ret
})
},
},
testNativeSO() {
let ret = sayHelloFromSO();
uni.showToast({
icon: 'none',
title: '来自so中的返回值:' + ret
})
},
testGotoDemoActivity() {
let ret = gotoDemoActivity();
if (!ret) {
......
......@@ -116,9 +116,20 @@
}, {
name: "参数传递示例",
url: "SyntaxCase/paramTest"
},{
},
{
name: "实例测试示例",
url: "SyntaxCase/instanceTest"
},
// #ifdef UNI-APP-X
{
name: "默认值测试示例",
url: "SyntaxCase/defaultValueTest"
},
// #endif
{
name: "混编测试示例",
url: "SyntaxCase/MixNativeCode"
}
]
},
......
<template>
<div>
<uts-hello-view buttonText="点击按钮内容" style="width:375px;height: 375px;background-color: aqua;"></uts-hello-view>
<uts-hello-container>
<text>文本组件</text>
<uts-hello-container style="flex: 1;background-color: red;">
<text style="left: 100px;top: 100px;background-color: green;">文本组件</text>
<image src="../../static/logo.png" mode="aspectFit"></image>
</uts-hello-container>
</div>
......
......@@ -2,8 +2,8 @@
<div>
<button @tap="doSth">调用组件的方法</button>
<uts-hello-view ref="helloView" buttonText="点击按钮内容" style="width:375px;height: 375px;background-color: aqua;"></uts-hello-view>
<uts-hello-container>
<text>文本组件</text>
<uts-hello-container style="flex: 1;background-color: red;">
<text style="left: 100px;top: 100px;background-color: green;">文本组件</text>
<image src="../../static/logo.png" mode="aspectFit"></image>
</uts-hello-container>
</div>
......@@ -14,7 +14,6 @@
export default {
data() {
return {
}
},
methods: {
......
const ERR_RE = /expected:<(.*)> but was:<(.*)>/
let result;
const resultEmptyError = '获取到 result 是空的, 请运行项目进行排查'
beforeAll(async () => {
await program.reLaunch('/pages/index/basicTest')
......@@ -11,6 +11,9 @@ beforeAll(async () => {
})
function getApiFailed(describe, api) {
if(Object.keys(result).length === 0){
return resultEmptyError
}
const failed = result[describe]?.failed?.find(item => {
return item.split(':')[0] === api
})
......@@ -22,7 +25,9 @@ describes.forEach(d => {
d?.tests && d.tests.forEach(api => {
it(api, () => {
const failed = getApiFailed(d.describe, api)
if (failed) {
if(failed == resultEmptyError){
expect('').toBe(resultEmptyError)
}else if (failed) {
const parts = failed.split('\n')
const matches = parts[1].match(ERR_RE)
if (matches?.length) {
......@@ -41,32 +46,6 @@ if (process.env.UNI_PROJECT_TYPE === '2.0' && process.env.uniTestPlatformInfo.to
it("jest_testTypeFromAppJs", async () => {
const res = await page.callMethod('jest_testTypeFromAppJs')
expect(res).toEqual(true)
})
})
}
if (process.env.UNI_PROJECT_TYPE === '2.0' && (process.env.uniTestPlatformInfo.toLocaleLowerCase().startsWith('ios') || process.env.uniTestPlatformInfo.startsWith('android'))) {
describe('testCallbackKeepAlive', () => {
it("jest_testCallbackKeepAlive", async () => {
const res = await page.callMethod('jest_testCallbackKeepAlive')
expect(res).toEqual(true)
})
it("jest_testCallbackNonKeepAlive", async () => {
const res = await page.callMethod('jest_testCallbackNonKeepAlive')
expect(res).toEqual(4)
})
})
}
if (process.env.UNI_PROJECT_TYPE === '1.0' && (process.env.uniTestPlatformInfo.toLocaleLowerCase().startsWith('ios') || process.env.uniTestPlatformInfo.startsWith('android'))) {
describe('testCallbackKeepAlive', () => {
it("jest_testCallbackKeepAlive", async () => {
const res = await page.callMethod('jest_testCallbackKeepAlive')
expect(res).toEqual(20)
})
it("jest_testCallbackNonKeepAlive", async () => {
const res = await page.callMethod('jest_testCallbackNonKeepAlive')
expect(res).toEqual(4)
})
})
}
}
\ No newline at end of file
......@@ -22,11 +22,7 @@
<script lang="ts">
import { runTests, Result } from '../../uni_modules/uts-tests'
// #ifdef APP-IOS
import { testTypeFromAppJs, Options } from '@/uni_modules/uts-ios-tests';
// #endif
// #ifdef APP
import { onTest1, testKeepAlive, testKeepAliveOption, createTest, TestKeepAliveClass, TestKeepAliveOption, } from '@/uni_modules/uts-tests'
import { testNonKeepAlive, testNonKeepAliveOption } from '@/uni_modules/uts-tests'
import { testTypeFromAppJs, Options } from '@/uni_modules/uts-ios-tests'
// #endif
export default {
data() {
......@@ -34,9 +30,7 @@ export default {
title: 'UTS基础语法',
resultArray: [] as Result[],
result: {} as UTSJSONObject,
names: [] as string[],
keepAliveCount: 0,
nonKeepAliveCount: 0
names: [] as string[],
}
},
onReady() {
......@@ -54,158 +48,13 @@ export default {
for (const key in resultMap) {
this.names.push(key)
this.resultArray.push(resultMap[key] as Result)
}
console.log('jest_testCallbackKeepAlive:' + this.jest_testCallbackKeepAlive())
this.jest_testCallbackNonKeepAlive().then(res=>{
console.log('jest_testCallbackNonKeepAlive:' + res)
})
}
},
// #ifdef APP-IOS
jest_testTypeFromAppJs() {
return testTypeFromAppJs({
num: 1
num: 1
} as Options)
},
// #endif
// #ifdef APP
jest_testCallbackKeepAlive(): boolean {
let ret: boolean = true
let count = 0;
onTest1((res) => {
count++;
console.log("onTest1 callback =====> ", res)
})
if (count < 2) {
ret = false
}
count = 0;
testKeepAlive((res) => {
count++;
console.log(res)
})
if (count < 2) {
ret = false
}
count = 0;
testKeepAliveOption({
a: "testKeepAliveOption",
success: (res) => {
count++;
console.log("testKeepAliveOption callback =====> ", res)
}
} as TestKeepAliveOption)
if (count < 2) {
ret = false
}
count = 0;
TestKeepAliveClass.onTestStatic((res) => {
count++;
console.log("onTestStatic callback =====> ", res)
})
if (count < 2) {
ret = false
}
count = 0;
TestKeepAliveClass.testKeepAliveStatic((res) => {
count++;
console.log("testKeepAliveStatic callback =====> ", res)
})
if (count < 2) {
ret = false
}
count = 0;
TestKeepAliveClass.testKeepAliveOptionStatic({
a: "testKeepAliveOption",
success: (res) => {
count++;
console.log("testKeepAliveOptionStatic callback =====> ", res)
}
} as TestKeepAliveOption)
if (count < 2) {
ret = false
}
count = 0;
const obj = new TestKeepAliveClass()
obj.onTest((res) => {
count++;
console.log("TestKeepAliveClass.onTest callback =====> ", res)
})
if (count < 2) {
ret = false
}
count = 0;
obj.testKeepAlive((res) => {
count++;
console.log("TestKeepAliveClass.testKeepAlive callback =====> ", res)
})
if (count < 2) {
ret = false
}
count = 0;
obj.testKeepAliveOption({
a: "testKeepAliveOption",
success: (res) => {
count++;
console.log("TestKeepAliveClass.testKeepAliveOption callback =====> ", res)
}
} as TestKeepAliveOption)
if (count < 2) {
ret = false
}
count = 0;
const testImpl = createTest()
testImpl.test((res) => {
count++;
console.log("TestImpl.test callback =====> ", res)
})
if (count < 2) {
ret = false
}
this.keepAliveCount = count
return ret
},
jest_testCallbackNonKeepAlive(): Promise<number> {
let count = 0
const fn = (res:string) => {
count++;
console.log("testCallbackNonKeepAlive callback =====> ", res)
}
testNonKeepAlive(fn)
testNonKeepAlive(fn)
const options: TestKeepAliveOption = {
a:'a',
success(res:string){
count++;
console.log("testCallbackNonKeepAliveOption callback =====> ", res)
}
}
testNonKeepAliveOption(options)
testNonKeepAliveOption(options)
return new Promise((resolve)=>{
setTimeout(()=>{
this.nonKeepAliveCount = count
resolve(count)
},50)
})
}
// #endif
},
......
......@@ -20,177 +20,20 @@
import {
runTests
} from '../../uni_modules/uts-tests'
import { onTest1, testKeepAlive, testKeepAliveOption, createTest, TestKeepAliveClass } from '@/uni_modules/uts-tests'
import { testNonKeepAlive, testNonKeepAliveOption } from '@/uni_modules/uts-tests'
export default {
data() {
return {
title: 'UTS基础语法',
result: {},
keepAliveCount: 0,
nonKeepAliveCount: 0
title: 'UTS基础语法',
result: {}
}
},
onReady() {
this.test()
},
methods: {
async test() {
test() {
this.result = runTests()
console.log(this.result)
console.log('jest_testCallbackKeepAlive:' + await this.jest_testCallbackKeepAlive())
console.log('jest_testCallbackNonKeepAlive:' + await this.jest_testCallbackNonKeepAlive())
},
jest_testCallbackKeepAlive() {
let ret = true
let count = 0;
onTest1((res) => {
count++;
console.log("onTest1 callback =====> ", res)
})
if (count < 2) {
ret = false
}
// count = 0;
testKeepAlive((res) => {
count++;
console.log(res)
})
if (count < 2) {
ret = false
}
// count = 0;
testKeepAliveOption({
a: "testKeepAliveOption",
success: (res) => {
count++;
console.log("testKeepAliveOption callback =====> ", res)
}
})
if (count < 2) {
ret = false
}
// count = 0;
TestKeepAliveClass.onTestStatic((res) => {
count++;
console.log("onTestStatic callback =====> ", res)
})
if (count < 2) {
ret = false
}
// count = 0;
TestKeepAliveClass.testKeepAliveStatic((res) => {
count++;
console.log("testKeepAliveStatic callback =====> ", res)
})
if (count < 2) {
ret = false
}
// count = 0;
TestKeepAliveClass.testKeepAliveOptionStatic({
a: "testKeepAliveOption",
success: (res) => {
count++;
console.log("testKeepAliveOptionStatic callback =====> ", res)
}
})
if (count < 2) {
ret = false
}
// count = 0;
const obj = new TestKeepAliveClass()
obj.onTest((res) => {
count++;
console.log("TestKeepAliveClass.onTest callback =====> ", res)
})
if (count < 2) {
ret = false
}
// count = 0;
obj.testKeepAlive((res) => {
count++;
console.log("TestKeepAliveClass.testKeepAlive callback =====> ", res)
})
if (count < 2) {
ret = false
}
// count = 0;
obj.testKeepAliveOption({
a: "testKeepAliveOption",
success: (res) => {
count++;
console.log("TestKeepAliveClass.testKeepAliveOption callback =====> ", res)
}
})
if (count < 2) {
ret = false
}
// count = 0;
const testImpl = createTest()
testImpl.test((res) => {
count++;
console.log("TestImpl.test callback =====> ", res)
})
if (count < 2) {
ret = false
}
return new Promise((resolve)=>{
setTimeout(()=>{
this.keepAliveCount = count
resolve(count)
},30)
})
},
jest_testCallbackNonKeepAlive() {
let ret = true
let count = 0
// 使用相同的回调函数多次传递调用,确保每次都正常
const fn = (res) => {
count++;
console.log("testCallbackNonKeepAlive callback =====> ", res)
}
testNonKeepAlive(fn)
testNonKeepAlive(fn)
if (count < 2) {
ret = false
}
count = 0
const options = {
a:'a',
success(res){
count++;
console.log("testCallbackNonKeepAliveOption callback =====> ", res)
}
}
testNonKeepAliveOption(options)
testNonKeepAliveOption(options)
if (count < 2) {
ret = false
}
return new Promise((resolve)=>{
setTimeout(()=>{
this.nonKeepAliveCount = count
resolve(count)
},30)
})
}
}
}
......
......@@ -6,12 +6,13 @@
<button type="primary" @tap="testDoSthWithCallback">uts异步方法(无参数)</button>
<button type="primary" @tap="testDoSthWithString">uts异步方法(字符串参数)</button>
<button type="primary" @tap="testDoSthWithJSON">uts异步方法(json参数)</button>
<button type="primary" @tap="testBuildinObject">内置对象语法测试</button>
<button type="primary" @tap="testCallback">多次回调示例</button>
<button type="primary" @tap="testBuildinObject">内置对象语法测试</button>
</view>
</view>
</template>
<script>
import { callWithJSONParam, callWithStringParam, callWithoutParam, JsonParamOptions, inputJSON } from "../../uni_modules/uts-helloworld";
import { callWithJSONParam, callWithStringParam, callWithoutParam, JsonParamOptions, inputJSON ,onCallback} from "../../uni_modules/uts-helloworld";
export default {
data() {
......@@ -72,15 +73,26 @@
}
} as JsonParamOptions);
},
/**
* 测试内置对象
*/
testBuildinObject: function() {
uni.navigateTo({
url: `/pages/index/basicTest`
})
}
testCallback: function () {
onCallback(
function(response){
uni.showToast({
title:'uts插件uts-helloworld的callWithStringParam方法收到了你输入的字符串:'+response,
icon:'none'
});
},
);
},
/**
* 测试内置对象
*/
testBuildinObject: function() {
uni.navigateTo({
url: `/pages/index/basicTest`
})
}
}
}
</script>
......
......@@ -6,12 +6,13 @@
<button type="primary" @tap="testDoSthWithCallback">uts异步方法(无参数)</button>
<button type="primary" @tap="testDoSthWithString">uts异步方法(字符串参数)</button>
<button type="primary" @tap="testDoSthWithJSON">uts异步方法(json参数)</button>
<button type="primary" @tap="testCallback">多次回调示例</button>
<button type="primary" @tap="testBuildinObject">内置对象语法测试</button>
</view>
</view>
</template>
<script>
import { callWithJSONParam, callWithStringParam, callWithoutParam } from "../../uni_modules/uts-helloworld";
import { callWithJSONParam, callWithStringParam, callWithoutParam,onCallback } from "../../uni_modules/uts-helloworld";
export default {
data() {
......@@ -46,7 +47,7 @@
this.stringParam,
function(response){
uni.showToast({
title:'uts插件uts-helloworld的callWithStringParam方法收到了你输入的字符串'+response,
title:'uts插件uts-helloworld的onCallback方法'+response,
icon:'none'
});
},
......@@ -71,6 +72,18 @@
}
});
},
testCallback: function () {
onCallback(
function(response){
uni.showToast({
title:'uts插件uts-helloworld的callWithStringParam方法收到了你输入的字符串:'+response,
icon:'none'
});
},
);
},
/**
* 测试内置对象
*/
......
......@@ -111,9 +111,8 @@ class AddUIRunnable implements Runnable {
textView.setBackgroundColor(Color.RED)
textView.setTag("helloText")
textView.setGravity(Gravity.CENTER)
let decorView = UTSAndroid.getUniActivity()!.window.decorView;
let decorView = UTSAndroid.getUniActivity()!.getWindow().getDecorView();
let frameContent = decorView.findViewById<FrameLayout>(android.R.id.content)
let layoutParam = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
......
......@@ -42,4 +42,23 @@ export function callWithJSONParam(opts: JsonParamOptions) {
}
/**
* 导出多次回调UTS函数
* @param opts
*/
export function onCallback(callback: (sth:string) => void) {
/**
* 模拟多次回调
*/
let count = 1
let taskId = -1
taskId = setInterval(function() {
callback(`第 ${count} 次回调`)
count++;
console.log("count",count)
if(count > 3){
clearInterval(taskId)
}
}, 500);
}
package uts.sdk.modules.utsNativepage
class NativeLib {
/**
* A native method that is implemented by the 'nativelib' native library,
* which is packaged with this application.
*/
external fun stringFromJNI(): String
companion object {
// Used to load the 'nativelib' library on application startup.
init {
System.loadLibrary("nativelib")
}
}
}
......@@ -19,7 +19,7 @@ import Toast from 'android.widget.Toast';
import ShortcutInfoCompat from 'androidx.core.content.pm.ShortcutInfoCompat'
import ShortcutManagerCompat from 'androidx.core.content.pm.ShortcutManagerCompat'
import IconCompat from 'androidx.core.graphics.drawable.IconCompat'
import ActivityLifecycleCallbacks from 'android.app.Application.ActivityLifecycleCallbacks';
import Service from 'android.app.Service';
import System from 'java.lang.System';
......@@ -61,7 +61,64 @@ export function sayHelloFromJar(): string {
}
/**
* 调用SO动态库中的方法
*/
export function sayHelloFromSO():string {
// 这里的逻辑是为了判断 当前的自定义activity 是否注册了,并以此为条件判断是否是自定义基座
let hasXActivityIntegration = true
try{
let packageManager = UTSAndroid.getUniActivity()!.getPackageManager();
let intent = new Intent(UTSAndroid.getUniActivity(),DemoActivity().javaClass);
let resolveInfo = packageManager.queryIntentActivities(intent,0);
console.log(resolveInfo.size)
if(resolveInfo.size == 0){
hasXActivityIntegration = false;
}
}catch(e:Exception){
console.log(e);
hasXActivityIntegration = false;
}
if(!hasXActivityIntegration){
return "需要在自定义基座运行";
}
let nativeLib = new NativeLib()
return nativeLib.stringFromJNI()
}
class MyLifecycleCallbacks implements ActivityLifecycleCallbacks {
override onActivityCreated(a: Activity, b: Bundle|null):void {
console.log("onActivityCreated",a)
}
override onActivityStarted(a: Activity):void {
console.log("onActivityStarted",a)
}
override onActivityResumed(a: Activity):void {
console.log("onActivityResumed",a)
}
override onActivityPaused(a: Activity):void {
console.log("onActivityPaused",a)
}
override onActivityStopped(a: Activity):void {
console.log("onActivityStopped",a)
}
override onActivitySaveInstanceState(a: Activity, b: Bundle):void {
console.log("onActivitySaveInstanceState",a)
}
override onActivityDestroyed(a: Activity):void {
console.log("onActivityDestroyed",a)
}
}
export class AppHookProxy implements UTSAndroidHookProxy {
......@@ -74,6 +131,9 @@ export class AppHookProxy implements UTSAndroidHookProxy {
//onCreate 初始化三方SDK
Log.d("AppHookProxy", "AppHookProxy--onCreate---isPrivacyAgree")
}
application.registerActivityLifecycleCallbacks(new MyLifecycleCallbacks());
}
}
......@@ -165,7 +225,7 @@ class StartServiceListener implements OnClickListener{
override onClick(v?: View):void{
var intent = new Intent(UTSAndroid.getUniActivity(), ForeService().javaClass);
let intent = new Intent(UTSAndroid.getUniActivity(), ForeService().javaClass);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
UTSAndroid.getAppContext()!.startForegroundService(intent);
}
......
package uts.sdk.modules.utsSyntaxcase
import android.app.ActivityManager
import android.content.Context.ACTIVITY_SERVICE
import android.os.Build
import io.dcloud.uts.UTSAndroid
import io.dcloud.uts.setInterval
import io.dcloud.uts.clearInterval
import io.dcloud.uts.console
object NativeCode {
fun getPhoneInfo():String{
return "${Build.BOARD}-${Build.USER}"
val ret = "${Build.BOARD}-${Build.USER}"
console.log("PhoneInfo",ret)
return ret
}
fun finishActivity(){
......@@ -17,5 +23,38 @@ object NativeCode {
fun getJavaUser():JavaUser{
return JavaUser("张三",12)
}
/**
* 记录上一次的任务id
*/
private var lastTaskId = -1
fun kotlinCallbackUTS(callback: (String) -> Unit){
if(lastTaskId != -1){
// 避免重复开启
clearInterval(lastTaskId)
}
lastTaskId = setInterval({
val activityManager = UTSAndroid.getUniActivity()?.getSystemService(ACTIVITY_SERVICE) as ActivityManager
val memoryInfo = ActivityManager.MemoryInfo()
activityManager.getMemoryInfo(memoryInfo)
val availMem = memoryInfo.availMem / 1024 / 1024
val totalMem = memoryInfo.totalMem / 1024 / 1024
callback("设备内存:$totalMem MB,可用内存:$availMem MB")
},1000,2000)
}
fun kotlinStopMemListenTest(){
if(lastTaskId != -1){
// 避免重复开启
clearInterval(lastTaskId)
}
}
}
\ No newline at end of file
{
"deploymentTarget": "13.0"
"deploymentTarget": "12.0"
}
\ No newline at end of file
import { RequestTask, SyncOptions, AsyncOptions, SyntaxResult, SyncResult, TestOptions } from "./interface.uts";
import { log } from "./utils.uts";
// #ifdef APP-IOS
import { UTSPromiseAggregateError, UTSPromiseFulfilledResult, UTSPromiseRejectedResult} from "DCloudUTSFoundation";
// #endif
/**
* 导出一个属性
......@@ -51,18 +54,12 @@ export function testSyncWithCallback(opts : AsyncOptions) : SyntaxResult {
async function testAwaitPromise(res : SyntaxResult) : Promise<SyntaxResult> {
// #ifdef APP-ANDROID
return await new Promise(function (resolve : (res : SyntaxResult) => void) {
resolve(res)
setTimeout(() => {
resolve(res)
}, 2000)
})
// #endif
// #ifndef APP-ANDROID
return res
// #endif
async function testAwaitPromise(res : SyntaxResult) : Promise<SyntaxResult> {
return await new Promise(function (resolve : (res : SyntaxResult) => void) {
setTimeout(() => {
resolve(res)
}, 2000)
})
}
/**
* 导出一个异步方法
......@@ -103,7 +100,7 @@ export async function testAsyncParam3(id : number, name : string, opts : AsyncOp
export class Test {
id : number;
name : string;
name : string;
static type : string = "Test";
constructor(id : number, options : TestOptions) {
......@@ -125,21 +122,119 @@ export class Test {
const res = await testAsync(opts);
return res;
}
}
export class SetterTest {
private _nickName: string = '';
get nickName (): string {
console.log('get nickName');
return this._nickName;
}
set nickName (value: string) {
console.log('set nickName');
this._nickName = value;
}
}
// #ifdef APP-IOS
// #ifdef UNI-APP-X
export function testPromiseStaticMethod() {
let p0 = new Promise<SyntaxResult | null>((resolve, reject) => {
let success = true
setTimeout(() => {
if (success) {
const res : SyntaxResult = {
name: "pomise 0",
}
resolve(res);
} else{
reject(new Error("this is promise 0 reject reasion"))
}
}, 1000);
});
let p1 = new Promise<SyntaxResult | null>((resolve, reject) => {
let success = true
setTimeout(() => {
if (success) {
resolve(null);
} else{
reject(new Error("this is promise 1 reject reasion"))
}
}, 2000);
});
let p2 = new Promise<SyntaxResult | null>((resolve, reject) => {
let success = false
setTimeout(() => {
if (success) {
resolve(null);
} else{
// reject(new Error("this is promise 2 reject reasion"))
reject(null)
}
}, 2500);
});
// test for any
let pt = Promise.any([p0, p1, p2]);
pt.then( (res) => {
console.log("promise.any test success", res)
})
.catch( (error: any | null) => {
if (error instanceof UTSPromiseAggregateError) {
let err = error as UTSPromiseAggregateError
console.log(err.name, err.message, err.errors);
}else {
console.log(error);
}
})
// test for allSettled
Promise.allSettled([p0, p1, p2])
.then((res) => {
res.forEach((item, index) => {
if (item instanceof UTSPromiseFulfilledResult<SyntaxResult | null >) {
let item0 = item as UTSPromiseFulfilledResult
console.log(item0.value, "UTSPromiseFulfilledResult value")
} else if (item instanceof UTSPromiseRejectedResult<SyntaxResult | null>) {
let item0 = item as UTSPromiseRejectedResult
console.log(item0.reason, "UTSPromiseRejectedResult reason")
}
})
})
.catch((error: any | null) => {
console.log(error, "rejected test for promise.allSettled")
})
// test for all
Promise.all([p0, p1, p2])
.then((res)=> {
console.log(res, res.count)
})
.catch( (error: any | null) => {
console.log(error, "rejected test for promise.all")
})
// test for race
Promise.race([p0, p1, p2])
.then((res) => {
console.log(res, "resolved test for promise.race");
})
.catch((error: any | null) => {
console.log(error, "catch test for promise.race")
})
}
// #endif
// #endif
export class SetterTest {
private _nickName: string = '';
get nickName (): string {
console.log('get nickName');
return this._nickName;
}
set nickName (value: string) {
console.log('set nickName');
this._nickName = value;
}
}
class RequestTaskImpl implements RequestTask {
......@@ -162,17 +257,34 @@ class RequestTaskImpl implements RequestTask {
export function request(url : string) : RequestTask | null {
return new RequestTaskImpl(url)
}
// #ifdef APP-ANDROID
// #ifdef UNI-APP-X
}
// #ifdef APP-ANDROID
export function callKotlinMethodGetInfo():String {
return NativeCode.getPhoneInfo()
}
}
export function callJavaMethodGetInfo():String {
return new JavaUser("jack",12).name
}
}
export function callKotlinCallbackUTS(callback: (res: string) => void) {
NativeCode.kotlinCallbackUTS(function(res:string){
console.log(res)
callback(res)
})
}
export function callKotlinStopCallbackUTS() {
NativeCode.kotlinStopMemListenTest()
}
// #endif
// #ifdef APP-ANDROID
// #ifdef UNI-APP-X
import KeyEvent from 'android.view.KeyEvent';
import Configuration from 'android.content.res.Configuration';
......@@ -316,4 +428,44 @@ export class UTSActivityComponentCallback extends UniActivityComponentCallback {
}
}
// #endif
// #endif
\ No newline at end of file
// #endif
export function Scan(timeMillis : Number = 60000):number {
console.log("Scan", timeMillis)
return timeMillis
}
export function Scan1(timeMillis ?: Number):string {
console.log("Scan", timeMillis)
if(timeMillis == null){
return "null"
}
return timeMillis!.toString()
}
export function Scan2(timeMillis ?: Number | null):string {
console.log("Scan", timeMillis)
if(timeMillis == null){
return "null"
}
return timeMillis!.toString()
}
export class myClass {
constructor() {
}
to(name: String):string {
console.log(name);
return name
}
to1(name?: String):string {
if(name == null){
return "null"
}
console.log(name);
return name!
}
}
\ No newline at end of file
......@@ -72,9 +72,6 @@ export function testArray() : Result {
console.log(arr[1])//'shoes'
console.log(arr[1])//'shirts'
// #END
expect(arr.length).toEqual(4);
expect(arr[0]).toEqual('shoes');
expect(arr[1]).toEqual('shirts');
// expect(arr[4]).toEqual(null);
const numbers : number[] = [1, 2, 3, 4, 5];
if (numbers.length > 3) {
......
......@@ -5,8 +5,8 @@ import { TFloat64Array } from './TFloat64Array.uts'
import { TInt8Array } from './TInt8Array.uts'
import { TInt16Array } from './TInt16Array.uts'
import { TInt32Array } from './TInt32Array.uts'
import { TUint8Array } from './TUint8Array.uts'
import { TUint8ClampedArray } from './TUint8ClampedArray.uts'
import { TUint8Array } from './TUInt8Array.uts'
import { TUint8ClampedArray } from './TUInt8ClampedArray.uts'
import { TUint16Array } from './TUint16Array.uts'
import { TUint32Array } from './TUint32Array.uts'
// #ifdef APP-ANDROID
......
......@@ -76,7 +76,8 @@ export function testGlobal() : Result {
expect(parseInt("922337203685477580700099999999999999999999999999999999999999999999999999999999999999999")).toEqualNumber(9.223372036854776e+86)
expect(parseInt("50") / 100).toEqualNumber(0.5);
expect(parseInt("500") / 100).toEqualNumber(5);
expect(parseInt("3.0")).toEqual(3);
expect(parseInt("3.02")).toEqual(3);
// #END
})
......@@ -90,6 +91,9 @@ export function testGlobal() : Result {
expect(parseFloat("3.14some non-digit characters")).toEqual(3.14);
expect(parseFloat("100") / 50).toEqualNumber(2);
expect(parseFloat("105") / 50).toEqual(2.1);
expect(parseFloat("3.0")).toEqual(3);
expect(parseFloat("3.02").toString()).toEqual("3.02");
// #END
})
......
......@@ -38,9 +38,62 @@ function countOccurrences(str : string, substr : string) : number {
return count;
}
// #ifdef APP-ANDROID
class A1 implements IJSONStringify{
override toJSON():any|null{
let jsonRet = {
'name': "zhangsan",
'age': 12,
}
return jsonRet
}
}
class A2 implements IJSONStringify{
toJSON():any|null{
return 2
}
}
class A3 implements IJSONStringify{
toJSON():any|null{
return "json"
}
}
class A4 implements IJSONStringify{
toJSON():any|null{
return null
}
}
class A5 implements IJSONStringify{
toJSON():any|null{
return new A1()
}
}
class A6 implements IJSONStringify{
toJSON():any|null{
return new A5()
}
}
// #endif
export function testJSON() : Result {
return describe("JSON", () => {
test('custom-stringify', () => {
// #ifdef APP-ANDROID
expect(JSON.stringify(new A1()).length).toEqual(28)
expect(JSON.stringify(new A2())).toEqual("2")
expect(JSON.stringify(new A3())).toEqual('"json"')
expect(JSON.stringify(new A4())).toEqual('null')
expect(JSON.stringify(new A5()).length).toEqual(28)
expect(JSON.stringify(new A6()).length).toEqual(28)
// #endif
})
test('parse', () => {
// #TEST JSON.parse_tip,JSON.parse
const json = `{"result":true, "count":42}`;
......@@ -221,21 +274,21 @@ export function testJSON() : Result {
// #ifdef APP-ANDROID
let a = JSON.stringify({ "x": 111, "y": "aaa" })
expect(a).toEqual('{"x":111,"y":"aaa"}');
let a1 = JSON.stringify({ "x": 111, "y": "aaa" }, function (key : any, value : any | null) : any | null {
let a1 = JSON.stringify({ "x": 111, "y": "aaa" }, function (key : string, value : any | null) : any | null {
if (key == "x") {
return "x"
}
return value
})
expect(a1).toEqual('{"x":"x","y":"aaa"}');
let a2 = JSON.stringify({ "x": 111, "y": "aaa" }, function (key : any, value : any | null) : any | null {
let a2 = JSON.stringify({ "x": 111, "y": "aaa" }, function (key : string, value : any | null) : any | null {
if (key == "x") {
return "x"
}
return value
}, 6)
expect(a2.length).toEqual(36);
let a3 = JSON.stringify({ "x": 111, "y": "aaa" }, function (key : any, value : any | null) : any | null {
let a3 = JSON.stringify({ "x": 111, "y": "aaa" }, function (key : string, value : any | null) : any | null {
if (key == "x") {
return "x"
}
......@@ -243,7 +296,7 @@ export function testJSON() : Result {
}, 11)
expect(a3.length).toEqual(44);
let a4 = JSON.stringify({ "x": 111, "y": "aaa" }, function (key : any, value : any | null) : any | null {
let a4 = JSON.stringify({ "x": 111, "y": "aaa" }, function (key : string, value : any | null) : any | null {
if (key == "x") {
return "x"
}
......@@ -264,9 +317,11 @@ export function testJSON() : Result {
expect(a8.length).toEqual(73);
expect(countOccurrences(a8, "99999")).toEqual(6);
// #endif
})
test('stringify', () => {
// #ifdef APP-ANDROID
......
......@@ -22522,22 +22522,23 @@ export function testJSONLarge() : Result {
return describe("JSON_large", () => {
test('parse', () => {
// #ifdef APP-ANDROID
let startTime = System.currentTimeMillis()
let listdata = JSON.parseArray<PICKER_ITEM_INFO>(allStr)
let spendTime = System.currentTimeMillis() - startTime
console.log('指定类型转换耗时',spendTime,listdata!.length)
expect(listdata.length).toEqual(33);
expect(spendTime < 500).toEqual(true);
startTime = System.currentTimeMillis()
let listdata2 = JSON.parse(allStr)
spendTime = System.currentTimeMillis() - startTime
expect(listdata2 instanceof Array).toEqual(true);
let parseArray = listdata2 as Array
expect(parseArray.length).toEqual(33);
expect(spendTime < 300).toEqual(true);
console.log('不指定类型转换耗时',spendTime,listdata2)
let startTime = System.currentTimeMillis()
let listdata = JSON.parseArray<PICKER_ITEM_INFO>(allStr)
let spendTime = System.currentTimeMillis() - startTime
console.log('指定类型转换耗时',spendTime,listdata!.length)
expect(listdata.length).toEqual(33);
expect(spendTime < 1800).toEqual(true);
startTime = System.currentTimeMillis()
let listdata2 = JSON.parse(allStr)
spendTime = System.currentTimeMillis() - startTime
expect(listdata2 instanceof Array).toEqual(true);
let parseArray = listdata2 as Array
expect(parseArray.length).toEqual(33);
expect(spendTime < 1200).toEqual(true);
console.log('不指定类型转换耗时',spendTime,listdata2)
// #endif
......
......@@ -80,9 +80,11 @@ export function testKeyWord() : Result {
})
test('typeof', () => {
expect(typeof (null)).toEqual('object')
expect(typeof null).toEqual('object')
let new1 = new User()
expect(typeof (new1)).toEqual('object')
//expect(typeof null).toEqual('object')
// #ifdef APP-ANDROID || APP-IOS
expect(typeof (123456.789)).toEqual('Double')
//expect(typeof(789778979798797987979)).toEqual('number')
......
......@@ -126,7 +126,7 @@ export function testMath() : Result {
// 解决精度问题
expect(Math.acos(-1)).toEqual(3.141592653589793);
expect(Math.acos(0)).toEqual(1.5707963267948966);
expect(Math.acos(1)).toEqual(0.0);
expect(Math.acos(1)).toEqual(0);
})
test('acosh', () => {
......@@ -145,7 +145,7 @@ export function testMath() : Result {
// expected output: 1.566799236972411
// #END
// 解决精度问题
expect(Math.acosh(1)).toEqual(0.0);
expect(Math.acosh(1)).toEqual(0);
expectNumber(Math.acosh(2)).toEqualDouble(1.3169578969248166);
expectNumber(Math.acosh(2.5)).toEqualDouble(1.566799236972411);
})
......@@ -172,7 +172,7 @@ export function testMath() : Result {
// 解决精度问题
expect(Math.asin(-1)).toEqual(-1.5707963267948966);
// expect(Math.asin(0.5)).toEqual(0.5235987755982989);
expect(Math.asin(0)).toEqual(0.0);
expect(Math.asin(0)).toEqual(0);
expect(Math.asin(1)).toEqual(1.5707963267948966);
})
......@@ -197,7 +197,7 @@ export function testMath() : Result {
// #END
// 解决精度问题
expectNumber(Math.asinh(1)).toEqualDouble(0.881373587019543);
expectNumber(Math.asinh(0)).toEqualDouble(0.0);
expectNumber(Math.asinh(0)).toEqualDouble(0);
expectNumber(Math.asinh(-1)).toEqualDouble(-0.881373587019543);
expectNumber(Math.asinh(2)).toEqualDouble(1.4436354751788103);
})
......@@ -217,7 +217,7 @@ export function testMath() : Result {
// #END
// 解决精度问题
expect(Math.atan(1)).toEqual(0.7853981633974483);
expect(Math.atan(0)).toEqual(0.0);
expect(Math.atan(0)).toEqual(0);
})
test('atan2', () => {
......@@ -243,7 +243,7 @@ export function testMath() : Result {
// expected output: 0
// #END
// 解决精度问题
expect(Math.atanh(0)).toEqual(0.0);
expect(Math.atanh(0)).toEqual(0);
// expect(Math.atanh(0.5)).toEqual(0.5493061443340548);
})
......
......@@ -76,12 +76,12 @@ export function testNumber() : Result {
expect(UTSNumber.isFinite(Double.POSITIVE_INFINITY)).toEqual(false);
// #endif
})
test('number-from-json-parse', () => {
type A = {
a:number
a : number
}
let aj = JSON.parse<A>('{"a":1}');
expect(aj?.a == 1).toEqual(true);
......@@ -89,13 +89,13 @@ export function testNumber() : Result {
expect(aj?.a == 1.0).toEqual(true);
expect(aj?.a == 1.0 as number).toEqual(true);
// #ifdef APP-ANDROID
expect(numberEquals(aj?.a,1)).toEqual(true);
expect(numberEquals(aj?.a,1 as number)).toEqual(true);
expect(numberEquals(aj?.a,1.0)).toEqual(true);
expect(numberEquals(aj?.a,1.0 as number)).toEqual(true);
let ki:Int = 1;
let kd:Double = 1.0;
let kf:Float = (1.0).toFloat();
expect(numberEquals(aj?.a, 1)).toEqual(true);
expect(numberEquals(aj?.a, 1 as number)).toEqual(true);
expect(numberEquals(aj?.a, 1.0)).toEqual(true);
expect(numberEquals(aj?.a, 1.0 as number)).toEqual(true);
let ki : Int = 1;
let kd : Double = 1.0;
let kf : Float = (1.0).toFloat();
expect(aj?.a == ki).toEqual(true);
expect(aj?.a == kd).toEqual(true);
expect(aj?.a == kf).toEqual(true);
......@@ -112,7 +112,7 @@ export function testNumber() : Result {
newA.a = 1.1
expect(aj?.a == newA.a).toEqual(false);
expect(aj?.a === newA.a).toEqual(false);
let a10 = JSON.parse("10")
let b10 = JSON.parse("10")
let c10 = JSON.parse("10.0")
......@@ -120,12 +120,12 @@ export function testNumber() : Result {
expect(a10 == c10).toEqual(true);
let aj2 = JSON.parse<A>('{"a":1}');
expect(aj?.a == aj2?.a).toEqual(true);
// #endif
})
test('isInteger', () => {
expect(Number.isInteger(12)).toEqual(true);
expect(Number.isInteger(12.01)).toEqual(false);
......@@ -133,6 +133,49 @@ export function testNumber() : Result {
expect(Number.isInteger(-213123112)).toEqual(true);
})
test('Unary-Operators', () => {
// #ifdef APP-ANDROID
let a = JSON.parse("1") as Number
a++;
expect(a.toString()).toEqual("2");
expect(UTSAndroid.getJavaClass(a).name).toEqual("io.dcloud.uts.UTSNumber");
a--;
expect(a.toString()).toEqual("1");
expect(UTSAndroid.getJavaClass(a).name).toEqual("io.dcloud.uts.UTSNumber");
a /= 0.5;
expect(a.toString()).toEqual("2");
expect(UTSAndroid.getJavaClass(a).name).toEqual("io.dcloud.uts.UTSNumber");
a *= 5;
expect(a.toString()).toEqual("10");
expect(UTSAndroid.getJavaClass(a).name).toEqual("io.dcloud.uts.UTSNumber");
a += -1;
expect(a.toString()).toEqual("9");
expect(UTSAndroid.getJavaClass(a).name).toEqual("io.dcloud.uts.UTSNumber");
a -= -2;
expect(a.toString()).toEqual("11");
expect(UTSAndroid.getJavaClass(a).name).toEqual("io.dcloud.uts.UTSNumber");
let a2 = a % 5
expect(a2.toString()).toEqual("1");
expect(UTSAndroid.getJavaClass(a2).name).toEqual("io.dcloud.uts.UTSNumber");
let b = 12
let c1 = b + a2
expect(c1.toString()).toEqual("13");
expect(UTSAndroid.getJavaClass(c1).name).toEqual("io.dcloud.uts.UTSNumber");
let c2 = a2 + 2
expect(c2.toString()).toEqual("3");
expect(UTSAndroid.getJavaClass(c2).name).toEqual("io.dcloud.uts.UTSNumber");
let c3 = 2 + a2
expect(c3.toString()).toEqual("3");
expect(UTSAndroid.getJavaClass(c3).name).toEqual("io.dcloud.uts.UTSNumber");
// #endif
})
test('isNaN', () => {
expect(isNaN(0)).toEqual(false);
// #ifdef APP-ANDROID
......@@ -171,13 +214,13 @@ export function testNumber() : Result {
expect((123456789987654).toString(16)).toEqual("7048861cc146");
expect((-0xff).toString(2)).toEqual("-11111111");
const a = 1e38
expect(a.toString(16).substring(0,12)).toEqual("4b3b4ca85a86");
expect(a.toString(16).substring(0, 12)).toEqual("4b3b4ca85a86");
expect(a.toString(16).length).toEqual(32);
expect(a.toString(16).substring(23)).toEqual("000000000");
expect(a.toString(2).length).toEqual(127);
expect(a.toString(2).substring(0,32)).toEqual("10010110011101101001100101010000");
expect(a.toString(2).substring(0, 32)).toEqual("10010110011101101001100101010000");
expect(a.toString(2).substring(100)).toEqual("000000000000000000000000000");
const b = 1e22
const bStr12 = b.toString(12)
......@@ -186,9 +229,17 @@ export function testNumber() : Result {
* 浏览器端:27373a86ba1a195400000
*/
expect(bStr12.length).toEqual(21);
expect(bStr12.substring(0,14)).toEqual("27373a86ba1a19");
expect(bStr12.substring(0, 14)).toEqual("27373a86ba1a19");
// #ifdef APP-ANDROID
expect(0.6.toString()).toEqual("0.6");
expect((new UTSNumber(2709954670497349.5)).toString()).toEqual("2709954670497349.5");
expect((new UTSNumber(0.00000000000001)).toString()).toEqual("1e-14");
expect((new UTSNumber(0.000001)).toString()).toEqual("0.000001");
expect((new UTSNumber(0.0000001)).toString()).toEqual("1e-7");
expect((new UTSNumber(100000000000000000000.0)).toString()).toEqual("100000000000000000000");
expect((new UTSNumber(1000000000000000000000.0)).toString()).toEqual("1e+21");
// #endif
})
test('valueOf', () => {
......
import { describe, test, expect, Result } from './tests.uts'
export function testPromise() : Result {
return describe("Promise", () => {
test('constructor', () => {
// #TEST Promise.Constructor,Promise.Constructor_1
// 常规方式
let p = new Promise<number>((resolve, reject) => {
let success = true;
setTimeout(() => {
if (success) {
resolve(2024)
} else {
let error = new Error("something going wrong")
reject(error)
}
}, 10);
});
p.then((res : number) => {
expect(res).toEqual(2024)
})
// 单个函数
let p1 = new Promise<any | null>((resolve : (value : any | null) => void) => {
setTimeout(function () {
resolve(null)
}, 10);
})
p1.then((res : any | null) => {
expect(res).toEqual(null)
})
// 指定函数类型
let p2 = new Promise((resolve : (value : string) => void, reject : (error : any | null) => void) => {
setTimeout(function () {
reject(null)
}, 10);
})
p2.then()
.catch((error : any | null) => {
expect(error).toEqual(null)
})
// #END
})
test('then', () => {
// #TEST Promise.then,Promise.then_1,Promise.then_2,Promise.then_3,Promise.then_4
let p = new Promise<string>((reslove, reject) => {
setTimeout(function () {
reslove("hello world")
}, 13);
})
p.then(
(res : string) : Promise<string> => {
expect(res).toEqual("hello world")
let p0 = new Promise<string>((reslove, reject) => {
var success = true;
setTimeout(function () {
success = true;
if (success) {
reslove(res + " 2024")
} else {
reject("first then p0 reject message")
}
}, 8);
})
return p0;
},
(err : any | null) : void => {
throw new Error("first then throw error")
}
)
.catch(
(err) : string => {
return "first catch return message"
}
)
.then(
(res) => {
expect(res).toEqual("hello world 2024")
}
)
.catch(
(err) => {
console.log(err, "this is seconded catch")
}
)
.finally(() => {
expect("finally").toEqual("finally")
})
// #END
})
test('catch', () => {
// #TEST Promise.catch,Promise.catch_1,Promise.catch_2,Promise.catch_3,Promise.catch_4
let p = Promise.reject()
p.then()
.catch((res : any | null) => {
expect(res).toEqual(null)
})
// catch 指定返回值
new Promise<string>((resolve, reject) => {
setTimeout(() => {
reject("2024")
}, 12)
})
.then()
.catch((res : any | null) : string => {
expect(res!).toEqual("2024")
return "hello world"
})
.then((res) => {
expect(res).toEqual("hello world")
})
// catch 返回Promise
new Promise<string>((resolve, reject) => {
setTimeout(() => {
reject("2024")
}, 12)
})
.then()
.catch((res : any | null) : Promise<number> => {
expect(res!).toEqual("2024")
let p = new Promise<number>((resolve, reject) => {
resolve(1)
})
return p
})
.then((res) => {
expect(res).toEqual(1)
})
// #END
})
test('finally', () => {
// #TEST Promise.finally
Promise.resolve(2)
.finally(() => {
console.log("finally")
})
.then((res) => {
expect(res).toEqual(2)
})
Promise.reject(3)
.finally(() => {
console.log("finally")
})
.catch((res) => {
expect(res).toEqual(3)
})
Promise.resolve(2)
.finally(() : number => {
console.log("finally")
return 88
})
.then((res) => {
expect(res).toEqual(2)
})
Promise.reject(3).finally(() => {
throw new Error("99")
})
.catch((res) => {
expect((res as Error).message).toEqual("99");
})
console.log("start");
Promise.reject(4).finally(() : Promise<number> => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(20)
}, 1000)
})
})
.catch((res) => {
expect(res).toEqual(4)
})
// #END
})
test('resolve', () => {
// #TEST Promise.resolve,Promise.resolve_1,Promise.resolve_2
// resolve array
Promise.resolve([1, 2, 3])
.then((res) => {
expect(res).toEqual([1, 2, 3])
})
// resolve string
Promise.resolve("成功")
.then((res) => {
expect(res).toEqual("成功");
})
// resolve null
Promise.resolve()
.then((res) => {
// expect(res).toEqual(null);
})
// resolve promise
const original = Promise.resolve(33)
const cast = Promise.resolve(original)
cast.then((res) => {
expect(res).toEqual(33);
})
// 注:此处飘红是编译器误报,实际可以判等
expect(original === cast).toEqual(true)
// #END
})
test('reject', () => {
// #TEST Promise.reject
// reject array
Promise.reject([1, 2, 3])
.catch((err) => {
expect(err).toEqual([1, 2, 3])
})
// reject error
Promise.reject(new Error("this is reject error message"))
.catch((err) => {
expect((err as Error).message).toEqual("this is reject error message");
})
// reject null
Promise.reject()
.catch((err) => {
expect(err).toEqual(null);
})
// reject promise
const original = Promise.reject(33)
const cast = Promise.reject(original)
cast.catch((err) => {
expect((err as Promise<any>) === original).toEqual(true);
})
expect(original === cast).toEqual(false)
// #END
})
test('all', () => {
// #TEST Promise.all
let p0 = new Promise<string>((resolve, reject) => {
setTimeout(function () {
resolve("1");
}, 10);
})
let p1 = new Promise<string>((resolve, reject) => {
setTimeout(function () {
resolve("2");
}, 10);
})
let p2 = new Promise<string>((resolve, reject) => {
setTimeout(function () {
resolve("3");
}, 10);
})
let p3 = new Promise<string>((resolve, reject) => {
setTimeout(function () {
let error = new Error("p3 reject reason")
reject(error);
}, 10);
})
// resolve
Promise.all([p0, p1, p2])
.then((res) => {
expect(res).toEqual(["1", "2", "3"])
})
// reject
Promise.all([p1, p2, p3])
.then()
.catch((error) => {
console.log(error);
expect((error as Error).message).toEqual("p3 reject reason");
})
// #END
})
test('allSettled', () => {
// #TEST Promise.allSettled
let p0 = new Promise<string | null>((resolve, reject) => {
setTimeout(function () {
resolve("1");
}, 10);
})
let p1 = new Promise<string | null>((resolve, reject) => {
setTimeout(function () {
resolve(null);
}, 10);
})
let p2 = new Promise<string | null>((resolve, reject) => {
setTimeout(function () {
reject(null)
}, 10);
})
let p3 = new Promise<string | null>((resolve, reject) => {
setTimeout(function () {
let error = new Error("p3 reject reason")
reject(error);
}, 10);
})
Promise.allSettled([p0, p1, p2, p3])
.then((res) => {
console.log(res);
let statusArr : string[] = []
res.forEach((item, index : number) => {
statusArr.add(item.status)
})
expect(statusArr).toEqual(["fulfilled", "fulfilled", "rejected", "rejected"])
})
// #END
})
test('any', () => {
// #TEST Promise.any
let p0 = new Promise<string | null>((resolve, reject) => {
setTimeout(function () {
resolve("1");
}, 10);
})
let p1 = new Promise<string | null>((resolve, reject) => {
setTimeout(function () {
resolve(null);
}, 15);
})
let p2 = new Promise<string | null>((resolve, reject) => {
setTimeout(function () {
reject(null)
}, 10);
})
let p3 = new Promise<string | null>((resolve, reject) => {
setTimeout(function () {
reject("error");
}, 12);
})
// test for resolve
Promise.any([p0, p1, p2])
.then((res) => {
console.log(res)
expect(res).toEqual("1");
})
// test for reject
Promise.any([p2, p3])
.then()
.catch(
(error : any | null) => {
console.log("test for promise.any error ==> ", error);
// #ifdef APP-IOS
expect((error as UTSPromiseAggregateError).name).toEqual("AggregateError");
expect((error as UTSPromiseAggregateError).message).toEqual("All promises were rejected");
expect((error as UTSPromiseAggregateError).errors).toEqual([null, "error"]);
// #endif
// #ifdef APP-ANDROID
expect((error as UTSPromiseAggregateError).name).toEqual("AggregateError");
expect((error as UTSPromiseAggregateError).message).toEqual("All promises were rejected");
expect((error as UTSPromiseAggregateError).errors).toEqual([null, "error"]);
// #endif
})
// #END
})
test('race', () => {
// #TEST Promise.race
let p0 = new Promise<string | null>((resolve, reject) => {
setTimeout(function () {
resolve("fast");
}, 10);
})
let p1 = new Promise<string | null>((resolve, reject) => {
setTimeout(function () {
resolve("slow");
}, 15);
})
let p2 = new Promise<string | null>((resolve, reject) => {
setTimeout(function () {
reject(null)
}, 12);
})
// test for resolve
Promise.race([p0, p1])
.then((res) => {
console.log("test for race resolve ===> ", res);
expect(res).toEqual("fast");
})
// test for reject
Promise.race([p1, p2])
.then()
.catch((error) => {
console.log("test for race reject ===> ", error);
expect(error).toEqual(null);
})
// #END
})
})
}
\ No newline at end of file
import { describe, test, expect, expectNumber, Result } from './tests.uts'
import { mockData } from './data.uts'
export function testUTSJSONObject() : Result {
return describe("utsjsonobject", () => {
test('keys', () => {
// #TEST UTSJSONObject.keys
let obj = {
name:"zhangsan",
age:11
}
expect(UTSJSONObject.keys(obj).length).toEqual(2);
// #END
let obj = {
name: "zhangsan",
age: 11
}
let ret1 = UTSJSONObject.keys(obj).length
console.log(ret1) //2
// #END
expect(ret1).toEqual(2);
expect(UTSJSONObject.keys(mockData).length).toEqual(2);
})
test('toJSONObject', () => {
// #ifdef APP-ANDROID
let result = {}
result["opt"] = "xxxx"
let subArray = [] as Array<UTSJSONObject>
let subModel = {}
subModel["name"] = "xxx"
subModel["type"] = 0
subArray.push(subModel)
let service = {}
service["name"] = "0xxxb34fb"
service["type"] = 0
//这个数据返回为空对象数组
service["array"] = subArray
result["service"] = service
expect(result.toJSONObject().toJSONString()).toEqual('{"opt":"xxxx","service":{"array":[{"name":"xxx","type":0}],"name":"0xxxb34fb","type":0}}');
let result = {}
result["opt"] = "xxxx"
let subArray = [] as Array<UTSJSONObject>
let subModel = {}
subModel["name"] = "xxx"
subModel["type"] = 0
subArray.push(subModel)
let service = {}
service["name"] = "0xxxb34fb"
service["type"] = 0
//这个数据返回为空对象数组
service["array"] = subArray
result["service"] = service
expect(result.toJSONObject().toJSONString()).toEqual('{"opt":"xxxx","service":{"array":[{"name":"xxx","type":0}],"name":"0xxxb34fb","type":0}}');
type TestData = {
num:number;
num2:number;
str:string;
}
let data1:TestData = {
num:1,
num2:2.369,
str:'test'
}
let data2 = JSON.parse<UTSJSONObject>(JSON.stringify(data1))
expect(data2!.toJSONString()).toEqual('{"str":"test","num":1.0,"num2":2.369}')
class TestData2 implements IJSONStringify{
toJSON():any|null{
return "122"
}
}
let testData2 = TestData2()
let dataClass = UTSAndroid.getJavaClass(data2)
let data3 = {
strA:"stringA",
dataClass:dataClass,
booleanB:false,
testData:testData2
}
expect(data3!.toJSONString()).toEqual('{"testData":"122","strA":"stringA","dataClass":"io.dcloud.uts.UTSJSONObject","booleanB":false}')
type TestData4 = {
name:string,
data:any,
}
let data4 : TestData4 = {
name:"张三",
data:data1
}
let data5 = {
data4 :data4
}
expect(data5!.toJSONString()).toEqual('{"data4":{"data":{"num":1,"num2":2.369,"str":"test"},"name":"张三"}}')
// class TestData6 implements IJsonStringify{
// toJSON():any|null{
// return JSON.parse("22")
// }
// }
// let testData6 = TestData6()
// let data6 = {
// data:testData6,
// array:[1,"22",false],
// name:"data6"
// }
// expect(data6!.toJSONString()).toEqual('{"data":22.0,"array":[1,"22",false],"name":"data6"}')
// console.log(data6.toJSONString())
// #endif
})
test('assign-notype', () => {
// #ifdef APP-ANDROID
// #TEST UTSJSONObject.assign
......@@ -82,6 +154,16 @@ export function testUTSJSONObject() : Result {
// #endif
})
test('get-no-exist-value', () => {
// #ifdef APP-ANDROID
let test = {
qq:[11,22]
}
expect(test.getNumber("qq[2]")).toEqual(null);
expect(test.getNumber("qq[2]",999)).toEqual(999);
// #endif
})
test('setvalue-after-get', () => {
// #ifdef APP-ANDROID
// #TEST UTSJSONObject.getJSON,UTSJSONObject.getArray
......@@ -102,8 +184,8 @@ export function testUTSJSONObject() : Result {
expect(firstCar!['value']).toEqual(20);
// #endif
})
test('get-speed', () => {
// #ifdef APP-ANDROID
// #TEST UTSJSONObject.getString
......@@ -119,7 +201,7 @@ export function testUTSJSONObject() : Result {
}
// #END
let spendTime = Date.now() - startTime
expect(spendTime < 300).toEqual(true);
expect(spendTime < 800).toEqual(true);
// #endif
})
......@@ -215,5 +297,14 @@ export function testUTSJSONObject() : Result {
// #END
})
test('useless-as', () => {
const obj = {
a: { b: { c: 'c' } }
};
((obj["a"] as UTSJSONObject)["b"] as UTSJSONObject)["c"] = "c1"
expect(obj.getString("a.b.c")).toEqual('c1')
})
})
}
\ No newline at end of file
import { describe, test, expect, expectNumber, Result } from './tests.uts'
function obtainInnerObject(obj:Any | null):UTSJSONObject{
// #ifdef APP-ANDROID
function obtainInnerObject(obj:any | null):UTSJSONObject{
let jsonStr = console.getLogV2(obj).slice(19,-17)
let a = JSON.parseArray(jsonStr)![0]
return a as UTSJSONObject
}
// #endif
export function testConsole() : Result {
return describe("log", () => {
......
const mockData = {
username:"lucy",
age:12
}
export {mockData}
......@@ -19,9 +19,10 @@ import { testType } from './Type.uts'
export { Result } from './tests.uts'
import { testArrayBuffer } from './ArrayBuffer.uts'
import { testNativeCode } from './NativeCode.uts'
import { testEncoder} from "./TextEncoder.uts"
import { testPromise} from "./Promise.uts"
import { testEncoder} from "./TextEncoder.uts"
import { testDecoder} from "./TextDecoder.uts"
// Promise、Proxy、Reflect、Weakmap、WeakSet 不支持
// Proxy、Reflect、Weakmap、WeakSet 不支持
export function runTests() : UTSJSONObject {
const ArrayRes = testArray();
const DateRes = testDate();
......@@ -40,12 +41,13 @@ export function runTests() : UTSJSONObject {
const TypeRes = testType();
const JSONLargeRes = testJSONLarge();
const consoleRes = testConsole();
const UTSJSONObjectRes = testUTSJSONObject();
const UTSJSONObjectRes = testUTSJSONObject();
// #ifdef APP-ANDROID || WEB
const ArrayBufferRes = testArrayBuffer();
// #endif
const NativeCodeRes = testNativeCode();
const PromiseRes = testPromise();
// #ifdef APP-ANDROID || WEB
const TextEncoderRes = testEncoder();
const TextDecoderRes = testDecoder();
......@@ -74,108 +76,7 @@ export function runTests() : UTSJSONObject {
TextEncoder: TextEncoderRes,
TextDecoder: TextDecoderRes,
// #endif
NativeCode: NativeCodeRes
NativeCode: NativeCodeRes,
Primise: PromiseRes
}
}
// #ifdef APP
import { expect } from './tests.uts'
export type TestKeepAliveCallback = (res: string) => void
export function onTest1(callback: TestKeepAliveCallback) {
callback("1")
callback("2")
}
@UTSJS.keepAlive
export function testKeepAlive(callback: TestKeepAliveCallback) {
callback("1")
callback("2")
}
export type TestKeepAliveOption = {
a: string
success: TestKeepAliveCallback | null
}
@UTSJS.keepAlive
export function testKeepAliveOption(option: TestKeepAliveOption) {
console.log(option.a);
option.success?.("1")
option.success?.("2")
}
export class TestKeepAliveClass {
constructor() {
super()
}
onTest(callback: TestKeepAliveCallback) {
callback("1")
callback("2")
}
@UTSJS.keepAlive
testKeepAlive(callback: TestKeepAliveCallback) {
callback("1")
callback("2")
}
@UTSJS.keepAlive
testKeepAliveOption(option: TestKeepAliveOption) {
console.log(option.a);
option.success?.("1")
option.success?.("2")
}
static onTestStatic(callback: TestKeepAliveCallback) {
callback("1")
callback("2")
}
@UTSJS.keepAlive
static testKeepAliveStatic(callback: TestKeepAliveCallback) {
callback("1")
callback("2")
}
@UTSJS.keepAlive
static testKeepAliveOptionStatic(option: TestKeepAliveOption) {
console.log(option.a);
option.success?.("1")
option.success?.("2")
}
}
interface ITest {
test(callback : (msg : string) => void) : void
}
class TestImpl implements ITest {
@UTSJS.keepAlive
test(callback : (msg : string) => void) : void {
callback("1")
callback("2")
}
}
export function createTest() : ITest {
return new TestImpl()
}
export function testNonKeepAlive(callback: (res: string) => void){
setTimeout(()=>{
callback("1")
},10)
}
export function testNonKeepAliveOption(option: TestKeepAliveOption) {
console.log(option.a);
setTimeout(()=>{
option.success?.("1")
},10)
}
// #endif
}
\ No newline at end of file
import { Matchers,NumberMatchers } from './Matchers.uts'
export const describes = new Map<string, Result>()
// #ifndef APP-IOS
export class Result implements IJSONStringify {
total = 0
passed: string[] = []
failed: string[] = []
toJSON():any|null{
let jsonRet = {
'total': this.total,
'passed': this.passed,
'failed': this.failed,
}
return jsonRet
}
}
// #endif
// #ifdef APP-IOS
export class Result {
total = 0
passed: string[] = []
failed: string[] = []
}
// #endif
let result: Result = new Result()
......@@ -24,7 +43,7 @@ export function test(name: string, fn: () => void) {
result.passed.push(name)
// console.log('push....',result.passed.length)
} catch (e) {
result.failed.push(`${name}:\n${(e as Error).message}`)
result.failed.push(`${name}:\n${e.message}`)
}
result.total++
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册