1 /*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License. You may obtain a copy of
6 * the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations under
14 * the License.
15 */
16
17 #include <stdlib.h>
18 #include <stdio.h>
19
20 #include "Log.h"
21 #include "StringUtil.h"
22
23 #include "SimpleScriptExec.h"
24
25 const char* SimpleScriptExec::PYTHON_PATH = "/usr/bin/python";
26 const char* PASS_MAGIC_WORD = "___CTS_AUDIO_PASS___";
27
checkPythonEnv()28 bool SimpleScriptExec::checkPythonEnv()
29 {
30 android::String8 script("test_description/conf/check_conf.py");
31 android::String8 param;
32 android::String8 result;
33 if (!runScript(script, param, result)) {
34 return false;
35 }
36
37 android::String8 rePattern;
38 return checkIfPassed(result, rePattern);
39 }
40
checkIfPassed(const android::String8 & str,const android::String8 & reMatch,int nmatch,regmatch_t pmatch[])41 bool SimpleScriptExec::checkIfPassed(const android::String8& str, const android::String8& reMatch,
42 int nmatch, regmatch_t pmatch[])
43 {
44 android::String8 match;
45 match.append(PASS_MAGIC_WORD);
46 match.append(reMatch);
47 LOGV("re match %s", match.string());
48 regex_t re;
49 int cflags = REG_EXTENDED;
50 if (nmatch == 0) {
51 cflags |= REG_NOSUB;
52 }
53 if (regcomp(&re, match.string(), cflags) != 0) {
54 LOGE("regcomp failed");
55 return false;
56 }
57 bool result = false;
58 if (regexec(&re, str.string(), nmatch, pmatch, 0) == 0) {
59 // match found. passed
60 result = true;
61 }
62 regfree(&re);
63 return result;
64 }
65
runScript(const android::String8 & script,const android::String8 & param,android::String8 & result)66 bool SimpleScriptExec::runScript(const android::String8& script, const android::String8& param,
67 android::String8& result)
68 {
69 FILE *fpipe;
70 android::String8 command;
71 command.appendFormat("%s %s %s", PYTHON_PATH, script.string(), param.string());
72 const int READ_SIZE = 1024;
73 char buffer[READ_SIZE];
74 size_t len = 0;
75
76 if ( !(fpipe = (FILE*)popen(command.string(),"r")) ) {
77 LOGE("cannot execute python");
78 return false;
79 }
80 result.clear();
81 while((len = fread(buffer, 1, READ_SIZE, fpipe)) > 0) {
82 result.append(buffer, len);
83 }
84 pclose(fpipe);
85
86 return true;
87 }
88
89
90
91