From 49908a43c79756ac9a3a8aca0636ca22f779a8d7 Mon Sep 17 00:00:00 2001 From: wupingyuan Date: Thu, 17 Aug 2023 09:30:17 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8F=90=E4=BA=A4xts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/ohosTest/ets/test/FTPClient.test.ets | 728 ++++++++++++++++++ .../entry/src/ohosTest/ets/test/List.test.ets | 6 +- .../src/ohosTest/ets/test/canarySpec.test.ets | 11 - .../ohosTest/ets/test/commandSpec.test.ets | 24 - .../src/ohosTest/ets/test/Ability.test.ets | 4 +- .../entry/src/ohosTest/ets/test/List.test.ets | 4 +- .../entry/src/ohosTest/ets/test/POP3.test.ets | 467 +++++++++++ .../entry/src/ohosTest/ets/test/List.test.ets | 4 +- .../entry/src/ohosTest/ets/test/SMTP.test.ets | 315 ++++++++ 9 files changed, 1518 insertions(+), 45 deletions(-) create mode 100644 FTPClient/entry/src/ohosTest/ets/test/FTPClient.test.ets delete mode 100644 FTPClient/entry/src/ohosTest/ets/test/canarySpec.test.ets delete mode 100644 FTPClient/entry/src/ohosTest/ets/test/commandSpec.test.ets create mode 100644 POP3Client/entry/src/ohosTest/ets/test/POP3.test.ets create mode 100644 SMTPClient/entry/src/ohosTest/ets/test/SMTP.test.ets diff --git a/FTPClient/entry/src/ohosTest/ets/test/FTPClient.test.ets b/FTPClient/entry/src/ohosTest/ets/test/FTPClient.test.ets new file mode 100644 index 0000000..9349266 --- /dev/null +++ b/FTPClient/entry/src/ohosTest/ets/test/FTPClient.test.ets @@ -0,0 +1,728 @@ +import hilog from '@ohos.hilog'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from '@ohos/hypium' +import NoTlsUtil from '../../../../../entry/src/main/ets/utils/FtpApiUtil' +import { AccessOptions, FileInfo, FileType, FTPResponse, UnixPermissions } from '@ohos/basic-ftp' +import fs from '@ohos.file.fs' +import buffer from '@ohos.buffer' +import socket from '@ohos.net.socket'; +import promptAction from '@ohos.promptAction' +import { ToolType } from '@ohos.multimodalInput.touchEvent' +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; + +export default function FTPClientTest() { + + let remoteChildPath; + let ftpUtil; + let message = 'Hello World' + let secure = false; + let user = 'zhaodongyang'; + let password = '123456'; + let host = '1.15.87.213'; + let secureOptions: socket.TLSConnectOptions = undefined + let remoteRoot = undefined + let currentFileList: FileInfo[] = []; + let localUploadFilePath = undefined; + let localUploadFileDir = undefined; + let localDownloadFilePath = undefined; + let localDownloadFileDir = undefined; + let selectFilePath = undefined; + let selectDirPath = undefined; + let isShowLog = false; + let isLogin = false; + let selectIndex: FileInfo[] = [] + let textValue = '' + let inputValue = 'click me' + let operationType = '' + + let option= { + ALPNProtocols: ["spdy/1", "http/1.1"], + address: { + address: '1.15.87.213', + port: 21, + family: 1 + }, + secureOptions: { + key: '', + cert: '', + ca: [''], + password: '123456', + protocols: [socket.Protocol.TLSv12, socket.Protocol.TLSv13], + useRemoteCipherPrefer: true, + signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", + cipherSuite: "AES256-SHA256" + } + } + + beforeAll(function () { + let context = AbilityDelegatorRegistry.getAbilityDelegator().getAppContext() + ftpUtil = new NoTlsUtil(context) + ftpUtil.setTag(); + + }) + + async function loginServer() { + message = '初始化参数,准备登录' + var loginInfo: AccessOptions = null + if (secure) { + let context = AbilityDelegatorRegistry.getAbilityDelegator().getAppContext() + let keyData = await context.resourceManager.getRawFileContent('client_rsa_private.pem.unsecure') + let key = ''; + for (let i = 0; i < keyData.length; i++) { + let todo = keyData[i] + let item = String.fromCharCode(todo); + key += item; + } + option.secureOptions.key = key; + + let certData = await context.resourceManager.getRawFileContent('client.pem') + let cert = ''; + for (let i = 0; i < certData.length; i++) { + let todo = certData[i] + let item = String.fromCharCode(todo); + cert += item; + } + option.secureOptions.cert = cert; + + + let caData = await context.resourceManager.getRawFileContent('ca.pem') + let ca = ''; + for (let i = 0; i < caData.length; i++) { + let todo = caData[i] + let item = String.fromCharCode(todo); + ca += item; + } + option.secureOptions.ca[0] = ca; + + loginInfo = { + host: '1.15.87.213', + user: 'zhaodongyang', + password: '123456', + secure: 'implicit', + secureOptions: option + } + } else { + loginInfo = { + host: '1.15.87.213', + user: 'zhaodongyang', + password: '123456', + secure: false, + secureOptions: undefined + } + } + if (ftpUtil) { + ftpUtil.doLogin(loginInfo, { + onLoginStart(info) { + }, + onLoginSuccess(result) { + }, + onLoginErr(err: Error) { + expect(0).assertEqual(1) + throw new Error("throw error:"+err) + } + }) + } + } + + + describe('FTPClientTest', function () { + + it('loginserver', 0, async function () { + message = '初始化参数,准备登录' + var loginInfo: AccessOptions = null + if (secure) { + let context = AbilityDelegatorRegistry.getAbilityDelegator().getAppContext() + let keyData = await context.resourceManager.getRawFileContent('client_rsa_private.pem.unsecure') + let key = ''; + for (let i = 0; i < keyData.length; i++) { + let todo = keyData[i] + let item = String.fromCharCode(todo); + key += item; + } + option.secureOptions.key = key; + + let certData = await context.resourceManager.getRawFileContent('client.pem') + let cert = ''; + for (let i = 0; i < certData.length; i++) { + let todo = certData[i] + let item = String.fromCharCode(todo); + cert += item; + } + option.secureOptions.cert = cert; + + + let caData = await context.resourceManager.getRawFileContent('ca.pem') + let ca = ''; + for (let i = 0; i < caData.length; i++) { + let todo = caData[i] + let item = String.fromCharCode(todo); + ca += item; + } + option.secureOptions.ca[0] = ca; + + loginInfo = { + host: '1.15.87.213', + user: 'zhaodongyang', + password: '123456', + secure: 'implicit', + secureOptions: option + } + } else { + loginInfo = { + host: '1.15.87.213', + user: 'zhaodongyang', + password: '123456', + secure: false, + secureOptions: undefined + } + } + if (ftpUtil) { + ftpUtil.doLogin(loginInfo, { + onLoginStart(info) { + }, + onLoginSuccess(result) { + expect(0).assertEqual(0) + }, + onLoginErr(err: Error) { + expect(0).assertEqual(1) + } + }) + } + + }) + + + it('getCurrentDirectoryAndFileList', 0, function () { + loginServer(); + if (ftpUtil) { + if (!ftpUtil.getLogin()) { + return; + } + ftpUtil.getCurrentDirectory({ + currentDirectoryErr(err: Error) { + expect(0).assertEqual(1) + }, + currentDirectoryStart(info) { + }, + currentDirectorySuccess(msg) { + remoteRoot = msg + let listName = ''; + if (remoteRoot == '' || remoteRoot == '\\' || remoteRoot == '/') { + listName = '' + } else { + listName = msg + } + ftpUtil.getList(listName, { + getListErr(err: Error) { + currentFileList = [] + expect(0).assertEqual(1) + }, + getListStart(info) { + }, + getListSuccess(result: FileInfo[]) { + expect(0).assertEqual(0) + if (!result) { + currentFileList = [] + } else { + currentFileList = result; + } + + } + }) + + } + }) + } + }) + + + it('createSingleFile', 0, function () { + loginServer(); + try { + localUploadFilePath = AbilityDelegatorRegistry.getAbilityDelegator().getAppContext().cacheDir + '/' + 'clientToServer.txt' + let file = fs.openSync(localUploadFilePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE) + let str = '' + for (let i = 0; i < 1024; i++) { + str += "客户端发送到服务端的信息,请查收\r\n" + } + fs.writeSync(file.fd, str) + fs.fsyncSync(file.fd) + fs.closeSync(file) + } catch (err) { + localUploadFilePath = undefined + expect(0).assertEqual(1) + } + }) + + it('uploadSingleFile', 0, function () { + loginServer(); + if (ftpUtil) { + if (!ftpUtil.getLogin()) { + operationType = '' + return + } + if (!localUploadFilePath || localUploadFilePath.length < 1) { + operationType = '' + return + } + if (!remoteRoot || remoteRoot.length < 1) { + operationType = '' + return + } + if (!inputValue || inputValue.length < 1) { + operationType = '' + return + } + ftpUtil.uploadSingleFile(localUploadFilePath, inputValue, { + uploadErr(err: Error) { + throw new Error("throw error:"+err) + expect(0).assertEqual(1) + }, + uploadStart(info) { + }, + uploadSuccess(msg: FTPResponse) { + }, + uploadProgress(currentSize: number, totalSize: number) { + } + }) + } + }) + + + it('createFileDir', 0, function () { + loginServer(); + try { + localUploadFileDir = AbilityDelegatorRegistry.getAbilityDelegator().getAppContext().cacheDir + '/client' + let localPath1 = localUploadFileDir + '/' + 'test1.txt' + let localPath2 = localUploadFileDir + '/' + 'test2.txt' + let localPath3 = localUploadFileDir + '/' + 'test3.txt' + + fs.mkdirSync(localUploadFileDir) + let file = fs.openSync(localPath1, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE) + let str = '' + for (let i = 0; i < 1024; i++) { + str += "客户端发送到服务端的信息,请查收\r\n" + } + fs.writeSync(file.fd, str) + fs.fsyncSync(file.fd) + fs.closeSync(file) + + let file1 = fs.openSync(localPath2, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE) + let str1 = '789456123abcd' + fs.writeSync(file1.fd, str1) + fs.fsyncSync(file1.fd) + fs.closeSync(file1) + + + let file3 = fs.openSync(localPath3, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE) + let str3 = '111111111111111111111111111111111111111111111111111111' + fs.writeSync(file3.fd, str3) + fs.fsyncSync(file3.fd) + fs.closeSync(file3) + + + } catch (err) { + localUploadFileDir = undefined + } + }) + + + it('uploadDir', 0, function () { + loginServer(); + if (ftpUtil) { + if (!ftpUtil.getLogin()) { + operationType = '' + return + } + if (!localUploadFileDir || localUploadFileDir.length < 1) { + operationType = '' + return + } + if (!remoteRoot || remoteRoot.length < 1) { + operationType = '' + return + } + if (!inputValue || inputValue.length < 1) { + operationType = '' + return + } + let regex = new RegExp(`^(?!_)(?!.*?_$)[a-zA-Z0-9_u4e00-u9fa5]+$`); //正则表达式 + if (!regex.test(inputValue)) { + operationType = '' + return + } + ftpUtil.uploadDir(localUploadFileDir, inputValue, { + uploadDirErr(err: Error) { + expect(0).assertEqual(1) + }, + uploadDirStart(info) { + }, + uploadDirSuccess(msg) { + }, + uploadDirProgress(currentSize: number, totalSize: number) { + } + }) + } + }) + + it('downloadSingleFile', 0, function () { + loginServer(); + + let localPath = AbilityDelegatorRegistry.getAbilityDelegator().getAppContext().cacheDir + '/' + 'downloadfromServer.txt' + + let file = fs.openSync(localPath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE) + if (ftpUtil) { + if (!ftpUtil.getLogin()) { + return + } + if (!remoteRoot || remoteRoot.length < 1) { + return + } + if (!selectFilePath || selectFilePath.length < 1) { + return + } + ftpUtil.downloadSingleFile(localPath, selectFilePath, { + downloadErr(err: Error) { + expect(0).assertEqual(1) + }, + downloadStart(info) { + }, + downloadSuccess(msg: FTPResponse) { + + let readBuffer = new ArrayBuffer(8192) + let readLen = fs.readSync(file.fd, readBuffer); + let trueData = readBuffer.slice(0, readLen) + let data = buffer.from(trueData).toString('utf8') + while ((readLen = fs.readSync(file.fd, readBuffer)) > 0) { + fs.fsyncSync(file.fd); + let trueData = readBuffer.slice(0, readLen) + let content = buffer.from(trueData).toString('utf8') + data = data + content + } + fs.fsyncSync(file.fd); + fs.close(file) + }, + downloadProgress(currentSize: number, totalSize: number) { + } + }) + } + }) + + it('downloadDir', 0, function () { + loginServer(); + let localDir = "/data/storage/el2/base/haps/entry/cache" + '/server' + + if (ftpUtil) { + if (!ftpUtil.getLogin()) { + return + } + if (!remoteRoot || remoteRoot.length < 1) { + return + } + if (!selectDirPath || selectDirPath.length < 1) { + return + } + ftpUtil.downloadDir(localDir, selectDirPath, { + downloadDirErr(err: Error) { + expect(0).assertEqual(1) + }, + downloadDirStart(info) { + }, + downloadDirSuccess(msg) { + }, + downloadDirProgress(currentSize: number, totalSize: number) { + } + }) + } + }) + + it('getFileSize', 0, function () { + loginServer(); + if (ftpUtil) { + if (!ftpUtil.getLogin()) { + return + } + if (!remoteRoot || remoteRoot.length < 1) { + return + } + if (!selectFilePath || selectFilePath.length < 1) { + return + } + ftpUtil.getFileSize(selectFilePath, { + getSizeErr(err: Error) { + expect(0).assertEqual(1) + }, + getSizeStart(info) { + }, + getSizeSuccess(result: number) { + } + }) + } + }) + + it('getServerFeatures', 0, function () { + loginServer(); + if (ftpUtil) { + if (!ftpUtil.getLogin()) { + return + } + ftpUtil.getServerFeatures({ + featuresErr(err: Error) { + expect(0).assertEqual(1) + }, + featuresStart(info) { + }, + featuresSuccess(msg: Map) { + } + }) + } + }) + + it('getLastModifyTime', 0, function () { + loginServer(); + if (ftpUtil) { + if (!ftpUtil.getLogin()) { + return + } + if (!remoteRoot || remoteRoot.length < 1) { + return + } + if (!selectFilePath || selectFilePath.length < 1) { + return + } + ftpUtil.getLastModify(selectFilePath, { + lastModifyErr(err: Error) { + expect(0).assertEqual(1) + }, + lastModifyStart(info) { + }, + lastModifySuccess(msg: Date) { + } + }) + } + }) + + + it('deleteSingleFile', 0, function () { + loginServer(); + + if (ftpUtil) { + if (!ftpUtil.getLogin()) { + return + } + if (!remoteRoot || remoteRoot.length < 1) { + return + } + if (!selectFilePath || selectFilePath.length < 1) { + return + } + ftpUtil.deleteFile(selectFilePath, { + deleteFileErr(err: Error) { + expect(0).assertEqual(1) + }, + deleteFileStart(info) { + }, + deleteFileSuccess(msg: FTPResponse) { + } + }) + } + }) + + + it('cdToParentDirectory', 0, function () { + loginServer(); + + if (ftpUtil) { + if (!ftpUtil.getLogin()) { + return + } + if (!remoteRoot || remoteRoot.length < 1) { + return + } + ftpUtil.cdToParentDirectory({ + cdToParentDirectoryErr(err: Error) { + expect(0).assertEqual(1) + }, + cdToParentDirectoryStart(info) { + }, + cdToParentDirectorySuccess(res: FTPResponse) { + } + }) + } + }) + + + it('ensureRemotePath', 0, function () { + loginServer(); + + if (ftpUtil) { + if (!ftpUtil.getLogin()) { + operationType = '' + return + } + if (!remoteRoot || remoteRoot.length < 1) { + operationType = '' + return + } + if (!inputValue || inputValue.length < 1) { + operationType = '' + return + } + let regex = new RegExp(`^(?!_)(?!.*?_$)[a-zA-Z0-9_u4e00-u9fa5]+$`); //正则表达式 + if (!regex.test(inputValue)) { + operationType = '' + return + } + ftpUtil.ensureRemotePath(inputValue, { + ensureRemotePathErr(err: Error) { + expect(0).assertEqual(1) + operationType = '' + }, + ensureRemotePathStart(info) { + operationType = '' + }, + ensureRemotePathSuccess(result) { + operationType = '' + } + }) + } + }) + + it('deleteEmptyDirectory', 0, function () { + loginServer(); + + if (ftpUtil) { + if (!ftpUtil.getLogin()) { + return + } + if (!remoteRoot || remoteRoot.length < 1) { + return + } + if (!selectDirPath || selectDirPath.length < 1) { + return + } + + ftpUtil.deleteEmptyDirectory(selectDirPath, { + deleteEmptyDirectoryErr(err: Error) { + expect(0).assertEqual(1) + }, + deleteEmptyDirectoryStart(info) { + }, + deleteEmptyDirectorySuccess(result: FTPResponse) { + } + }) + } + }) + + + it('deleteAll', 0, function () { + loginServer(); + + if (ftpUtil) { + if (!ftpUtil.getLogin()) { + return + } + if (!remoteRoot || remoteRoot.length < 1) { + return + } + if (!selectDirPath || selectDirPath.length < 1) { + return + } + + ftpUtil.deleteAll(selectDirPath, { + deleteAllErr(err: Error) { + expect(0).assertEqual(1) + }, + deleteAllStart(info) { + }, + deleteAllSuccess(result) { + } + }) + } + }) + + it('deleteAllButSelf', 0, function () { + loginServer(); + + if (ftpUtil) { + if (!ftpUtil.getLogin()) { + return + } + if (!remoteRoot || remoteRoot.length < 1) { + return + } + ftpUtil.deleteAllButSelf({ + deleteAllButSelfErr(err: Error) { + expect(0).assertEqual(1) + }, + deleteAllButSelfStart(info) { + }, + deleteAllButSelfSuccess(result) { + } + }) + } + }) + + it('renameFile', 0, function () { + loginServer(); + + if (ftpUtil) { + if (!ftpUtil.getLogin()) { + operationType = '' + return + } + if (!remoteRoot || remoteRoot.length < 1) { + operationType = '' + return + } + if (!inputValue || inputValue.length < 1) { + operationType = '' + return + } + if (!selectFilePath || selectFilePath.length < 1) { + return + } + + ftpUtil.renameFile(inputValue, selectFilePath, { + renameFileErr(err: Error) { + expect(0).assertEqual(1) + operationType = '' + }, + renameFileStart(info) { + operationType = '' + }, + renameFileSuccess(result: FTPResponse) { + operationType = '' + } + }) + } + }) + + + it('setWorkingDirectory', 0, function () { + loginServer(); + + if (ftpUtil) { + if (!ftpUtil.getLogin()) { + return + } + if (!remoteRoot || remoteRoot.length < 1) { + return + } + if (!remoteChildPath || remoteChildPath.length < 1) { + return + } + + ftpUtil.setWorkingDirectory(remoteChildPath, { + setWorkingDirectoryErr(err: Error) { + expect(0).assertEqual(1) + }, + setWorkingDirectoryStart(info) { + }, + setWorkingDirectorySuccess(result: FTPResponse) { + } + }) + } + }) + + }) +} \ No newline at end of file diff --git a/FTPClient/entry/src/ohosTest/ets/test/List.test.ets b/FTPClient/entry/src/ohosTest/ets/test/List.test.ets index 2df934b..d140b95 100644 --- a/FTPClient/entry/src/ohosTest/ets/test/List.test.ets +++ b/FTPClient/entry/src/ohosTest/ets/test/List.test.ets @@ -1,7 +1,5 @@ -import abilityTest from './Ability.test' -import canarySpecTest from './canarySpec.test' +import FTPClientTest from './FTPClient.test' export default function testsuite() { - abilityTest() - canarySpecTest() + FTPClientTest() } \ No newline at end of file diff --git a/FTPClient/entry/src/ohosTest/ets/test/canarySpec.test.ets b/FTPClient/entry/src/ohosTest/ets/test/canarySpec.test.ets deleted file mode 100644 index 41a8aaf..0000000 --- a/FTPClient/entry/src/ohosTest/ets/test/canarySpec.test.ets +++ /dev/null @@ -1,11 +0,0 @@ -import hilog from '@ohos.hilog'; -import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it as _it} from '@ohos/hypium' - -export default function canarySpecTest() { - describe('canarySpecTest', function () { - - _it("can run unit tests",0, function() { - expect(true).assertTrue(); - }); - }) -} \ No newline at end of file diff --git a/FTPClient/entry/src/ohosTest/ets/test/commandSpec.test.ets b/FTPClient/entry/src/ohosTest/ets/test/commandSpec.test.ets deleted file mode 100644 index 6547ce9..0000000 --- a/FTPClient/entry/src/ohosTest/ets/test/commandSpec.test.ets +++ /dev/null @@ -1,24 +0,0 @@ -import hilog from '@ohos.hilog'; -import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from '@ohos/hypium' -import { AccessOptions, Client, FileInfo, FTPResponse, join, to } from '@ohos/basic-ftp' -const MockFtpServer = require("./MockFtpServer"); - -const FEAT_REPLY = ` -211-Extensions supported: - MLST size*;create - SIZE -211 END -`; -const NO_FEAT_REPLY = ` -211 No features -`; -const FILENAME = "file.txt" - -export default function commandSpecTest() { - describe('commandSpecTest', function () { - - it("can run unit tests",0, function() { - expect(true).assertTrue(); - }); - }) -} \ No newline at end of file diff --git a/POP3Client/entry/src/ohosTest/ets/test/Ability.test.ets b/POP3Client/entry/src/ohosTest/ets/test/Ability.test.ets index 140ca1a..50f4ed6 100644 --- a/POP3Client/entry/src/ohosTest/ets/test/Ability.test.ets +++ b/POP3Client/entry/src/ohosTest/ets/test/Ability.test.ets @@ -1,8 +1,8 @@ import hilog from '@ohos.hilog'; import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from '@ohos/hypium' -export default function abilityTest() { - describe('ActsAbilityTest', function () { +export default function POP3Test() { + describe('POP3Test', function () { // Defines a test suite. Two parameters are supported: test suite name and test suite function. beforeAll(function () { // Presets an action, which is performed only once before all test cases of the test suite start. diff --git a/POP3Client/entry/src/ohosTest/ets/test/List.test.ets b/POP3Client/entry/src/ohosTest/ets/test/List.test.ets index d766fe2..500d462 100644 --- a/POP3Client/entry/src/ohosTest/ets/test/List.test.ets +++ b/POP3Client/entry/src/ohosTest/ets/test/List.test.ets @@ -1,5 +1,5 @@ -import abilityTest from './Ability.test' +import POP3Test from './POP3.test' export default function testsuite() { - abilityTest() + POP3Test() } \ No newline at end of file diff --git a/POP3Client/entry/src/ohosTest/ets/test/POP3.test.ets b/POP3Client/entry/src/ohosTest/ets/test/POP3.test.ets new file mode 100644 index 0000000..b575f8e --- /dev/null +++ b/POP3Client/entry/src/ohosTest/ets/test/POP3.test.ets @@ -0,0 +1,467 @@ +import hilog from '@ohos.hilog'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from '@ohos/hypium' +import promptAction from '@ohos.promptAction' +import router from '@ohos.router' +import socket from '@ohos.net.socket' +import Pop3Command from '@ohos/node_pop3' +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; +import MsgBean from '../../../../../entry/src/main/ets/MsgBean' + +export default function POP3Test() { + + let message = 'Hello World' + let account = '479868299' + let password = 'bfxeualuaxambged' + let mailType = '@qq.com' + let textValue = '' + let inputValue = 'click me' + let secure = false + let listData: Array = [] + let client: Pop3Command = undefined + let selectMsgNum: number = -1 + let isListShow: boolean = false + let msgList: Array = [] + + describe('POP3Test', function () { + + + beforeAll(async function () { + globalThis.client = undefined; + let jumpOption = undefined; + try { + if (this.secure) { + let option: socket.TLSConnectOptions = { + ALPNProtocols: ["spdy/1", "http/1.1"], + address: { + address: 'smtp.qq.com', + port: 465, + family: 1 + }, + secureOptions: { + key: '', + cert: '', + ca: [''], + useRemoteCipherPrefer: true, + } + } + let context = AbilityDelegatorRegistry.getAbilityDelegator().getAppContext() + let ca0Data = await context.resourceManager.getRawFileContent('QQMailMiddle.pem') + let ca0 = ''; + for (let i = 0; i < ca0Data.length; i++) { + let todo = ca0Data[i] + let item = String.fromCharCode(todo); + ca0 += item; + } + // @ts-ignore + option.secureOptions.ca[0] = ca0; + + let ca1Data = await context.resourceManager.getRawFileContent('QQMailRoot.pem') + let ca1 = ''; + for (let i = 0; i < ca1Data.length; i++) { + let todo = ca1Data[i] + let item = String.fromCharCode(todo); + ca1 += item; + } + // @ts-ignore + option.secureOptions.ca[1] = ca1; + jumpOption = { + host: 'pop.qq.com', + port: 995, + user: account + mailType, + password: password, + timeout: 30000, + servername: 'pop.qq.com', + tls: true, + tlsOptions: option + } + } else { + jumpOption = { + host: 'pop.qq.com', + port: 110, + user: account + mailType, + password: password, + timeout: 30000, + servername: 'pop.qq.com', + tls: false, + tlsOptions: undefined + } + } + } catch (err) { + expect(0).assertEqual(1) + } + }) + + it('diyLogin', 0, async function () { + try { + if (!globalThis.client) { + let client: Pop3Command = undefined; + if (this.secure) { + let option: socket.TLSConnectOptions = { + ALPNProtocols: ["spdy/1", "http/1.1"], + address: { + address: 'smtp.qq.com', + port: 465, + family: 1 + }, + secureOptions: { + key: '', + cert: '', + ca: [''], + useRemoteCipherPrefer: true, + } + } + let context = AbilityDelegatorRegistry.getAbilityDelegator().getAppContext() + let ca0Data = await context.resourceManager.getRawFileContent('QQMailMiddle.pem') + let ca0 = ''; + for (let i = 0; i < ca0Data.length; i++) { + let todo = ca0Data[i] + let item = String.fromCharCode(todo); + ca0 += item; + } + // @ts-ignore + option.secureOptions.ca[0] = ca0; + + let ca1Data = await context.resourceManager.getRawFileContent('QQMailRoot.pem') + let ca1 = ''; + for (let i = 0; i < ca1Data.length; i++) { + let todo = ca1Data[i] + let item = String.fromCharCode(todo); + ca1 += item; + } + // @ts-ignore + option.secureOptions.ca[1] = ca1; + + client = new Pop3Command({ + host: 'pop.qq.com', + port: 465, + user: account + mailType, + password: password, + timeout: 30000, + servername: 'pop.qq.com', + tls: true, + tlsOptions: option + }); + } else { + client = new Pop3Command({ + host: 'pop.qq.com', + port: 465, + user: account + mailType, + password: password, + timeout: 30000, + servername: 'pop.qq.com', + tls: false, + tlsOptions: undefined + }); + } + globalThis.client = client + } + + if (globalThis.client) { + // 因为没有登录状态判断的接口 所以登陆之前先退出一下 防止已经登录导致出错了 + try { + const [quitInfo] = await globalThis.client.commond('QUIT'); + } catch (err) { + + } + // These must be in order + await globalThis.client.connect(); + await globalThis.client.command('USER', account + mailType); + await globalThis.client.command('PASS', password); + } + } catch (err) { + expect(0).assertEqual(1) + } + }) + + it('autoLogin', 0, async function () { + globalThis.client = undefined; + let jumpOption = undefined; + try { + if (this.secure) { + let option: socket.TLSConnectOptions = { + ALPNProtocols: ["spdy/1", "http/1.1"], + address: { + address: 'smtp.qq.com', + port: 465, + family: 1 + }, + secureOptions: { + key: '', + cert: '', + ca: [''], + useRemoteCipherPrefer: true, + } + } + let context = AbilityDelegatorRegistry.getAbilityDelegator().getAppContext() + let ca0Data = await context.resourceManager.getRawFileContent('QQMailMiddle.pem') + let ca0 = ''; + for (let i = 0; i < ca0Data.length; i++) { + let todo = ca0Data[i] + let item = String.fromCharCode(todo); + ca0 += item; + } + // @ts-ignore + option.secureOptions.ca[0] = ca0; + + let ca1Data = await context.resourceManager.getRawFileContent('QQMailRoot.pem') + let ca1 = ''; + for (let i = 0; i < ca1Data.length; i++) { + let todo = ca1Data[i] + let item = String.fromCharCode(todo); + ca1 += item; + } + // @ts-ignore + option.secureOptions.ca[1] = ca1; + jumpOption = { + host: 'pop.qq.com', + port: 995, + user: account + mailType, + password: password, + timeout: 30000, + servername: 'pop.qq.com', + tls: true, + tlsOptions: option + } + } else { + jumpOption = { + host: 'pop.qq.com', + port: 110, + user: account + mailType, + password: password, + timeout: 30000, + servername: 'pop.qq.com', + tls: false, + tlsOptions: undefined + } + } + } catch (err) { + expect(0).assertEqual(1) + } + }) + + it('sendSTAT', 0, async function () { + isListShow = false + msgList = [] + listData = [] + selectMsgNum = -1; + try { + if (globalThis.client) { + let result = await globalThis.client.STAT() + if (result && result.toString() && result.toString().length > 0) { + let arr = result.toString().split(' ') + if (arr && arr.length >= 1) { + let totalMailSize = parseInt(arr[0]); + if (totalMailSize > 0) { + isListShow = true; + listData.push(`获取到STAT命令的结果:${'\r\n'}${result}`) + return + } + } + } + listData.push(`获取到STAT命令的结果:${'\r\n'}获取到的结果为空`) + } else { + listData.push(`账号未登录,请需重新登录`) + expect(0).assertEqual(1) + } + + } catch (err) { + listData.push(`获取STAT命令结果失败:${'\r\n'}${err.message}`) + expect(0).assertEqual(1) + } + }) + + it('sendLIST', 0, async function () { + msgList = []; + listData = [] + selectMsgNum = -1; + try { + if (client) { + let result = await client.LIST() + if (result && result.toString() && result.toString().length > 0) { + let arr = result.toString().split(',') + if (arr && arr.length >= 2) { + isListShow = true; + for (let i = 0; i < arr.length; i += 2) { + let index = parseInt(arr[i]); + let size = parseInt(arr[i+1]); + listData.push(`列表条目,序号:${index},大小:${size}`) + let bean = new MsgBean() + bean.setIndex(index); + bean.setSize(size); + msgList.push(bean); + } + return + } + } + listData.push(`获取到LIST命令的结果解析失败,${result}`) + expect(0).assertEqual(1) + } else { + listData.push(`账号未登录,请需重新登录`) + expect(0).assertEqual(1) + } + + } catch (err) { + listData.push(`获取LIST命令结果失败:${'\r\n'}${err.message}`) + expect(0).assertEqual(1) + } + }) + + it('sendNOOP', 0, async function () { + msgList = [] + listData = [] + selectMsgNum = -1; + try { + if (client) { + let result = await client.NOOP() + listData.push(`获取到NOOP命令的结果:${'\r\n'}${JSON.stringify(result)}`) + } else { + listData.push(`账号未登录,请需重新登录`) + expect(0).assertEqual(1) + } + + } catch (err) { + listData.push(`获取NOOP命令结果失败:${'\r\n'}${err.message}`) + expect(0).assertEqual(1) + } + }) + + it('sendUIDL', 0, async function () { + listData = [] + try { + if (selectMsgNum === -1) { + expect(0).assertEqual(1) + return + } + if (client) { + let result = await client.UIDL(selectMsgNum + '') + listData.push(`获取到UIDL命令的结果:${'\r\n'}${result}`) + } else { + listData.push(`账号未登录,请需重新登录`) + expect(0).assertEqual(1) + } + + } catch (err) { + listData.push(`获取UIDL命令结果失败:${'\r\n'}${err.message}`) + expect(0).assertEqual(1) + } + selectMsgNum = -1; + }) + + it('sendLAST', 0, async function () { + msgList = [] + listData = [] + selectMsgNum = -1; + try { + if (client) { + let result = await client.LAST() + listData.push(`获取到LAST命令的结果:${'\r\n'}${result}`) + } else { + listData.push(`账号未登录,请需重新登录`) + expect(0).assertEqual(1) + } + + } catch (err) { + listData.push(`获取LAST命令结果失败:${'\r\n'}${err.message}`) + expect(0).assertEqual(1) + } + }) + + it('sendDELE', 0, async function () { + listData = [] + try { + if (selectMsgNum === -1) { + expect(0).assertEqual(1) + return + } + if (client) { + let result = await client.DELE(selectMsgNum + '') + listData.push(`获取到DELE命令的结果:${'\r\n'}${result}`) + } else { + listData.push(`账号未登录,请需重新登录`) + expect(0).assertEqual(1) + } + + } catch (err) { + listData.push(`获取DELE命令结果失败:${'\r\n'}${err.message}`) + expect(0).assertEqual(1) + } + selectMsgNum = -1; + }) + + it('sendRSET', 0, async function () { + listData = [] + try { + if (selectMsgNum === -1) { + return + } + if (client) { + let delResult = client.DELE(selectMsgNum + '') + listData.push(`发送DELE命令删除的结果:${'\r\n'}${delResult}`) + let result = await client.RSET() // 用于撤销DELE命令 所以不需要等DELE命令返回 + listData.push(`发送RSET命令取消删除操作的结果:${'\r\n'}${result}`) + } else { + listData.push(`账号未登录,请需重新登录`) + expect(0).assertEqual(1) + } + + } catch (err) { + listData.push(`获取RSET命令结果失败:${'\r\n'}${err.message}`) + expect(0).assertEqual(1) + } + selectMsgNum = -1; + }) + + it('sendRETR', 0, async function () { + listData = [] + try { + if (selectMsgNum === -1) { + expect(0).assertEqual(1) + return + } + if (client) { + + let result = await client.RETR(selectMsgNum + '') + listData.push(`获取到RETR命令的结果,结果长度为:${'\r\n'}${result.toString().length}${'\r\n'}}`) + if (result.toString().length > 1000) { + listData.push(`由于RETR命令的结果太长text无法完全显示,取最后1000字节显示:${'\r\n'}${result.toString() + .substring(result.toString().length - 1000, result.toString().length)}`) + }else { + listData.push(`ETR命令的结果显示:${'\r\n'}${result.toString()}`) + } + + } else { + listData.push(`账号未登录,请需重新登录`) + expect(0).assertEqual(1) + } + + } catch (err) { + listData.push(`获取RETR命令结果失败:${'\r\n'}${err.message}`) + expect(0).assertEqual(1) + } + selectMsgNum = -1; + }) + + it('sendQUIT', 0, async function () { + msgList = [] + listData = [] + selectMsgNum = -1; + try { + + if (client) { + const [quitInfo] = await client.QUIT(); + + listData.push(`获取到QUIT命令的结果:${'\r\n'}${quitInfo}`) + + } else { + listData.push(`账号未登录,请需重新登录`) + expect(0).assertEqual(1) + } + + } catch (err) { + listData.push(`获取RETR命令结果失败:${'\r\n'}${err.message}`) + expect(0).assertEqual(1) + } + }) + + }) +} \ No newline at end of file diff --git a/SMTPClient/entry/src/ohosTest/ets/test/List.test.ets b/SMTPClient/entry/src/ohosTest/ets/test/List.test.ets index d766fe2..f59b1be 100644 --- a/SMTPClient/entry/src/ohosTest/ets/test/List.test.ets +++ b/SMTPClient/entry/src/ohosTest/ets/test/List.test.ets @@ -1,5 +1,5 @@ -import abilityTest from './Ability.test' +import SMTPTest from './SMTP.test' export default function testsuite() { - abilityTest() + SMTPTest() } \ No newline at end of file diff --git a/SMTPClient/entry/src/ohosTest/ets/test/SMTP.test.ets b/SMTPClient/entry/src/ohosTest/ets/test/SMTP.test.ets new file mode 100644 index 0000000..74d436d --- /dev/null +++ b/SMTPClient/entry/src/ohosTest/ets/test/SMTP.test.ets @@ -0,0 +1,315 @@ +import hilog from '@ohos.hilog'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium' +import { AUTH_METHODS, SMTPClient } from '@ohos/emailjs' +import promptAction from '@ohos.promptAction' +import router from '@ohos.router' +import socket from '@ohos.net.socket' +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; +import { Message, MessageHeaders, MessageAttachment } from '@ohos/emailjs' +import fs from '@ohos.file.fs'; + +export default function SMTPTest() { + + let message = 'Hello World' + let account = '479868299' + let password = 'bfxeualuaxambged' + let mailType = '@qq.com' + let textValue = '' + let inputValue = 'click me' + let secure = false + let attachment: Array = [] + + + beforeAll(function () { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + loginmail() + }) + + async function loginmail() { + try { + if (!globalThis.client) { + let client: SMTPClient = undefined; + if (secure) { + let option: socket.TLSConnectOptions = { + ALPNProtocols: ["spdy/1", "http/1.1"], + address: { + address: 'smtp.qq.com', + port: 465, + family: 1 + }, + secureOptions: { + key: '', + cert: '', + ca: [''], + useRemoteCipherPrefer: true, + } + } + let context: Context = AbilityDelegatorRegistry.getAbilityDelegator().getAppContext() + let ca0Data = await context.resourceManager.getRawFileContent('QQMailMiddle.pem') + let ca0 = ''; + for (let i = 0; i < ca0Data.length; i++) { + let todo = ca0Data[i] + let item = String.fromCharCode(todo); + ca0 += item; + } + // @ts-ignore + option.secureOptions.ca[0] = ca0; + + let ca1Data = await context.resourceManager.getRawFileContent('QQMailRoot.pem') + let ca1 = ''; + for (let i = 0; i < ca1Data.length; i++) { + let todo = ca1Data[i] + let item = String.fromCharCode(todo); + ca1 += item; + } + // @ts-ignore + option.secureOptions.ca[1] = ca1; + + client = new SMTPClient({ + user: '479868299@qq.com', + password: 'bfxeualuaxambged', + host: 'smtp.qq.com', + port: 465, + timeout: 30000, + authentication: [AUTH_METHODS.LOGIN], + ssl: option, + tls: undefined + }); + } else { + client = new SMTPClient({ + user: '479868299@qq.com', + password: 'bfxeualuaxambged', + host: 'smtp.qq.com', + port: 25, + timeout: 30000, + authentication: [AUTH_METHODS.LOGIN], + ssl: false, + tls: undefined + }); + } + globalThis.client = client + } + if (globalThis.client) { + if (!globalThis.client.isLogin()) { + globalThis.client.login((err, result) => { + if (!err && result == true) { + expect(0).assertContain(0) + } else { + expect(0).assertContain(1) + return + } + }) + } + } + } catch (err) { + expect(0).assertContain(1) + return + } + } + + + function createAttachment() { + try { + if (attachment && attachment.length == 0) { + let context: Context = AbilityDelegatorRegistry.getAbilityDelegator().getAppContext() + let randomNum = Math.round(Math.random() * 1024 + 1); + let filePath = context.cacheDir + '/' + 'attachment-' + randomNum + '.txt' + let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE) + let str = "客户端发送到服务端的信息,请查收\r\n" + fs.writeSync(file.fd, str) + fs.fsyncSync(file.fd) + fs.closeSync(file) + let attach: MessageAttachment = { + name: 'attachment-' + randomNum + '.txt', + path: filePath, + type: '.txt', + size: str.length + } + attachment.push(attach) + } else if (attachment && attachment.length == 1) { + let context: Context = AbilityDelegatorRegistry.getAbilityDelegator().getAppContext() + let filePath = context.cacheDir + '/test.jpg' + context.resourceManager.getRawFileContent('test.jpg').then((imageData) => { + if (imageData) { + let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE) + fs.writeSync(file.fd, imageData.buffer) + fs.fsyncSync(file.fd) + fs.closeSync(file) + let attach: MessageAttachment = { + name: 'test.jpg', + path: filePath, + type: 'jpg', + size: imageData.buffer.byteLength + } + attachment.push(attach) + } else { + expect(0).assertEqual(1) + } + }).catch((err: Error) => { + expect(0).assertEqual(1) + }) + } else if (attachment && attachment.length == 2) { + let context: Context = AbilityDelegatorRegistry.getAbilityDelegator().getAppContext() + let filePath = context.cacheDir + '/test.docx' + context.resourceManager.getRawFileContent('test.docx').then((wordData) => { + if (wordData) { + let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE) + fs.writeSync(file.fd, wordData.buffer) + fs.fsyncSync(file.fd) + fs.closeSync(file) + let attach: MessageAttachment = { + name: 'test.docx', + path: filePath, + type: 'docx', + size: wordData.buffer.byteLength + } + attachment.push(attach) + } else { + expect(0).assertEqual(1) + } + }).catch((err: Error) => { + expect(0).assertEqual(1) + }) + } else if (attachment && attachment.length == 3) { + let context: Context = AbilityDelegatorRegistry.getAbilityDelegator().getAppContext() + let filePath = context.cacheDir + '/test.xlsx' + context.resourceManager.getRawFileContent('test.xlsx').then((excelData) => { + if (excelData) { + let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE) + fs.writeSync(file.fd, excelData.buffer) + fs.fsyncSync(file.fd) + fs.closeSync(file) + let attach: MessageAttachment = { + name: 'test.xlsx', + path: filePath, + type: 'xlsx', + size: excelData.buffer.byteLength + } + attachment.push(attach) + } else { + expect(0).assertEqual(1) + } + }).catch((err: Error) => { + expect(0).assertEqual(1) + }) + } else { + expect(0).assertEqual(1) + } + + } catch (err) { + console.log("SMTP------------>createAttachment------>error:" + err) + expect(0).assertEqual(1) + } + } + + + describe('SMTPTest', function () { + + + it('login', 0, async function () { + // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. + try { + if (!globalThis.client) { + let client: SMTPClient = undefined; + if (secure) { + let option: socket.TLSConnectOptions = { + ALPNProtocols: ["spdy/1", "http/1.1"], + address: { + address: 'smtp.qq.com', + port: 465, + family: 1 + }, + secureOptions: { + key: '', + cert: '', + ca: [''], + useRemoteCipherPrefer: true, + } + } + let context: Context = AbilityDelegatorRegistry.getAbilityDelegator().getAppContext() + let ca0Data = await context.resourceManager.getRawFileContent('QQMailMiddle.pem') + let ca0 = ''; + for (let i = 0; i < ca0Data.length; i++) { + let todo = ca0Data[i] + let item = String.fromCharCode(todo); + ca0 += item; + } + // @ts-ignore + option.secureOptions.ca[0] = ca0; + + let ca1Data = await context.resourceManager.getRawFileContent('QQMailRoot.pem') + let ca1 = ''; + for (let i = 0; i < ca1Data.length; i++) { + let todo = ca1Data[i] + let item = String.fromCharCode(todo); + ca1 += item; + } + // @ts-ignore + option.secureOptions.ca[1] = ca1; + + client = new SMTPClient({ + user: '479868299@qq.com', + password: 'bfxeualuaxambged', + host: 'smtp.qq.com', + port: 465, + timeout: 30000, + authentication: [AUTH_METHODS.LOGIN], + ssl: option, + tls: undefined + }); + } else { + client = new SMTPClient({ + user: '479868299@qq.com', + password: 'bfxeualuaxambged', + host: 'smtp.qq.com', + port: 25, + timeout: 30000, + authentication: [AUTH_METHODS.LOGIN], + ssl: false, + tls: undefined + }); + } + globalThis.client = client + } + if (globalThis.client) { + if (!globalThis.client.isLogin()) { + globalThis.client.login((err, result) => { + if (!err && result == true) { + expect(0).assertContain(0) + } else { + expect(0).assertContain(1) + } + }) + } + } + } catch (err) { + console.log("SMPT----------->LOGIN------->ERROR:" + err) + expect(0).assertContain(1) + } + }) + + it('sendMail', 0, async function () { + setTimeout(async ()=>{ + createAttachment() + try { + let msg: Message | MessageHeaders = { + text: '鸿蒙客户端发送的邮件内容,哈哈哈哈哈哈哈', + from: '软通测试 <479868299@qq.com>', + to: '赵先生 <479868299@qq.com>', + cc: 'else ', + bcc: 'else ', + subject: '鸿蒙客户端邮件主题', + attachment: attachment + } + const message = await globalThis.client.sendAsync(msg) + } catch (err) { + console.log("SMTP---------------->sendmail-------------->error:" + err) + expect(0).assertContain(1) + } + },300) + + }) + + }) +} \ No newline at end of file -- Gitee