Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitfc8c1e1

Browse files
committed
Addandroid.py test -c and -m options
1 parentf29e177 commitfc8c1e1

File tree

4 files changed

+82
-31
lines changed

4 files changed

+82
-31
lines changed

‎Android/android.py

Lines changed: 50 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -98,10 +98,19 @@ def run(command, *, host=None, env=None, log=True, **kwargs):
9898
env.update(host_env)
9999

100100
iflog:
101-
print(">"," ".join(map(str,command)))
101+
print(">",join_command(command))
102102
returnsubprocess.run(command,env=env,**kwargs)
103103

104104

105+
# Format a command so it can be copied into a shell. Like shlex.join, but also
106+
# accepts arguments which are Paths, or a single string/Path outside of a list.
107+
defjoin_command(args):
108+
ifisinstance(args, (str,Path)):
109+
returnstr(args)
110+
else:
111+
returnshlex.join(map(str,args))
112+
113+
105114
# Format the environment so it can be pasted into a shell.
106115
defprint_env(env):
107116
forkey,valueinsorted(env.items()):
@@ -512,24 +521,42 @@ async def gradle_task(context):
512521
task_prefix="connected"
513522
env["ANDROID_SERIAL"]=context.connected
514523

524+
hidden_output= []
525+
526+
deflog(line):
527+
# Gradle may take several minutes to install SDK packages, so it's worth
528+
# showing those messages even in non-verbose mode.
529+
ifcontext.verboseorline.startswith('Preparing "Install'):
530+
sys.stdout.write(line)
531+
else:
532+
hidden_output.append(line)
533+
534+
ifcontext.command:
535+
mode="-c"
536+
module=context.command
537+
else:
538+
mode="-m"
539+
module=context.moduleor"test"
540+
515541
args= [
516542
gradlew,"--console","plain",f"{task_prefix}DebugAndroidTest",
517-
"-Pandroid.testInstrumentationRunnerArguments.pythonArgs="
518-
+shlex.join(context.args),
543+
]+ [
544+
f"-Pandroid.testInstrumentationRunnerArguments.python{name}={value}"
545+
forname,valuein [
546+
("Mode",mode),
547+
("Module",module),
548+
("Args",join_command(context.args)),
549+
]
519550
]
520-
hidden_output= []
551+
log("> "+join_command(args))
552+
521553
try:
522554
asyncwithasync_process(
523555
*args,cwd=TESTBED_DIR,env=env,
524556
stdout=subprocess.PIPE,stderr=subprocess.STDOUT,
525557
)asprocess:
526558
whileline:= (awaitprocess.stdout.readline()).decode(*DECODE_ARGS):
527-
# Gradle may take several minutes to install SDK packages, so
528-
# it's worth showing those messages even in non-verbose mode.
529-
ifcontext.verboseorline.startswith('Preparing "Install'):
530-
sys.stdout.write(line)
531-
else:
532-
hidden_output.append(line)
559+
log(line)
533560

534561
status=awaitwait_for(process.wait(),timeout=1)
535562
ifstatus==0:
@@ -701,15 +728,25 @@ def parse_args():
701728
"-v","--verbose",action="count",default=0,
702729
help="Show Gradle output, and non-Python logcat messages. "
703730
"Use twice to include high-volume messages which are rarely useful.")
731+
704732
device_group=test.add_mutually_exclusive_group(required=True)
705733
device_group.add_argument(
706734
"--connected",metavar="SERIAL",help="Run on a connected device. "
707735
"Connect it yourself, then get its serial from `adb devices`.")
708736
device_group.add_argument(
709737
"--managed",metavar="NAME",help="Run on a Gradle-managed device. "
710738
"These are defined in `managedDevices` in testbed/app/build.gradle.kts.")
739+
740+
mode_group=test.add_mutually_exclusive_group()
741+
mode_group.add_argument(
742+
"-c",dest="command",help="Execute the given Python code.")
743+
mode_group.add_argument(
744+
"-m",dest="module",help="Execute the module with the given name.")
745+
test.epilog= (
746+
"If neither -c nor -m are passed, the default is '-m test', which will "
747+
"run Python's own test suite.")
711748
test.add_argument(
712-
"args",nargs="*",help=f"Argumentsfor `python -m test`. "
749+
"args",nargs="*",help=f"Argumentsto add to sys.argv. "
713750
f"Separate them from{SCRIPT_NAME}'s own arguments with `--`.")
714751

715752
returnparser.parse_args()
@@ -756,14 +793,9 @@ def print_called_process_error(e):
756793
ifnotcontent.endswith("\n"):
757794
stream.write("\n")
758795

759-
# Format the command so it can be copied into a shell. shlex uses single
760-
# quotes, so we surround the whole command with double quotes.
761-
args_joined= (
762-
e.cmdifisinstance(e.cmd,str)
763-
else" ".join(shlex.quote(str(arg))forargine.cmd)
764-
)
796+
# shlex uses single quotes, so we surround the command with double quotes.
765797
print(
766-
f'Command "{args_joined}" returned exit status{e.returncode}'
798+
f'Command "{join_command(e.cmd)}" returned exit status{e.returncode}'
767799
)
768800

769801

‎Android/testbed/app/src/androidTest/java/org/python/testbed/PythonSuite.kt

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,11 @@ class PythonSuite {
1717
funtestPython() {
1818
val start=System.currentTimeMillis()
1919
try {
20-
valcontext=
20+
valstatus=PythonTestRunner(
2121
InstrumentationRegistry.getInstrumentation().targetContext
22-
val args=
23-
InstrumentationRegistry.getArguments().getString("pythonArgs","")
24-
val status=PythonTestRunner(context).run(args)
22+
).run(
23+
InstrumentationRegistry.getArguments()
24+
)
2525
assertEquals(0, status)
2626
}finally {
2727
// Make sure the process lives long enough for the test script to

‎Android/testbed/app/src/main/java/org/python/testbed/MainActivity.kt

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,29 @@ class MainActivity : AppCompatActivity() {
1515
overridefunonCreate(savedInstanceState:Bundle?) {
1616
super.onCreate(savedInstanceState)
1717
setContentView(R.layout.activity_main)
18-
val status=PythonTestRunner(this).run("-W -uall")
18+
val status=PythonTestRunner(this).run("-m","test","-W -uall")
1919
findViewById<TextView>(R.id.tvHello).text="Exit status$status"
2020
}
2121
}
2222

2323

2424
classPythonTestRunner(valcontext:Context) {
25-
/** @param args Extra arguments for `python -m test`.
26-
* @return The Python exit status: zero if the tests passed, nonzero if
27-
* they failed.*/
28-
funrun(args:String = "") :Int {
25+
funrun(instrumentationArgs:Bundle)=run(
26+
instrumentationArgs.getString("pythonMode")!!,
27+
instrumentationArgs.getString("pythonModule")!!,
28+
instrumentationArgs.getString("pythonArgs")!!,
29+
)
30+
31+
/** Run Python.
32+
*
33+
* @param mode Either "-c" or "-m".
34+
* @param module Python statements for "-c" mode, or a module name for
35+
* "-m" mode.
36+
* @param args Arguments to add to sys.argv. Will be parsed by `shlex.split`.
37+
* @return The Python exit status: zero on success, nonzero on failure.*/
38+
funrun(mode:String,module:String,args:String = "") :Int {
39+
Os.setenv("PYTHON_MODE", mode,true)
40+
Os.setenv("PYTHON_MODULE", module,true)
2941
Os.setenv("PYTHON_ARGS", args,true)
3042

3143
// Python needs this variable to help it find the temporary directory,
@@ -36,8 +48,9 @@ class PythonTestRunner(val context: Context) {
3648
System.loadLibrary("main_activity")
3749
redirectStdioToLogcat()
3850

39-
// The main module is in src/main/python/main.py.
40-
return runPython(pythonHome.toString(),"main")
51+
// The main module is in src/main/python. We don't simply call it
52+
// "main", as that could clash with third-party test code.
53+
return runPython(pythonHome.toString(),"android_testbed_main")
4154
}
4255

4356
privatefunextractAssets() :File {

‎Android/testbed/app/src/main/python/main.pyrenamed to‎Android/testbed/app/src/main/python/android_testbed_main.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,13 @@
2626
# test_signals in test_threadsignals.py.
2727
signal.pthread_sigmask(signal.SIG_UNBLOCK, [signal.SIGUSR1])
2828

29+
mode=os.environ["PYTHON_MODE"]
30+
module=os.environ["PYTHON_MODULE"]
2931
sys.argv[1:]=shlex.split(os.environ["PYTHON_ARGS"])
3032

31-
# The test module will call sys.exit to indicate whether the tests passed.
32-
runpy.run_module("test")
33+
ifmode=="-c":
34+
exec(module, {})
35+
elifmode=="-m":
36+
runpy.run_module(module,run_name="__main__",alter_sys=True)
37+
else:
38+
raiseValueError(f"unknown mode:{mode}")

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp