Monday, October 10, 2022

Shell Script to detect events in ADB Logcat in a loop

The following shell script performs an action (tap) on the screen, then checks that a particular event does not happen on the device. It then performs another action (press back button) and then checks the target event happens only once. Then it closes a process and iterates through the same steps in a loop 50 times.

#!/bin/sh

# Clean up any reminiscent from previous run of the script
rm -rf script_logs
mkdir script_logs
for i in {1..50}
do
	echo $i
	echo "Clearing device logs"
	adb logcat -c
	echo "Starting log recording"
	adb logcat >> script_logs/script_logs$i.txt &
	logcat_pid=$!
	echo "Clicking at a point on the screen"
	adb shell input tap 200 300
	echo "Waiting for 4 seconds for event to happen and logs generated"
	sleep 4
	events=`grep "<log_pattern>" script_logs/script_logs$i.txt | wc -l`
	if [ $events == 0 ]
	then
		echo "No event found"
	else
		echo "$events were found, the test failed"
		kill -9 $logcat_pid
		exit 1
	fi
	adb shell input keyevent KEYCODE_BACK
	echo "Waiting for 4 seconds for another event"
	sleep 4
	echo "Checking how many events were sent"
	events=`grep "<log_pattern>" script_logs/script_logs$i.txt | wc -l`
	if [ $events == 1 ]
	then
		echo "One and only one event was found"
	else
		echo "$events were found, the test failed"
		kill -9 $logcat_pid
		exit 1
	fi
	echo "Killing target process"
	pid=`adb shell pidof <process_name>`
	adb shell kill -9 $pid
	echo "Stopping logcat"
	kill -9 $logcat_pid
	sleep 2
done

Pass by Pointer vs Pass by Reference in C++

Variables can be passed by pointer and by reference. Both produce the same result and have the same effect on the arguments passed in the calling function. The difference is that the pointer stores the address to a variable whereas a reference refers to an existing variable in a different name.

Reference: https://www.tutorialspoint.com/passing-by-pointer-vs-passing-by-reference-in-cplusplus

Pass by Pointer:

Code: 
#include <iostream>

using namespace std;

void swapNum(int* a, int* b) {
    int t = *a;
    *a = *b;
    *b = t;
}

int main()
{
    int i = 1;
    int j = 2;
    cout << "Before swapping " << i << " " << j << endl;
    swapNum(&i, &j);
    cout << "After swapping " << i << " " << j << endl;
    return 0;
}
Output:
Before swapping 1 2
After swapping 2 1

Pass by Reference:

Code: 
#include <iostream>

using namespace std;

void swapNum(int& a, int& b) {
    int t = a;
    a = b;
    b = t;
}

int main()
{
    int i = 1;
    int j = 2;
    cout << "Before swapping " << i << " " << j << endl;
    swapNum(i, j);
    cout << "After swapping " << i << " " << j << endl;
    return 0;
} 
Output:
Before swapping 1 2
After swapping 2 1