Skip to content

Commit

Permalink
- Modularization and refactors in adb-actions class
Browse files Browse the repository at this point in the history
- Added tests for listed devices
  • Loading branch information
vinicioslc committed Dec 12, 2019
1 parent 0bb05c1 commit fc3f131
Show file tree
Hide file tree
Showing 7 changed files with 102 additions and 44 deletions.
27 changes: 24 additions & 3 deletions src/__tests__/adbactions.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,31 @@
import { ADBInterface, ADBResultState, ADBResult } from './../adb-actions'
import { ConsoleInterfaceMock } from '../console-interface/console-interface-mock'
// import { ConsoleInterface } from './../console-interface/console-interface'

// Mocked ConsoleInterface
const cimock = new ConsoleInterfaceMock()
const adbInterfaceInstance = new ADBInterface(cimock)

test('Test ADB Server has killed', async () => {
cimock.setConsoleOutput('')
let result = await adbInterfaceInstance.KillADBServer()

test('Kill ADB Server', async () => {
let result = await ADBInterface.KillADBServer()
let expected = await new ADBResult(
ADBResultState.Success,
'ADB Server killed'
)
expect(result).toStrictEqual(expected)

expect(JSON.stringify(result)).toBe(JSON.stringify(expected))
})

test('Test ADB Listed Devices', async () => {
const str = `* daemon not running; starting now at tcp:5037
* daemon started successfully
List of devices attached
`
cimock.setConsoleOutput(str)
let result = await adbInterfaceInstance.GetConnectedDevices()

expect(typeof result).toStrictEqual(typeof Array())
})
10 changes: 10 additions & 0 deletions src/adb-actions/adb-shell-commands.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
export default {
/**
* Kills ADB Server needing some command to restart
*/
ADB_KILL_SERVER: 'adb kill-server',
/**
* Shows an list of devices attached to adb and restart adb server if it as killed before
*/
ADB_DEVICES: 'adb devices'
}
72 changes: 45 additions & 27 deletions src/adb-actions/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,26 @@
import { execSync } from 'child_process'
import { NetHelpers } from '../ip-helpers'
import { IConsoleInterface } from '../console-interface/iconsole-interface'
import { stringLiteral } from '@babel/types'
import { log } from 'util'
import adbCommands from './adb-shell-commands'

export class ADBInterface {
static ConnectToDevice(deviceIP: string): ADBResult {
consoleInterface: IConsoleInterface
constructor(consoleInterface: IConsoleInterface) {
this.consoleInterface = consoleInterface
}
ConnectToDevice(deviceIP: string): ADBResult {
deviceIP = this.extractIPAddress(deviceIP)

var finalResult = new ADBResult(
ADBResultState.Error,
'Some error ocurred during connection'
)

const result = execSync(`adb connect ${deviceIP}:5555`)
const result = this.consoleInterface.execConsoleSync(
`adb connect ${deviceIP}:5555`
)

const output: String = result.toLocaleString()

Expand All @@ -35,13 +45,13 @@ export class ADBInterface {

return finalResult
}
static async ResetPorts(): Promise<ADBResult> {
async ResetPorts(): Promise<ADBResult> {
var finalResult = new ADBResult(
ADBResultState.Error,
'Error while reset TCPIP Ports'
)
try {
const result = execSync(`adb tcpip 5555`)
const result = this.consoleInterface.execConsoleSync(`adb tcpip 5555`)
const output = result.toLocaleString()
if (output.includes('restarting in TCP mode port: 5555')) {
finalResult = new ADBResult(
Expand All @@ -60,34 +70,36 @@ export class ADBInterface {
return finalResult
}

static getDeviceName(deviceIP: string): string {
const result = execSync(
`adb -s ${deviceIP} shell getprop ro.product.model`
).toString()
getDeviceName(deviceIP: string): string {
const result = this.consoleInterface
.execConsoleSync(`adb -s ${deviceIP} shell getprop ro.product.model`)
.toString()
return result
}

static firebaseEventsDebug({ package_name }): string {
const result = execSync(
`adb shell setprop debug.firebase.analytics.app ${package_name}`
).toString()
firebaseEventsDebug({ package_name }): string {
const result = this.consoleInterface
.execConsoleSync(
`adb shell setprop debug.firebase.analytics.app ${package_name}`
)
.toString()
return result
}

static disableFirebaseEventsDebug(): string {
const result = execSync(
`adb shell setprop debug.firebase.analytics.app .none.`
).toString()
disableFirebaseEventsDebug(): string {
const result = this.consoleInterface
.execConsoleSync(`adb shell setprop debug.firebase.analytics.app .none.`)
.toString()
return result
}

static async DisconnectFromAllDevices(): Promise<ADBResult> {
async DisconnectFromAllDevices(): Promise<ADBResult> {
var finalResult = new ADBResult(
ADBResultState.Error,
'Error while reset TCPIP Ports'
)
try {
const result = execSync(`adb disconnect`)
const result = this.consoleInterface.execConsoleSync(`adb disconnect`)
const output = result.toLocaleString()
if (output.includes('disconnected everything')) {
finalResult = new ADBResult(
Expand All @@ -104,16 +116,18 @@ export class ADBInterface {
* Returns if the ipAddress contains some ip address pattern
* @param ipAddress string to test
*/
static testIP(ipAddress: string): Boolean {
testIP(ipAddress: string): Boolean {
const regexIP = /([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1}\.[0-9]{1,3})/gim
return regexIP.test(ipAddress)
}
static async GetConnectedDevices(): Promise<Array<string>> {
async GetConnectedDevices(): Promise<Array<string>> {
var devicesArray = []
try {
const result = execSync(`adb devices`)
const result = this.consoleInterface.execConsoleSync(
adbCommands.ADB_DEVICES
)
const output = result.toLocaleString()
if (output.startsWith('List of devices attached')) {
if (output.includes('List of devices attached')) {
let ips = output.split(/[\r]|[\n]/gim)
ips = ips.filter(ip => this.testIP(ip))
ips = ips.map(ipAddress => {
Expand All @@ -133,19 +147,23 @@ export class ADBInterface {
return devicesArray
}

static extractIPAddress(ipAddress: string): string {
extractIPAddress(ipAddress: string): string {
const regexIP = /([\d]+\.[\d]+\.[\d]+\.[\d]+)/gim
var matches = regexIP.exec(ipAddress) || ['']
return matches[0]
}

static async KillADBServer(): Promise<ADBResult> {
async KillADBServer(): Promise<ADBResult> {
let returned = new ADBResult(ADBResultState.Error, 'Fail during ADB Kill')
try {
const result = execSync('adb kill-server')
returned = new ADBResult(ADBResultState.Success, 'ADB Server killed')
const result = this.consoleInterface.execConsoleSync(
adbCommands.ADB_KILL_SERVER
)
if (result.toLocaleString() === '') {
returned = new ADBResult(ADBResultState.Success, 'ADB Server killed')
}
} catch (e) {
returned.message = 'Fail during ADB Kill' + e.message
returned.message = 'Fail \n ' + e.message
}
return returned
}
Expand Down
14 changes: 9 additions & 5 deletions src/console-interface/console-interface-mock.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import { execSync } from 'child_process'
import { IConsoleInterface } from './iconsole-interface'

export class ConsoleInterface implements IConsoleInterface {
_output: Buffer
export class ConsoleInterfaceMock implements IConsoleInterface {
private _output: Buffer

setConsoleOutput(output: string): void {
this._output = Buffer.from(output, 'utf8')
setConsoleOutput(value: string): void {
if (value) {
this._output = Buffer.from(value, 'utf8')
} else {
this._output = Buffer.from('', 'utf8')
}
}

sendConsoleSync(command: string): Buffer {
execConsoleSync(command: string): Buffer {
return this._output
}
}
2 changes: 1 addition & 1 deletion src/console-interface/console-interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { execSync } from 'child_process'
import { IConsoleInterface } from './iconsole-interface'

export class ConsoleInterface implements IConsoleInterface {
sendConsoleSync(command: string): Buffer {
execConsoleSync(command: string): Buffer {
return execSync(command)
}
}
2 changes: 1 addition & 1 deletion src/console-interface/iconsole-interface.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export interface IConsoleInterface {
sendConsoleSync(command: string): Buffer
execConsoleSync(command: string): Buffer
}
19 changes: 12 additions & 7 deletions src/extension/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ import * as FirebaseExtension from '../firebase-actions'
import * as vscode from 'vscode'
import stateKeys from './global-state-keys'

import { ConsoleInterface } from './../console-interface/console-interface'
const adbInterfaceInstance = new ADBInterface(new ConsoleInterface())

export async function ResetDevicesPort() {
vscode.window.withProgress(
{
Expand All @@ -11,7 +14,7 @@ export async function ResetDevicesPort() {
},
async progress => {
progress.report({ message: 'Reseting Ports to 5555', increment: 50 })
var adbInterfaceResult = await ADBInterface.ResetPorts()
var adbInterfaceResult = await adbInterfaceInstance.ResetPorts()
progress.report({ increment: 85 })
switch (adbInterfaceResult.state) {
case ADBResultState.NoDevices:
Expand Down Expand Up @@ -57,7 +60,9 @@ function connectToAdbDevice(context: vscode.ExtensionContext, value: string) {
},
async progress => {
progress.report({ message: `Connecting to ${value}`, increment: 50 })
var adbInterfaceResult = await ADBInterface.ConnectToDevice(value)
var adbInterfaceResult = await adbInterfaceInstance.ConnectToDevice(
value
)
progress.report({ increment: 85 })
switch (adbInterfaceResult.state) {
case ADBResultState.NoDevices:
Expand Down Expand Up @@ -89,7 +94,7 @@ function connectToAdbDevice(context: vscode.ExtensionContext, value: string) {

export async function DisconnectAnyDevice() {
try {
const adbInterfaceResult = await ADBInterface.DisconnectFromAllDevices()
const adbInterfaceResult = await adbInterfaceInstance.DisconnectFromAllDevices()
adbInterfaceResult.state
switch (adbInterfaceResult.state) {
case ADBResultState.DisconnectedEverthing:
Expand All @@ -111,17 +116,17 @@ export async function DisconnectAnyDevice() {
export async function ConnectToDeviceFromList(
context: vscode.ExtensionContext
) {
const adbInterfaceResult = await ADBInterface.DisconnectFromAllDevices()
let items = ADBInterface.GetConnectedDevices()
const adbInterfaceResult = await adbInterfaceInstance.DisconnectFromAllDevices()
let items = adbInterfaceInstance.GetConnectedDevices()
let result = await vscode.window.showQuickPick(items, {
ignoreFocusOut: true,
placeHolder: 'Enter the IP address from your device to connect to him.'
})
connectToAdbDevice(context, ADBInterface.extractIPAddress(result))
connectToAdbDevice(context, adbInterfaceInstance.extractIPAddress(result))
}

export async function KillADBServer() {
const adbInterfaceResult = await ADBInterface.KillADBServer()
const adbInterfaceResult = await adbInterfaceInstance.KillADBServer()
if (adbInterfaceResult.state == ADBResultState.Success) {
vscode.window.showInformationMessage(adbInterfaceResult.message)
} else {
Expand Down

0 comments on commit fc3f131

Please sign in to comment.