Datasets:
Upload folder using huggingface_hub (part 4)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- android/secuso-privacy-friendly-2048/LICENSEAdded+676
- android/secuso-privacy-friendly-2048/instance.jsonAdded+10
- android/secuso-privacy-friendly-2048/reference/launch.shAdded+9
- android/secuso-privacy-friendly-2048/tests/android_computation_eval.jsonAdded+232
- android/secuso-privacy-friendly-2048/tests/android_interaction_eval.jsonAdded+274
- android/secuso-privacy-friendly-2048/tests/android_navigation_eval.jsonAdded+283
- android/secuso-privacy-friendly-2048/tests/android_states_eval.jsonAdded+229
- android/secuso-privacy-friendly-2048/tests/android_structure_eval.jsonAdded+202
- android/secuso-privacy-friendly-2048/tests/android_testgen_kit.pyAdded+1910
- android/secuso-privacy-friendly-2048/tests/android_text_eval.jsonAdded+196
- android/secuso-privacy-friendly-2048/tests/conftest.pyAdded+1
- android/secuso-privacy-friendly-2048/tests/requirements.txtAdded+2
- android/secuso-privacy-friendly-2048/tests/test_android_computation.pyAdded+1075
- android/secuso-privacy-friendly-2048/tests/test_android_interaction.pyAdded+1012
- android/secuso-privacy-friendly-2048/tests/test_android_navigation.pyAdded+599
- android/secuso-privacy-friendly-2048/tests/test_android_states.pyAdded+984
- android/secuso-privacy-friendly-2048/tests/test_android_structure.pyAdded+403
- android/secuso-privacy-friendly-2048/tests/test_android_text.pyAdded+697
- android/secuso-privacy-friendly-2048/tests/test_manifest.jsonAdded+857
- android/secuso-privacy-friendly-2048/vlm_assertions.jsonAdded+743
- android/secuso-privacy-friendly-pedometer/LICENSEAdded+675
- android/secuso-privacy-friendly-pedometer/instance.jsonAdded+10
- android/secuso-privacy-friendly-pedometer/reference/launch.shAdded+9
- android/secuso-privacy-friendly-pedometer/tests/android_computation_eval.jsonAdded+215
- android/secuso-privacy-friendly-pedometer/tests/android_interaction_eval.jsonAdded+192
- android/secuso-privacy-friendly-pedometer/tests/android_navigation_eval.jsonAdded+209
- android/secuso-privacy-friendly-pedometer/tests/android_states_eval.jsonAdded+266
- android/secuso-privacy-friendly-pedometer/tests/android_structure_eval.jsonAdded+229
- android/secuso-privacy-friendly-pedometer/tests/android_testgen_kit.pyAdded+1910
- android/secuso-privacy-friendly-pedometer/tests/android_text_eval.jsonAdded+196
- android/secuso-privacy-friendly-pedometer/tests/conftest.pyAdded+1
- android/secuso-privacy-friendly-pedometer/tests/requirements.txtAdded+2
- android/secuso-privacy-friendly-pedometer/tests/test_android_computation.pyAdded+498
- android/secuso-privacy-friendly-pedometer/tests/test_android_interaction.pyAdded+768
- android/secuso-privacy-friendly-pedometer/tests/test_android_navigation.pyAdded+401
- android/secuso-privacy-friendly-pedometer/tests/test_android_states.pyAdded+1145
- android/secuso-privacy-friendly-pedometer/tests/test_android_structure.pyAdded+495
- android/secuso-privacy-friendly-pedometer/tests/test_android_text.pyAdded+618
- android/secuso-privacy-friendly-pedometer/tests/test_manifest.jsonAdded+792
- android/secuso-privacy-friendly-pedometer/vlm_assertions.jsonAdded+723
- android/secuso-privacy-friendly-sudoku/LICENSE.mdAdded+674
- android/secuso-privacy-friendly-sudoku/instance.jsonAdded+10
- android/secuso-privacy-friendly-sudoku/reference/launch.shAdded+9
- android/secuso-privacy-friendly-sudoku/tests/android_computation_eval.jsonAdded+222
- android/secuso-privacy-friendly-sudoku/tests/android_interaction_eval.jsonAdded+195
- android/secuso-privacy-friendly-sudoku/tests/android_navigation_eval.jsonAdded+227
- android/secuso-privacy-friendly-sudoku/tests/android_states_eval.jsonAdded+242
- android/secuso-privacy-friendly-sudoku/tests/android_structure_eval.jsonAdded+173
- android/secuso-privacy-friendly-sudoku/tests/android_testgen_kit.pyAdded+1910
- android/secuso-privacy-friendly-sudoku/tests/android_text_eval.jsonAdded+293
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license forsoftware and other kinds of works.
The licenses for most software and other practical works are designedto take away your freedom to share and change the works. By contrast,the GNU General Public License is intended to guarantee your freedom toshare and change all versions of a program--to make sure it remains freesoftware for all its users. We, the Free Software Foundation, use theGNU General Public License for most of our software; it applies also toany other work released this way by its authors. You can apply it toyour programs, too.
When we speak of free software, we are referring to freedom, notprice. Our General Public Licenses are designed to make sure that youhave the freedom to distribute copies of free software (and charge forthem if you wish), that you receive source code or can get it if youwant it, that you can change the software or use pieces of it in newfree programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying youthese rights or asking you to surrender the rights. Therefore, you havecertain responsibilities if you distribute copies of the software, or ifyou modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whethergratis or for a fee, you must pass on to the recipients the samefreedoms that you received. You must make sure that they, too, receiveor can get the source code. And you must show them these terms so theyknow their rights.
Developers that use the GNU GPL protect your rights with two steps:(1) assert copyright on the software, and (2) offer you this Licensegiving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explainsthat there is no warranty for this free software. For both users' andauthors' sake, the GPL requires that modified versions be marked aschanged, so that their problems will not be attributed erroneously toauthors of previous versions.
Some devices are designed to deny users access to install or runmodified versions of the software inside them, although the manufacturercan do so. This is fundamentally incompatible with the aim ofprotecting users' freedom to change the software. The systematicpattern of such abuse occurs in the area of products for individuals touse, which is precisely where it is most unacceptable. Therefore, wehave designed this version of the GPL to prohibit the practice for thoseproducts. If such problems arise substantially in other domains, westand ready to extend this provision to those domains in future versionsof the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.States should not allow patents to restrict development and use ofsoftware on general-purpose computers, but in those that do, we wish toavoid the special danger that patents applied to a free program couldmake it effectively proprietary. To prevent this, the GPL assures thatpatents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution andmodification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds ofworks, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under thisLicense. Each licensee is addressed as "you". "Licensees" and"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the workin a fashion requiring copyright permission, other than the making of anexact copy. The resulting work is called a "modified version" of theearlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work basedon the Program.
To "propagate" a work means to do anything with it that, withoutpermission, would make you directly or secondarily liable forinfringement under applicable copyright law, except executing it on acomputer or modifying a private copy. Propagation includes copying,distribution (with or without modification), making available to thepublic, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables otherparties to make or receive copies. Mere interaction with a user througha computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"to the extent that it includes a convenient and prominently visiblefeature that (1) displays an appropriate copyright notice, and (2)tells the user that there is no warranty for the work (except to theextent that warranties are provided), that licensees may convey thework under this License, and how to view a copy of this License. Ifthe interface presents a list of user commands or options, such as amenu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the workfor making modifications to it. "Object code" means any non-sourceform of a work.
A "Standard Interface" means an interface that either is an officialstandard defined by a recognized standards body, or, in the case ofinterfaces specified for a particular programming language, one thatis widely used among developers working in that language.
The "System Libraries" of an executable work include anything, otherthan the work as a whole, that (a) is included in the normal form ofpackaging a Major Component, but which is not part of that MajorComponent, and (b) serves only to enable use of the work with thatMajor Component, or to implement a Standard Interface for which animplementation is available to the public in source code form. A"Major Component", in this context, means a major essential component(kernel, window system, and so on) of the specific operating system(if any) on which the executable work runs, or a compiler used toproduce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means allthe source code needed to generate, install, and (for an executablework) run the object code and to modify the work, including scripts tocontrol those activities. However, it does not include the work'sSystem Libraries, or general-purpose tools or generally available freeprograms which are used unmodified in performing those activities butwhich are not part of the work. For example, Corresponding Sourceincludes interface definition files associated with source files forthe work, and the source code for shared libraries and dynamicallylinked subprograms that the work is specifically designed to require,such as by intimate data communication or control flow between thosesubprograms and other parts of the work.
The Corresponding Source need not include anything that userscan regenerate automatically from other parts of the CorrespondingSource.
The Corresponding Source for a work in source code form is thatsame work.
2. Basic Permissions.
All rights granted under this License are granted for the term ofcopyright on the Program, and are irrevocable provided the statedconditions are met. This License explicitly affirms your unlimitedpermission to run the unmodified Program. The output from running acovered work is covered by this License only if the output, given itscontent, constitutes a covered work. This License acknowledges yourrights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do notconvey, without conditions so long as your license otherwise remainsin force. You may convey covered works to others for the sole purposeof having them make modifications exclusively for you, or provide youwith facilities for running those works, provided that you comply withthe terms of this License in conveying all material for which you donot control copyright. Those thus making or running the covered worksfor you must do so exclusively on your behalf, under your directionand control, on terms that prohibit them from making any copies ofyour copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely underthe conditions stated below. Sublicensing is not allowed; section 10makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technologicalmeasure under any applicable law fulfilling obligations under article11 of the WIPO copyright treaty adopted on 20 December 1996, orsimilar laws prohibiting or restricting circumvention of suchmeasures.
When you convey a covered work, you waive any legal power to forbidcircumvention of technological measures to the extent such circumventionis effected by exercising rights under this License with respect tothe covered work, and you disclaim any intention to limit operation ormodification of the work as a means of enforcing, against the work'susers, your or third parties' legal rights to forbid circumvention oftechnological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as youreceive it, in any medium, provided that you conspicuously andappropriately publish on each copy an appropriate copyright notice;keep intact all notices stating that this License and anynon-permissive terms added in accord with section 7 apply to the code;keep intact all notices of the absence of any warranty; and give allrecipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications toproduce it from the Program, in the form of source code under theterms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independentworks, which are not by their nature extensions of the covered work,and which are not combined with it such as to form a larger program,in or on a volume of a storage or distribution medium, is called an"aggregate" if the compilation and its resulting copyright are notused to limit the access or legal rights of the compilation's usersbeyond what the individual works permit. Inclusion of a covered workin an aggregate does not cause this License to apply to the otherparts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the termsof sections 4 and 5, provided that you also convey themachine-readable Corresponding Source under the terms of this License,in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excludedfrom the Corresponding Source as a System Library, need not beincluded in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means anytangible personal property which is normally used for personal, family,or household purposes, or (2) anything designed or sold for incorporationinto a dwelling. In determining whether a product is a consumer product,doubtful cases shall be resolved in favor of coverage. For a particularproduct received by a particular user, "normally used" refers to atypical or common use of that class of product, regardless of the statusof the particular user or of the way in which the particular useractually uses, or expects or is expected to use, the product. A productis a consumer product regardless of whether the product has substantialcommercial, industrial or non-consumer uses, unless such uses representthe only significant mode of use of the product.
"Installation Information" for a User Product means any methods,procedures, authorization keys, or other information required to installand execute modified versions of a covered work in that User Product froma modified version of its Corresponding Source. The information mustsuffice to ensure that the continued functioning of the modified objectcode is in no case prevented or interfered with solely becausemodification has been made.
If you convey an object code work under this section in, or with, orspecifically for use in, a User Product, and the conveying occurs aspart of a transaction in which the right of possession and use of theUser Product is transferred to the recipient in perpetuity or for afixed term (regardless of how the transaction is characterized), theCorresponding Source conveyed under this section must be accompaniedby the Installation Information. But this requirement does not applyif neither you nor any third party retains the ability to installmodified object code on the User Product (for example, the work hasbeen installed in ROM).
The requirement to provide Installation Information does not include arequirement to continue to provide support service, warranty, or updatesfor a work that has been modified or installed by the recipient, or forthe User Product in which it has been modified or installed. Access to anetwork may be denied when the modification itself materially andadversely affects the operation of the network or violates the rules andprotocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,in accord with this section must be in a format that is publiclydocumented (and with an implementation available to the public insource code form), and must require no special password or key forunpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of thisLicense by making exceptions from one or more of its conditions.Additional permissions that are applicable to the entire Program shallbe treated as though they were included in this License, to the extentthat they are valid under applicable law. If additional permissionsapply only to part of the Program, that part may be used separatelyunder those permissions, but the entire Program remains governed bythis License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your optionremove any additional permissions from that copy, or from any part ofit. (Additional permissions may be written to require their ownremoval in certain cases when you modify the work.) You may placeadditional permissions on material, added by you to a covered work,for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material youadd to a covered work, you may (if authorized by the copyright holders ofthat material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "furtherrestrictions" within the meaning of section 10. If the Program as youreceived it, or any part of it, contains a notice stating that it isgoverned by this License along with a term that is a furtherrestriction, you may remove that term. If a license document containsa further restriction but permits relicensing or conveying under thisLicense, you may add to a covered work material governed by the termsof that license document, provided that the further restriction doesnot survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, youmust place, in the relevant source files, a statement of theadditional terms that apply to those files, or a notice indicatingwhere to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in theform of a separately written license, or stated as exceptions;the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expresslyprovided under this License. Any attempt otherwise to propagate ormodify it is void, and will automatically terminate your rights underthis License (including any patent licenses granted under the thirdparagraph of section 11).
However, if you cease all violation of this License, then yourlicense from a particular copyright holder is reinstated (a)provisionally, unless and until the copyright holder explicitly andfinally terminates your license, and (b) permanently, if the copyrightholder fails to notify you of the violation by some reasonable meansprior to 60 days after the cessation.
Moreover, your license from a particular copyright holder isreinstated permanently if the copyright holder notifies you of theviolation by some reasonable means, this is the first time you havereceived notice of violation of this License (for any work) from thatcopyright holder, and you cure the violation prior to 30 days afteryour receipt of the notice.
Termination of your rights under this section does not terminate thelicenses of parties who have received copies or rights from you underthis License. If your rights have been terminated and not permanentlyreinstated, you do not qualify to receive new licenses for the samematerial under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive orrun a copy of the Program. Ancillary propagation of a covered workoccurring solely as a consequence of using peer-to-peer transmissionto receive a copy likewise does not require acceptance. However,nothing other than this License grants you permission to propagate ormodify any covered work. These actions infringe copyright if you donot accept this License. Therefore, by modifying or propagating acovered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automaticallyreceives a license from the original licensors, to run, modify andpropagate that work, subject to this License. You are not responsiblefor enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of anorganization, or substantially all assets of one, or subdividing anorganization, or merging organizations. If propagation of a coveredwork results from an entity transaction, each party to thattransaction who receives a copy of the work also receives whateverlicenses to the work the party's predecessor in interest had or couldgive under the previous paragraph, plus a right to possession of theCorresponding Source of the work from the predecessor in interest, ifthe predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of therights granted or affirmed under this License. For example, you maynot impose a license fee, royalty, or other charge for exercise ofrights granted under this License, and you may not initiate litigation(including a cross-claim or counterclaim in a lawsuit) alleging thatany patent claim is infringed by making, using, selling, offering forsale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under thisLicense of the Program or a work on which the Program is based. Thework thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claimsowned or controlled by the contributor, whether already acquired orhereafter acquired, that would be infringed by some manner, permittedby this License, of making, using, or selling its contributor version,but do not include claims that would be infringed only as aconsequence of further modification of the contributor version. Forpurposes of this definition, "control" includes the right to grantpatent sublicenses in a manner consistent with the requirements ofthis License.
Each contributor grants you a non-exclusive, worldwide, royalty-freepatent license under the contributor's essential patent claims, tomake, use, sell, offer for sale, import and otherwise run, modify andpropagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any expressagreement or commitment, however denominated, not to enforce a patent(such as an express permission to practice a patent or covenant not tosue for patent infringement). To "grant" such a patent license to aparty means to make such an agreement or commitment not to enforce apatent against the party.
If you convey a covered work, knowingly relying on a patent license,and the Corresponding Source of the work is not available for anyoneto copy, free of charge and under the terms of this License, through apublicly available network server or other readily accessible means,then you must either (1) cause the Corresponding Source to be soavailable, or (2) arrange to deprive yourself of the benefit of thepatent license for this particular work, or (3) arrange, in a mannerconsistent with the requirements of this License, to extend the patentlicense to downstream recipients. "Knowingly relying" means you haveactual knowledge that, but for the patent license, your conveying thecovered work in a country, or your recipient's use of the covered workin a country, would infringe one or more identifiable patents in thatcountry that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction orarrangement, you convey, or propagate by procuring conveyance of, acovered work, and grant a patent license to some of the partiesreceiving the covered work authorizing them to use, propagate, modifyor convey a specific copy of the covered work, then the patent licenseyou grant is automatically extended to all recipients of the coveredwork and works based on it.
A patent license is "discriminatory" if it does not include withinthe scope of its coverage, prohibits the exercise of, or isconditioned on the non-exercise of one or more of the rights that arespecifically granted under this License. You may not convey a coveredwork if you are a party to an arrangement with a third party that isin the business of distributing software, under which you make paymentto the third party based on the extent of your activity of conveyingthe work, and under which the third party grants, to any of theparties who would receive the covered work from you, a discriminatorypatent license (a) in connection with copies of the covered workconveyed by you (or copies made from those copies), or (b) primarilyfor and in connection with specific products or compilations thatcontain the covered work, unless you entered into that arrangement,or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limitingany implied license or other defenses to infringement that mayotherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement orotherwise) that contradict the conditions of this License, they do notexcuse you from the conditions of this License. If you cannot convey acovered work so as to satisfy simultaneously your obligations under thisLicense and any other pertinent obligations, then as a consequence you maynot convey it at all. For example, if you agree to terms that obligate youto collect a royalty for further conveying from those to whom you conveythe Program, the only way you could satisfy both those terms and thisLicense would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you havepermission to link or combine any covered work with a work licensedunder version 3 of the GNU Affero General Public License into a singlecombined work, and to convey the resulting work. The terms of thisLicense will continue to apply to the part which is the covered work,but the special requirements of the GNU Affero General Public License,section 13, concerning interaction through a network will apply to thecombination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions ofthe GNU General Public License from time to time. Such new versions willbe similar in spirit to the present version, but may differ in detail toaddress new problems or concerns.
Each version is given a distinguishing version number. If theProgram specifies that a certain numbered version of the GNU GeneralPublic License "or any later version" applies to it, you have theoption of following the terms and conditions either of that numberedversion or of any later version published by the Free SoftwareFoundation. If the Program does not specify a version number of theGNU General Public License, you may choose any version ever publishedby the Free Software Foundation.
If the Program specifies that a proxy can decide which futureversions of the GNU General Public License can be used, that proxy'spublic statement of acceptance of a version permanently authorizes youto choose that version for the Program.
Later license versions may give you additional or differentpermissions. However, no additional obligations are imposed on anyauthor or copyright holder as a result of your choosing to follow alater version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BYAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHTHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTYOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULARPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAMIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OFALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITINGWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYSTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANYGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THEUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OFDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRDPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OFSUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability providedabove cannot be given local legal effect according to their terms,reviewing courts shall apply local law that most closely approximatesan absolute waiver of all civil liability in connection with theProgram, unless a warranty or assumption of liability accompanies acopy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatestpossible use to the public, the best way to achieve this is to make itfree software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safestto attach them to the start of each source file to most effectivelystate the exclusion of warranty; and each file should have at leastthe "copyright" line and a pointer to where the full notice is found.
Privacy Friendly Example App. The Android application demonstrate the design of a Privacy Friendly App. Copyright (C) 2016-2018 Karola Marky
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a shortnotice like this when it starts in an interactive mode:
Privacy Friendly Apps Copyright (C) 2016-2018 Karola Marky This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriateparts of the General Public License. Of course, your program's commandsmight be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,if any, to sign a "copyright disclaimer" for the program, if necessary.For more information on this, and how to apply and follow the GNU GPL, see<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your programinto proprietary programs. If your program is a subroutine library, youmay consider it more useful to permit linking proprietary applications withthe library. If this is what you want to do, use the GNU Lesser GeneralPublic License instead of this License. But first, please read<http://www.gnu.org/philosophy/why-not-lgpl.html>.
12345678910{ "schema_version": 1, "instance_id": "android/secuso-privacy-friendly-2048", "platform": "android", "repo": "https://github.com/SecUSo/privacy-friendly-2048", "commit": "4ee3cf356376c1f8905f81a02ffc9f37b3db6c96", "patches": [], "package": "org.secuso.privacyfriendly2048", "license": null}123456789#!/usr/bin/env bash# TEMPLATE (rb_unify) — review before use.set -euo pipefail: "${RB_PACKAGE:?must be exported by the runner from instance.json}"D="$(cd "$(dirname "$0")" && pwd)"; SER="${DEVICE_SERIAL:-emulator-5554}"APK="$(find "$D" -name '*.apk' | head -1)"[ -n "$APK" ] || { echo "ERROR: no apk found; extract reference.tar.gz first" >&2; exit 1; }adb -s "$SER" install -r -g "$APK"adb -s "$SER" shell monkey -p "$RB_PACKAGE" -c android.intent.category.LAUNCHER 1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232{ "module": "computation", "total": 22, "passed": 22, "failed": 0, "pass_rate": 1.0, "rule": { "total": 20, "passed": 20, "failed": 0, "pass_rate": 1.0 }, "vlm": { "total": 2, "passed": 2, "failed": 0, "pass_rate": 1.0 }, "vlm_ratio": 0.1, "audit": { "kit_api_version": 1, "existence": 0, "liveness": 0, "interactive": 22, "depth_ge1": 22, "depth_ge2": 0, "value": 22, "vlm_fine": 2 }, "results": [ { "test": "computation_fresh_seed_two_tiles", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "fresh game: exactly 2 numeric tiles and points == 0" }, { "test": "computation_effective_move_sum_delta", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "each effective move increases the tile sum by exactly 2 or 4" }, { "test": "computation_slide_adds_one_tile", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "a no-merge move raises tile count by 1, spawning a 2 or a 4" }, { "test": "computation_merge_scores_points", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "a merge adds a positive even points delta; tile sum grows by 2/4" }, { "test": "computation_merge_pair_value", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "single-pair merge scores exactly twice the merged tile value" }, { "test": "computation_blocked_move_no_change", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "a blocked move leaves the tile multiset and points identical" }, { "test": "computation_blocked_move_no_new_tile", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "a blocked move leaves the tile count unchanged (no new tile)" }, { "test": "computation_record_is_max", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "record == points at the moment points first exceed the old record" }, { "test": "computation_record_monotonic", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "record is non-decreasing across a sequence of moves" }, { "test": "computation_restart_resets", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "restart -> points == 0 and exactly 2 tiles" }, { "test": "computation_restart_two_tiles_vlm", "passed": true, "message": "VLM: Q='Does the game grid show exactly two numbered tiles, with every other cell empty?' A=YES expect=YES", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "VLM YES: Does the game grid show exactly two numbered tiles, with every other cell empty?", "tag": "position" }, { "test": "computation_undo_restores_points", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "points return to the pre-move value after undo" }, { "test": "computation_undo_restores_tile_count", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "tile count returns to the pre-move count after undo" }, { "test": "computation_undo_once", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "one undo restores the pre-move points; a second cannot lower them" }, { "test": "computation_points_accumulate", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "final score equals the running sum of non-negative per-move deltas" }, { "test": "computation_merge_collapses_pair", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "on a scoring (merge) move the tile count does not increase" }, { "test": "computation_two_slides_add_two", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "each of two no-merge moves raises the tile count by exactly one" }, { "test": "computation_restart_then_move", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "after restart the seed is 2 tiles and a move grows it past 2" }, { "test": "computation_undo_then_replay", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "after undo restores points, further moves raise them again" }, { "test": "computation_5x5_larger_grid", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "5x5 board has more cells than 4x4; both seed exactly 2 tiles" }, { "test": "computation_5x5_grid_vlm", "passed": true, "message": "VLM: Q='Is the game board a square grid with five columns and five rows of cells (a 5 by 5 grid)?' A=YES expect=YES", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "VLM YES: Is the game board a square grid with five columns and five rows of cells (a 5 by 5 grid)?", "tag": "size" }, { "test": "computation_sum_growth_bounded", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "every per-move tile-sum delta is 0 (blocked) or 2/4 (one spawn)" } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274{ "module": "interaction", "total": 26, "passed": 26, "failed": 0, "pass_rate": 1.0, "rule": { "total": 18, "passed": 18, "failed": 0, "pass_rate": 1.0 }, "vlm": { "total": 8, "passed": 8, "failed": 0, "pass_rate": 1.0 }, "vlm_ratio": 0.4444, "audit": { "kit_api_version": 1, "existence": 0, "liveness": 0, "interactive": 26, "depth_ge1": 26, "depth_ge2": 15, "value": 0, "vlm_fine": 5 }, "results": [ { "test": "interaction_persist_after_kill", "passed": true, "message": "", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "continue restores points=4 tiles=[2, 2, 4] after process death" }, { "test": "interaction_persist_board_restored_vlm", "passed": true, "message": "VLM: Q='Does the game board show multiple numbered tiles (a populated grid), i.e. it is NOT an empty grid?' A=YES expect=YES", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Does the game board show multiple numbered tiles (a populated grid), i.e. it is NOT an empty grid?", "tag": "content" }, { "test": "interaction_kill_without_back_not_saved", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "continue DISABLED after play then kill-without-back" }, { "test": "interaction_continue_enable_after_play_back", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "continue enabled=true after play then back" }, { "test": "interaction_undo_reverts_points", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "points return to 0 after undo" }, { "test": "interaction_undo_board_reverted_vlm", "passed": true, "message": "VLM: Q='Does the game board still show numbered tiles on the grid after the undo (a non-empty board)?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Does the game board still show numbered tiles on the grid after the undo (a non-empty board)?", "tag": "content" }, { "test": "interaction_undo_icon_visible_vlm", "passed": true, "message": "VLM: Q='Is there a curved counter-clockwise undo arrow icon visible near the top of the screen?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Is there a curved counter-clockwise undo arrow icon visible near the top of the screen?", "tag": "shape" }, { "test": "interaction_undo_once_per_move", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "undoButton absent -> present after move -> absent after undo" }, { "test": "interaction_restart_reseeds_board", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "points=0 and exactly 2 tiles after restart" }, { "test": "interaction_restart_two_tiles_vlm", "passed": true, "message": "VLM: Q='Does the game board show exactly two numbered tiles, with all the other grid cells empty?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Does the game board show exactly two numbered tiles, with all the other grid cells empty?", "tag": "position" }, { "test": "interaction_restart_then_playable", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "a move after restart adds a tile (2->3) and undo returns" }, { "test": "interaction_merged_tiles_colored_vlm", "passed": true, "message": "VLM: Q='Do the numbered tiles on the board have colored (non-white) backgrounds?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Do the numbered tiles on the board have colored (non-white) backgrounds?", "tag": "color" }, { "test": "interaction_accumulated_score_persists", "passed": true, "message": "", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "points=44 (>0) survive back+kill+continue" }, { "test": "interaction_stats_moves_increment", "passed": true, "message": "", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "moves_All1>=1 and moves_L1>=1 after 4x4 play" }, { "test": "interaction_stats_nonzero_vlm", "passed": true, "message": "VLM: Q='Does this statistics screen display numeric values in its rows (numbers other than only zeros)?' A=YES expect=YES", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Does this statistics screen display numeric values in its rows (numbers other than only zeros)?", "tag": "content" }, { "test": "interaction_stats_highest_number", "passed": true, "message": "", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "highest_number1>=4 (board reached 4)" }, { "test": "interaction_stats_highest_score", "passed": true, "message": "", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "highest_score1 == 20" }, { "test": "interaction_stats_mode_isolation", "passed": true, "message": "", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "4x4 moves_All1>0 and 5x5 moves_All2==0" }, { "test": "interaction_stats_undo_counter", "passed": true, "message": "", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "undo_number1 >= 1 after using undo" }, { "test": "interaction_5x5_larger_grid_vlm", "passed": true, "message": "VLM: Q='Is the game board a large square grid with five columns and five rows of cells?' A=YES expect=YES", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Is the game board a large square grid with five columns and five rows of cells?", "tag": "size" }, { "test": "interaction_continue_mode_correct", "passed": true, "message": "", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "5x5 continue restores points=44 tiles=[2, 2, 2, 8, 8, 8]" }, { "test": "interaction_two_saved_games", "passed": true, "message": "", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "both modes enabled; 4x4 continue restores points=48" }, { "test": "interaction_continue_repeatable", "passed": true, "message": "", "depth": 3, "jump_kind": "transition", "tier": 2, "expect": "points=24 preserved across resume->back->resume" }, { "test": "interaction_restart_then_persist", "passed": true, "message": "", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "continue restores post-restart points=0 tiles=[2, 2, 2, 2, 4]" }, { "test": "interaction_stats_overflow_menu", "passed": true, "message": "", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "overflow opens revealing a menu item over the Stats surface" }, { "test": "interaction_restart_icon_visible_vlm", "passed": true, "message": "VLM: Q='Is there a circular refresh / restart arrow icon visible near the top-right of the game screen?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Is there a circular refresh / restart arrow icon visible near the top-right of the game screen?", "tag": "shape" } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283{ "module": "navigation", "total": 27, "passed": 27, "failed": 0, "pass_rate": 1.0, "rule": { "total": 19, "passed": 19, "failed": 0, "pass_rate": 1.0 }, "vlm": { "total": 8, "passed": 8, "failed": 0, "pass_rate": 1.0 }, "vlm_ratio": 0.4211, "audit": { "kit_api_version": 1, "existence": 0, "liveness": 0, "interactive": 27, "depth_ge1": 23, "depth_ge2": 5, "value": 0, "vlm_fine": 6 }, "results": [ { "test": "nav_reach_statistics", "passed": true, "message": "", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "StatsActivity: 'Highest Number' appears; Main 'START NEW GAME' gone" }, { "test": "nav_reach_statistics_vlm", "passed": true, "message": "VLM: Q='Is a horizontal row of tab labels shown across the top of the screen, with rows of statistics listed below it?' A=YES expect=YES", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "VLM YES: Is a horizontal row of tab labels shown across the top of the screen, with rows of statistics listed below it?", "tag": "position" }, { "test": "nav_reach_settings", "passed": true, "message": "", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "SettingsActivity: 'Select theme' appears; Main 'START NEW GAME' gone" }, { "test": "nav_reach_settings_vlm", "passed": true, "message": "VLM: Q='Is this a settings screen showing a vertical list of preference rows, each with a title line?' A=YES expect=YES", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "VLM YES: Is this a settings screen showing a vertical list of preference rows, each with a title line?", "tag": "position" }, { "test": "nav_reach_help", "passed": true, "message": "", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "HelpActivity: FAQ row 'What is the goal of this game?' appears; Main 'START NEW GAME' gone" }, { "test": "nav_reach_help_vlm", "passed": true, "message": "VLM: Q='Is the screen a vertical list of question rows, one per line, like an FAQ / help list?' A=YES expect=YES", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "VLM YES: Is the screen a vertical list of question rows, one per line, like an FAQ / help list?", "tag": "layout" }, { "test": "nav_reach_about", "passed": true, "message": "", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "AboutActivity: 'Version:' label appears; Main 'START NEW GAME' gone" }, { "test": "nav_reach_about_vlm", "passed": true, "message": "VLM: Q='Does this screen show app information text such as a version number, author names, and a license paragraph?' A=YES expect=YES", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "VLM YES: Does this screen show app information text such as a version number, author names, and a license paragraph?", "tag": "content" }, { "test": "nav_reach_tutorial", "passed": true, "message": "", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "TutorialActivity: slide title 'Welcome!' appears; Main 'START NEW GAME' gone" }, { "test": "nav_reach_tutorial_vlm", "passed": true, "message": "VLM: Q='Are there SKIP and NEXT buttons at the bottom of the screen below an introduction slide?' A=YES expect=YES", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "VLM YES: Are there SKIP and NEXT buttons at the bottom of the screen below an introduction slide?", "tag": "position" }, { "test": "nav_reach_game_new", "passed": true, "message": "", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "GameActivity: restartButton appears; Main 'START NEW GAME' gone" }, { "test": "nav_reach_game_new_vlm", "passed": true, "message": "VLM: Q='Is there a left-pointing back/up arrow at the top-left of the screen, above a grid of square game tiles?' A=YES expect=YES", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "VLM YES: Is there a left-pointing back/up arrow at the top-left of the screen, above a grid of square game tiles?", "tag": "position" }, { "test": "nav_back_game_to_main", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "MainActivity restored: 'START NEW GAME' reappears, restartButton disappears" }, { "test": "nav_back_stats_to_main", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "MainActivity restored: 'START NEW GAME' reappears, 'Highest Number' disappears" }, { "test": "nav_back_settings_to_main", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "MainActivity restored: 'START NEW GAME' reappears, 'Select theme' disappears" }, { "test": "nav_back_about_to_main", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "MainActivity restored: 'START NEW GAME' reappears, 'Version:' disappears" }, { "test": "nav_pager_next_4to5", "passed": true, "message": "", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "mode label '5x5' appears and '4x4' disappears after btn_next" }, { "test": "nav_pager_prev_5to4", "passed": true, "message": "", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "mode label '4x4' appears and '5x5' disappears after btn_prev" }, { "test": "nav_pager_to_last_7x7", "passed": true, "message": "", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "mode label '7x7'; btn_next absent on the last page; btn_prev present" }, { "test": "nav_pager_last_arrow_vlm", "passed": true, "message": "VLM: Q='Is there a right-pointing next arrow on the RIGHT edge next to the mode preview? Answer NO if only a left-pointing arrow is present.' A=NO expect=NO", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "VLM NO: Is there a right-pointing next arrow on the RIGHT edge next to the mode preview? Answer NO if only a left-pointing arrow is present.", "tag": "position" }, { "test": "nav_stats_tab_4to5", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "tapping 5X5 tab reveals the 5x5 stat ids (highest_number2)" }, { "test": "nav_deep_theme_dialog", "passed": true, "message": "", "depth": 2, "jump_kind": "reach", "tier": 2, "expect": "theme AlertDialog: option 'Dark' appears; settings row 'Activate Animation' disappears" }, { "test": "nav_deep_theme_dialog_vlm", "passed": true, "message": "VLM: Q='Is a pop-up dialog titled 'Select theme' shown with radio options (System / Light / Dark) stacked vertically?' A=YES expect=YES", "depth": 2, "jump_kind": "reach", "tier": 2, "expect": "VLM YES: Is a pop-up dialog titled 'Select theme' shown with radio options (System / Light / Dark) stacked vertically?", "tag": "shape" }, { "test": "nav_deep_color_dialog", "passed": true, "message": "", "depth": 2, "jump_kind": "reach", "tier": 2, "expect": "color AlertDialog: option 'Original' appears; settings row 'Activate Animation' disappears" }, { "test": "nav_deep_game_roundtrip", "passed": true, "message": "", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "after Main->Game->BACK the MainActivity is restored: 'START NEW GAME' present, restartButton gone" }, { "test": "nav_deep_stats_tab_content", "passed": true, "message": "", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "5X5 tab reveals highest_number2 and moves_L2 stat fields" }, { "test": "nav_reach_continue_game", "passed": true, "message": "", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "GameActivity: restartButton appears; 'CONTINUE GAME' disappears" } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229{ "module": "states", "total": 21, "passed": 21, "failed": 0, "pass_rate": 1.0, "rule": { "total": 13, "passed": 13, "failed": 0, "pass_rate": 1.0 }, "vlm": { "total": 8, "passed": 8, "failed": 0, "pass_rate": 1.0 }, "vlm_ratio": 0.6154, "audit": { "kit_api_version": 1, "existence": 0, "liveness": 0, "interactive": 21, "depth_ge1": 21, "depth_ge2": 5, "value": 0, "vlm_fine": 8 }, "results": [ { "test": "states_animation_switch_on_off_vlm", "passed": true, "message": "VLM: Q='In this settings list, is the ON/OFF toggle switch next to 'Activate Animation' in its ON state, with the thumb slid to the RIGHT end of its track?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: In this settings list, is the ON/OFF toggle switch next to 'Activate Animation' in its ON state, with the thumb slid to the RIGHT end of its track?", "tag": "position" }, { "test": "states_animation_toggle", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "'Activate Animation' Switch checked true->false after tap" }, { "test": "states_animation_persists_revisit", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "'Activate Animation' checked=false persists after Main->Settings revisit" }, { "test": "states_screenlock_toggle", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "'Activate Screen Lock' Switch checked true->false after tap" }, { "test": "states_screenlock_persists_revisit", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "'Activate Screen Lock' checked=false persists across revisit" }, { "test": "states_theme_summary_changes", "passed": true, "message": "", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "'Select theme' summary System->Dark after picking Dark" }, { "test": "states_theme_dark_applied_vlm", "passed": true, "message": "VLM: Q='Is this settings screen drawn with a DARK theme, i.e. a near-black or dark-grey background behind light-coloured text?' A=YES expect=YES", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Is this settings screen drawn with a DARK theme, i.e. a near-black or dark-grey background behind light-coloured text?", "tag": "color" }, { "test": "states_theme_system_restored_vlm", "passed": true, "message": "VLM: Q='Is this settings screen drawn with a LIGHT theme, i.e. a white or light background behind dark-coloured text?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Is this settings screen drawn with a LIGHT theme, i.e. a white or light background behind dark-coloured text?", "tag": "color" }, { "test": "states_theme_persists_revisit", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "'Select theme' summary stays 'Light' after Main->Settings revisit" }, { "test": "states_color_summary_changes", "passed": true, "message": "", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "'Select Color Scheme' summary Default->Original after picking Original" }, { "test": "states_color_original_tiles_vlm", "passed": true, "message": "VLM: Q='On this 2048 game board, are the numbered tiles coloured in the classic warm ORANGE / TAN / beige palette (NOT blue)?' A=YES expect=YES", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: On this 2048 game board, are the numbered tiles coloured in the classic warm ORANGE / TAN / beige palette (NOT blue)?", "tag": "color" }, { "test": "states_color_default_tiles_vlm", "passed": true, "message": "VLM: Q='On this 2048 game board, are the numbered tiles coloured in a BLUE / blue-gradient palette (NOT orange or tan)?' A=YES expect=YES", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: On this 2048 game board, are the numbered tiles coloured in a BLUE / blue-gradient palette (NOT orange or tan)?", "tag": "color" }, { "test": "states_color_persists_revisit", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "'Select Color Scheme' summary stays 'Original' after revisit" }, { "test": "states_color_preview_changed_vlm", "passed": true, "message": "VLM: Q='On this home screen, is the small 2048 board preview image drawn in warm ORANGE / TAN colours rather than blue?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: On this home screen, is the small 2048 board preview image drawn in warm ORANGE / TAN colours rather than blue?", "tag": "color" }, { "test": "states_continue_enable_transition", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "button_continueGame enabled false->true after playing an unsaved mode then pressing back" }, { "test": "states_undo_button_appears", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "undoButton absent at start -> present after first effective move (same GameActivity)" }, { "test": "states_restart_zeros_points", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "points 4->0 after tapping restartButton" }, { "test": "states_drawer_checked_follows_surface", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "drawer checked flips Main(true)->Settings(true) after navigating to Settings" }, { "test": "states_drawer_selected_highlight_vlm", "passed": true, "message": "VLM: Q='In this open navigation drawer, is the 'Settings' menu row visually highlighted (a coloured/tinted background or coloured text) that sets it apart from the other menu rows?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: In this open navigation drawer, is the 'Settings' menu row visually highlighted (a coloured/tinted background or coloured text) that sets it apart from the other menu rows?", "tag": "color" }, { "test": "states_stats_tab_selected", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "tapping 5x5 tab: selected true (4x4 false) and stat ids *number1->*number2" }, { "test": "states_stats_tab_highlight_vlm", "passed": true, "message": "VLM: Q='In this row of tabs (4x4 / 5x5 / 6x6 / 7x7), is the '5x5' tab visually highlighted as the active tab, e.g. by a coloured underline indicator or a differently-coloured label, compared with the other tabs?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: In this row of tabs (4x4 / 5x5 / 6x6 / 7x7), is the '5x5' tab visually highlighted as the active tab, e.g. by a coloured underline indicator or a differently-coloured label, compared with the other tabs?", "tag": "color" } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202{ "module": "structure", "total": 18, "passed": 18, "failed": 0, "pass_rate": 1.0, "rule": { "total": 10, "passed": 10, "failed": 0, "pass_rate": 1.0 }, "vlm": { "total": 8, "passed": 8, "failed": 0, "pass_rate": 1.0 }, "vlm_ratio": 0.8, "audit": { "kit_api_version": 1, "existence": 3, "liveness": 0, "interactive": 15, "depth_ge1": 13, "depth_ge2": 0, "value": 0, "vlm_fine": 6 }, "results": [ { "test": "structure_gate_launch", "passed": true, "message": "", "depth": 0, "jump_kind": "none", "tier": 0, "expect": "" }, { "test": "structure_gate_main_vlm", "passed": true, "message": "VLM: Q='Is there a game mode preview card in the upper area and two wide buttons stacked near the bottom of the screen?' A=YES expect=YES", "depth": 0, "jump_kind": "none", "tier": 0, "expect": "VLM YES: Is there a game mode preview card in the upper area and two wide buttons stacked near the bottom of the screen?", "tag": "layout" }, { "test": "structure_main_dots_vlm", "passed": true, "message": "VLM: Q='Is there a horizontal row of exactly 4 small round page-indicator dots below the preview image?' A=YES expect=YES", "depth": 0, "jump_kind": "none", "tier": 0, "expect": "VLM YES: Is there a horizontal row of exactly 4 small round page-indicator dots below the preview image?", "tag": "shape" }, { "test": "structure_drawer_opens", "passed": true, "message": "", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "nav_view+6 CheckedTextView appear on open, gone on close" }, { "test": "structure_drawer_opens_vlm", "passed": true, "message": "VLM: Q='Is a vertical navigation menu panel of about six labeled rows shown on the left side of the screen?' A=YES expect=YES", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Is a vertical navigation menu panel of about six labeled rows shown on the left side of the screen?", "tag": "position" }, { "test": "structure_game_board_appears", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "number_field with >=16 Buttons appears; button_newGame disappears" }, { "test": "structure_game_board_appears_vlm", "passed": true, "message": "VLM: Q='Is a 4 by 4 grid of equally sized square cells shown in the middle of the screen?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Is a 4 by 4 grid of equally sized square cells shown in the middle of the screen?", "tag": "shape" }, { "test": "structure_board_size_grows", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "5x5 board Buttons (29) > 4x4 board Buttons (20)" }, { "test": "structure_board_size_grows_vlm", "passed": true, "message": "VLM: Q='Is the grid of tiles 5 columns wide and 5 rows tall?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Is the grid of tiles 5 columns wide and 5 rows tall?", "tag": "shape" }, { "test": "structure_restart_reseeds", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "numeric tiles: 2 fresh -> board changes on moves -> 2 after restart" }, { "test": "structure_game_tile_color_vlm", "passed": true, "message": "VLM: Q='Do the tiles that contain numbers have a solid fill color that clearly differs from the empty background cells?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Do the tiles that contain numbers have a solid fill color that clearly differs from the empty background cells?", "tag": "color" }, { "test": "structure_settings_list", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "ListView with >=4 preference title rows and exactly 2 Switch widgets" }, { "test": "structure_stats_tabs", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "4 mode tabs (4x4..7x7) + >=8 stat TextViews" }, { "test": "structure_stats_tabs_vlm", "passed": true, "message": "VLM: Q='Is a horizontal row of tab labels positioned across the top of the screen, with rows of statistics below it?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Is a horizontal row of tab labels positioned across the top of the screen, with rows of statistics below it?", "tag": "position" }, { "test": "structure_help_expand", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "9 listTitle rows; expanding a row adds 1 body TextView, collapsing removes it" }, { "test": "structure_help_expand_vlm", "passed": true, "message": "VLM: Q='Is the screen a vertical list of question rows, one per line, like an FAQ or expandable help list?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Is the screen a vertical list of question rows, one per line, like an FAQ or expandable help list?", "tag": "layout" }, { "test": "structure_about_scroll", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "ScrollView with >=6 static TextViews" }, { "test": "structure_tutorial_slider", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "ViewPager + layoutDots + SKIP + NEXT buttons" } ]}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910#!/usr/bin/env python3"""Android TestGen Kit — the single source of every test helper, so a test'sNAVIGATION DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded,and self-auditable.
LOCATION AT RUNTIME: alongside the generated test files (testgen: $TESTGEN_DIR/eval/,eval: the restored eval dir). READ-ONLY — never edit, copy, or reimplement it.`import` it from every test file:
import os, sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from android_testgen_kit import * # noqa: F403
WHY THIS EXISTS Helpers used to be re-emitted verbatim into every generated test file (~370 lines x 6 files). That blew the output-token ceiling, forced a "write the script in pieces" protocol, let each copy drift, and duplicated one API key into every file. Everything mechanical now lives here; prompts carry only judgement.
Two orthogonal properties decide whether a suite really exercises an app: * navigation DEPTH — how many SURFACES you cross before the assertion (0 = first screen, 1 = one page/dialog/sheet, 2+ = deeper) * jump RIGOR — what the assertion after the trigger actually checks Prose alone let these drift, so every behavioral test DECLARES both:
@and_test(expects=("interaction_create_note", "interaction_create_note_vlm")) def test_create_note(): ... record("interaction_create_note", ok, "behavior_wrong: ...", depth=1, jump_kind="value", expect="list shows 'Milk'")
jump_kind (verbatim strings — audit/stats key off them): "none" no trigger; existence/gate only -> tier 0 "liveness" only "did not crash / still foreground" -> tier 1 (weak; never ship) "reach" a real surface jump: the TARGET surface's element APPEARED *and* the SOURCE surface's DISAPPEARED -> tier 2 "transition" a state flip (checked/enabled/selected/mode) with before->after -> tier 2 "value" a specific expected value/content was asserted -> tier 3
WHAT A "SURFACE" IS ON ANDROID NOT the Activity — single-Activity Compose/Fragment apps never change it, so get_current_activity() cannot discriminate. A surface is the SET of visible discriminating element keys: and_showing() -> {"Button|Save", "TextView|Total"}. and_reach(before, after, target, source) therefore proves a real jump; reading a flat tree for an always-present element cannot fake it.
DETERMINISTIC DENOMINATOR Scoring is eval_pass_case / origin_total_case, so a test function MUST contribute the same number of records on every code path. @and_test(expects=(...)) owns the try/except and back-fills any declared-but-unrecorded name as a failure, and record() refuses duplicates. N is a literal in the decorator.
PORTABILITY (the same file scores the ORIGINAL and the RECREATION, whose packagename differs): always use the module-level PACKAGE (argv[1]). Never write a packagename, an .apk path, a /data/data path, or a pixel coordinate as a literal. python3 android_testgen_kit.py lint_sources <dir> # flags all of those
SELF-AUDIT (report-only — these are GOALS, never a gate that blocks delivery): python3 android_testgen_kit.py audit <results_dir> python3 android_testgen_kit.py lint <results_dir> python3 android_testgen_kit.py lint_sources <testgen_dir> python3 android_testgen_kit.py audit_depth <testgen_dir> [results_dir]"""from __future__ import annotations
import astimport base64import functoolsimport globimport hashlibimport jsonimport mathimport osimport reimport shleximport subprocessimport sysimport timeimport urllib.errorimport urllib.request
KIT_API_VERSION = 1
# ── Runtime context ────────────────────────────────────────────────────────────# argv[1] = package under test (ORIGINAL during testgen, RECREATION during eval).# argv[2] / $RESULTS_DIR = where the eval JSON + screenshots go.PACKAGE = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("PACKAGE", "")RESULTS_DIR = ( sys.argv[2] if len(sys.argv) > 2 else os.environ.get("RESULTS_DIR", "/workspace/testgen/eval"))ADB = os.environ.get("ADB_PATH", "adb")DEVICE = os.environ.get("DEVICE_SERIAL", "emulator-5554")
# Known emulator packages (from adb-tips). Used by type_text, never by tests.CLIPPER_PKG = "ca.zgrs.clipper"ADB_KEYBOARD_IME = "com.android.adbkeyboard/.AdbIME"
# ── Settling table (adb-tips §5). ANDROID_REMOTE=1 doubles it for tunnelled adb. ─_REMOTE = os.environ.get("ANDROID_REMOTE", "") in ("1", "true", "yes")_SETTLE_MULT = 2.0 if _REMOTE else 1.0SETTLE = { "launch": 3.0, "tap": 1.0, "key": 0.5, "keyboard": 0.5, "dump": 1.0, "ime": 0.5, "text": 0.5, "swipe": 1.0, "dump_retry": 2.0,}
JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3}
# Double-axis quota TARGETS (fractions). rb_audit REPORTS these; they are NOT a# gate. Tune here only — never restate them in a prompt.QUOTAS = { "existence_max": 0.30, # jump_kind=="none" share of ALL tests "interactive_min": 0.60, # reach|transition|value share of ALL tests "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests "depth_ge2_min": 0.15, # depth>=2 share of INTERACTIVE tests "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests # Suite-wide VLM budget, measured as vlm records / ALL records. The right # share is app-dependent (a chart/canvas app earns more than a list app) and # individual modules may legitimately contribute zero, so this is a BAND on # the whole suite, never a per-module requirement. "vlm_share_min": 0.30, "vlm_share_max": 0.50, "vlm_fine_min": 0.66, # fine-grained share of VLM records}
# Depth family (naming convention — see and_audit_depth). A test "crosses a# surface" iff it calls a member of this family; and_back* pops one. Semantic# aliases (and_enter_settings, and_reach_detail) match BY PREFIX, so the kit stays# small and the authored tests stay diverse.DEPTH_FWD_RE = re.compile(r"^and_(enter|reach)[a-z0-9_]*$")DEPTH_BACK_RE = re.compile(r"^and_back[a-z0-9_]*$")DEPTH_RESET_RE = re.compile(r"^and_reset_depth$")
# VLM tags. The fine-grained ones test an exact rendered property; and_audit# computes the >=2/3 fine share from these instead of trusting self-report.VLM_FINE_TAGS = {"color", "shape", "position", "size"}VLM_TAGS = VLM_FINE_TAGS | {"layout", "content"}
# Failure-message taxonomy. and_lint flags a failed record that uses none of them.FAIL_PREFIXES = ("setup_failed:", "feature_missing:", "behavior_wrong:", "exception:")
# Never tap these (tests mutate real device state).DANGEROUS_TEXTS = [ "delete", "remove", "clear", "reset", "erase", "discard", "uninstall", "sign out", "log out", "logout", "format", "wipe", "revoke", "deactivate", "删除", "移除", "清空", "清除", "重置", "退出登录", "注销", "格式化",]
_MODULE_ALIAS = { "states": "states", "state": "states", "structure": "structure", "structures": "structure", "navigation": "navigation", "nav": "navigation", "interaction": "interaction", "interactions": "interaction", "computation": "computation", "computations": "computation", "text": "text", "texts": "text",}
_DEPTH = 0 # surface counter for and_enter/and_back_results: list[dict] = []_seen: set[str] = set()_module: str = ""_screen_info: dict | None = None
def require_kit(min_version: int) -> None: """Fail loudly at import time if the kit is older than the test expects.""" if KIT_API_VERSION < min_version: raise RuntimeError( f"android_testgen_kit v{KIT_API_VERSION} is older than the required " f"v{min_version}; the restored testcase bundle and the kit disagree" )
def _infer_module() -> str: stem = os.path.splitext(os.path.basename(sys.argv[0] or ""))[0] if stem.startswith("test_android_"): return _MODULE_ALIAS.get(stem[len("test_android_"):], stem[len("test_android_"):]) return ""
def init(module: str = "", package: str = "", results_dir: str = "") -> None: """Optional. Overrides the values inferred from argv/env.""" global _module, PACKAGE, RESULTS_DIR if module: _module = _MODULE_ALIAS.get(module, module) if package: PACKAGE = package if results_dir: RESULTS_DIR = results_dir
_module = _infer_module()
def tier_of(jump_kind: str) -> int: return JUMP_KINDS.get(jump_kind, 2)
def settle(kind: str = "tap") -> None: """Sleep the calibrated settling time for `kind` (see SETTLE).""" time.sleep(SETTLE.get(kind, 1.0) * _SETTLE_MULT)
# ══════════════════════════════════════════════════════════════════════════════# (1) Results / recording# ══════════════════════════════════════════════════════════════════════════════
def record(test_name, passed, message="", *, depth=None, jump_kind="none", expect="", tag=None, backfilled=False) -> bool: """Record ONE test result. Returns bool(passed).
The three positional parameters are unchanged from the legacy inline helper. Everything new is keyword-only with a default, so old call sites still work.
depth surfaces this test crossed before asserting (see and_enter/and_reach) jump_kind none | liveness | reach | transition | value expect MANDATORY for reach/transition/value — the exact target you OBSERVED on the original app (and_lint flags an empty one) tag for VLM records: color|shape|position|size|layout|content message on failure, start it with setup_failed: / feature_missing: / behavior_wrong: / exception: """ if test_name in _seen: print(f" [DUP ] {_module}:{test_name} refused (already recorded) — " f"a duplicate would drift the denominator") return bool(passed) if jump_kind not in JUMP_KINDS: jump_kind = "none" d = _DEPTH if depth is None else int(depth) p = bool(passed) rec = { "test": test_name, "passed": p, "message": str(message), "depth": max(0, d), "jump_kind": jump_kind, "tier": tier_of(jump_kind), "expect": str(expect), } if tag: rec["tag"] = str(tag) if backfilled: rec["backfilled"] = True _results.append(rec) _seen.add(test_name) print(f" [{'PASS' if p else 'FAIL'}] {_module}:{test_name} " f"(depth={rec['depth']}, {jump_kind})" + (f" {message}" if message and not p else "")) _flush() return p
def _payload(module_name: str) -> dict: """The eval JSON. Shape is byte-compatible with the legacy helper: the aggregator reads module/total/passed/pass_rate, and the results extraction reads the rule/vlm sub-objects. New keys ride inside results[] + `audit`.""" rule = [r for r in _results if not r["test"].endswith("_vlm")] vlm = [r for r in _results if r["test"].endswith("_vlm")] rt, rp = len(rule), sum(1 for r in rule if r["passed"]) vt, vp = len(vlm), sum(1 for r in vlm if r["passed"]) total, passed = len(_results), sum(1 for r in _results if r["passed"]) fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS) inter = [r for r in _results if r["jump_kind"] in ("reach", "transition", "value")] return { "module": module_name, "total": total, "passed": passed, "failed": total - passed, "pass_rate": round(passed / total, 4) if total else 0, "rule": {"total": rt, "passed": rp, "failed": rt - rp, "pass_rate": round(rp / rt, 4) if rt else 0}, "vlm": {"total": vt, "passed": vp, "failed": vt - vp, "pass_rate": round(vp / vt, 4) if vt else 0}, "vlm_ratio": round(vt / rt, 4) if rt else 0, "audit": { "kit_api_version": KIT_API_VERSION, "existence": sum(1 for r in _results if r["jump_kind"] == "none"), "liveness": sum(1 for r in _results if r["jump_kind"] == "liveness"), "interactive": len(inter), "depth_ge1": sum(1 for r in inter if r["depth"] >= 1), "depth_ge2": sum(1 for r in inter if r["depth"] >= 2), "value": sum(1 for r in inter if r["jump_kind"] == "value"), "vlm_fine": fine, }, "results": _results, }
def _write_json(path: str, data: dict) -> None: """Atomic write, so a mid-run SIGKILL never leaves a truncated JSON.""" os.makedirs(os.path.dirname(path) or ".", exist_ok=True) tmp = path + ".tmp" with open(tmp, "w") as f: json.dump(data, f, indent=2, ensure_ascii=False) os.replace(tmp, path)
def _flush() -> None: """Persist after EVERY record, so a timeout/emulator hang leaves N results instead of zero. save_results() stays the documented finalizer.""" if not _module: return try: _write_json(os.path.join(RESULTS_DIR, f"android_{_module}_eval.json"), _payload(_module)) except Exception: pass
def save_results(module_name: str) -> dict: """MANDATORY finalizer. Authoritatively rewrites the eval JSON under the confirmed module name, prints the summary, and runs the in-process audit. Idempotent.""" global _module _module = _MODULE_ALIAS.get(module_name, module_name) out = _payload(_module) path = os.path.join(RESULTS_DIR, f"android_{_module}_eval.json") _write_json(path, out) print(f"Results: {out['passed']}/{out['total']} passed " f"(rule: {out['rule']['passed']}/{out['rule']['total']}, " f"vlm: {out['vlm']['passed']}/{out['vlm']['total']}) -> {path}") try: and_audit(RESULTS_DIR) and_lint(RESULTS_DIR) except Exception as exc: print(f"[audit] skipped: {exc}") return out
def declared_names() -> list[str]: """Every record name produced so far. The eval run MUST produce this same set against the recreation — a missing feature FAILS, it never vanishes from the denominator.""" return [r["test"] for r in _results]
def and_test(*, expects, module: str = ""): """Wrap a test function so it contributes EXACTLY len(expects) records on every code path — the deterministic-denominator guarantee.
Any name in `expects` still unrecorded when the function returns or raises is back-filled as a failure. The literal also lets and_audit_depth attribute records to this function exactly.
@and_test(expects=("states_toggle_dark", "states_toggle_dark_vlm")) def test_toggle_dark(): ... """ names = tuple(expects)
def deco(fn): @functools.wraps(fn) def wrapper(*a, **kw): if module: init(module=module) err = "" try: return fn(*a, **kw) except Exception as exc: err = f"{type(exc).__name__}: {exc}" print(f" [EXC ] {fn.__name__}: {err}") return None finally: for n in names: if n not in _seen: record(n, False, f"exception: not_reached ({err})" if err else "setup_failed: not_reached (no exception raised)", backfilled=True) wrapper._and_expects = names return wrapper return deco
def run_suite(tests, module: str) -> dict: """Run every test, then finalize. Each test owns its own entry point, so one failure never cascades.""" init(module=module) n_fix = len(fixture_names()) print(f"=== {module}: {len(tests)} tests | package={PACKAGE}" + (f" | fixtures={n_fix}" if n_fix else "") + " ===") if n_fix and not push_fixtures(): print(" [fixtures] WARNING: not all fixtures reached the device — every " "test that opens one will record setup_failed") for t in tests: and_reset_depth() try: t() except Exception as exc: print(f" [EXC ] {getattr(t, '__name__', t)}: {exc}") return save_results(module)
# ══════════════════════════════════════════════════════════════════════════════# (2) Device & adb primitives# ══════════════════════════════════════════════════════════════════════════════
def adb_shell(*args, timeout: int = 30) -> str: """`adb -s $DEVICE shell ...` -> stdout. The -s serial is ALWAYS injected, so a multi-device host can never dispatch to the wrong emulator.""" try: r = subprocess.run([ADB, "-s", DEVICE, "shell", *[str(a) for a in args]], capture_output=True, text=True, timeout=timeout) return r.stdout.strip() except subprocess.TimeoutExpired: return "" except Exception: return ""
def adb_raw(*args, timeout: int = 30) -> str: """`adb -s $DEVICE ...` (no `shell`) — for install/pull/exec-out.""" try: r = subprocess.run([ADB, "-s", DEVICE, *[str(a) for a in args]], capture_output=True, text=True, timeout=timeout) return r.stdout.strip() except Exception: return ""
def device_online() -> bool: try: out = subprocess.run([ADB, "devices"], capture_output=True, text=True, timeout=15).stdout except Exception: return False return any(ln.startswith(DEVICE) and ln.rstrip().endswith("device") for ln in out.splitlines()[1:])
def get_screen_info() -> dict: """Cached screen geometry. EVERY coordinate must be derived from this, never written as a literal — density and font scale differ across devices.""" global _screen_info if _screen_info: return _screen_info m = re.search(r"(\d+)x(\d+)", adb_shell("wm", "size")) w, h = (int(m.group(1)), int(m.group(2))) if m else (1080, 2400) md = re.search(r"(\d+)", adb_shell("wm", "density")) _screen_info = {"width": w, "height": h, "density": int(md.group(1)) if md else 440, "center_x": w // 2, "center_y": h // 2} return _screen_info
def screencap(path: str) -> bool: """Screenshot to a local path. exec-out first; falls back to on-device screencap + pull, which is what survives a tunnelled adb connection.""" os.makedirs(os.path.dirname(path) or ".", exist_ok=True) try: with open(path, "wb") as f: subprocess.run([ADB, "-s", DEVICE, "exec-out", "screencap", "-p"], stdout=f, timeout=20) if os.path.getsize(path) > 0: return True except Exception: pass remote = "/sdcard/_kit_shot.png" adb_shell("screencap", "-p", remote) adb_raw("pull", remote, path, timeout=40) adb_shell("rm", "-f", remote) return os.path.exists(path) and os.path.getsize(path) > 0
# ── Fixtures: sample files a file/image/document app needs to have anything to# open. These MUST be a pipeline artifact, not something you push by hand while# exploring: testgen and eval run in DIFFERENT jobs on DIFFERENT emulators, so a# hand-pushed file is gone by eval and every test that opens it records# setup_failed — blaming the recreation for a harness gap.## authoring (once, during recon): write the files into <EVAL_OUT>/fixtures/# consuming (every test run): run_suite() pushes them before the first test## The directory rides along with the test files into the testcases bank, so the# bytes are restored on every later eval. Sub-directories are preserved, so# fixtures/docs/a.pdf lands at /sdcard/Download/docs/a.pdf.FIXTURES_DEVICE_DIR = "/sdcard/Download"_fixtures_pushed = False
def fixtures_dir() -> str: """The host fixtures directory, or "" when this app needs none.
The script's own directory comes FIRST: at eval, RESULTS_DIR is a separate eval_results/ dir, while the fixtures were restored next to the test files. """ for cand in (os.environ.get("FIXTURES_DIR", ""), os.path.join(os.path.dirname(os.path.abspath(sys.argv[0] or ".")), "fixtures"), os.path.join(RESULTS_DIR, "fixtures")): if cand and os.path.isdir(cand): return cand return ""
def fixture_names() -> list[str]: """Fixture paths relative to fixtures_dir(), e.g. ["doc.pdf", "docs/b.epub"].""" src = fixtures_dir() if not src: return [] out = [] for root, _dirs, files in os.walk(src): for fn in sorted(files): if fn.startswith("."): continue out.append(os.path.relpath(os.path.join(root, fn), src)) return sorted(out)
def fixture_on_device(name: str, dest: str = FIXTURES_DEVICE_DIR) -> str: """Where `name` lives on the device after push_fixtures().""" return f"{dest.rstrip('/')}/{name}"
def push_fixtures(dest: str = FIXTURES_DEVICE_DIR, *, force: bool = False) -> bool: """Mirror the host fixtures onto the device. Idempotent and safe to call from every test — a file already there with the same size is not re-pushed, so the six module processes cost one real push between them.
Returns True when the device holds every fixture (including the vacuous case of an app that needs none). """ global _fixtures_pushed if _fixtures_pushed and not force: return True src = fixtures_dir() names = fixture_names() if not src or not names: _fixtures_pushed = True return True ok = True pushed = 0 for rel in names: local = os.path.join(src, rel) remote = fixture_on_device(rel, dest) try: want = os.path.getsize(local) except OSError: ok = False continue got = adb_shell("stat", "-c", "%s", remote) if not force and got.isdigit() and int(got) == want: continue parent = remote.rsplit("/", 1)[0] if parent: adb_shell("mkdir", "-p", parent) adb_raw("push", local, remote, timeout=120) check = adb_shell("stat", "-c", "%s", remote) if check.isdigit() and int(check) == want: pushed += 1 else: ok = False print(f" [fixtures] FAILED to push {rel} -> {remote}") if pushed: # Make the files visible to gallery/media-backed pickers. Both forms are # API-level dependent and neither is required for plain SAF browsing, so # failures here are not fatal. adb_shell("content", "call", "--uri", "content://media/external/file", "--method", "scan_volume", "--arg", "external_primary") adb_shell("am", "broadcast", "-a", "android.intent.action.MEDIA_SCANNER_SCAN_FILE", "-d", f"file://{dest}") print(f" [fixtures] pushed {pushed}/{len(names)} fixture(s) to {dest}") _fixtures_pushed = ok return ok
# ══════════════════════════════════════════════════════════════════════════════# (3) UI tree query & element matching# ══════════════════════════════════════════════════════════════════════════════
def dump_xml(retries: int = 3, settle_first: bool = True) -> str: """uiautomator dump -> XML text. Retries because the dump fails outright while an animation is in flight.""" if settle_first: settle("dump") remote = "/sdcard/_kit_ui.xml" for attempt in range(retries): adb_shell("uiautomator", "dump", remote) xml = adb_shell("cat", remote, timeout=60) if "<node" in xml: return xml settle("dump_retry") return ""
def parse_nodes(xml_str: str) -> list[dict]: """XML -> list of attribute dicts, each with _bounds and _center.""" nodes = [] for m in re.finditer(r"<node\s+([^>]+?)/?>", xml_str): attrs_str = m.group(1) attrs = {am.group(1): am.group(2) for am in re.finditer(r'([\w-]+)="([^"]*)"', attrs_str)} b = re.search(r'bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"', attrs_str) if b: x1, y1, x2, y2 = (int(v) for v in b.groups()) attrs["_bounds"] = (x1, y1, x2, y2) attrs["_center"] = ((x1 + x2) // 2, (y1 + y2) // 2) nodes.append(attrs) return nodes
def ui(retries: int = 3) -> list[dict]: """THE entry point for a fresh tree. Call it again after ANY state change — a scroll, navigation, dialog, or keyboard invalidates every prior coordinate.""" return parse_nodes(dump_xml(retries=retries))
def find_nodes(nodes, **criteria) -> list[dict]: """Nodes matching ALL criteria, EXACT string match. `True`/`False` match the "true"/"false" attribute strings. Underscores in keys become dashes (content_desc -> content-desc).""" out = [] for n in nodes: ok = True for k, v in criteria.items(): key = k.replace("_", "-") if "_" in k and k != "class" else k if key not in n: ok = False break if v is True and n[key] != "true": ok = False break if v is False and n[key] != "false": ok = False break if v is not True and v is not False and n[key] != v: ok = False break if ok: out.append(n) return out
def find_node(nodes, **criteria) -> dict | None: f = find_nodes(nodes, **criteria) return f[0] if f else None
def find_by_class(nodes, widget_class: str) -> list[dict]: """Partial class-name match, e.g. "Switch", "EditText", "RecyclerView".""" return [n for n in nodes if widget_class in n.get("class", "")]
def find_node_ci(nodes, text: str) -> dict | None: """Case-insensitive text or content-desc match. Use for user-visible labels whose casing a faithful recreation may legitimately differ on.""" t = text.strip().lower() for n in nodes: if (n.get("text", "").strip().lower() == t or n.get("content-desc", "").strip().lower() == t): return n return None
def node_by_id(nodes, rid_suffix: str) -> dict | None: """Match the LAST segment of resource-id, so the package prefix (which differs between original and recreation) is never compared.""" for n in nodes: rid = n.get("resource-id", "") if rid and rid.rsplit("/", 1)[-1] == rid_suffix: return n return None
def find_closest_match(nodes, original_node) -> dict | None: """Re-locate a node in a fresh dump by similarity (class/text/desc/position).""" best, best_score = None, 0 for n in nodes: score = 0 if n.get("class") == original_node.get("class"): score += 3 if n.get("text") and n.get("text") == original_node.get("text"): score += 5 if (n.get("content-desc") and n.get("content-desc") == original_node.get("content-desc")): score += 4 if "_center" in n and "_center" in original_node: if (abs(n["_center"][0] - original_node["_center"][0]) < 100 and abs(n["_center"][1] - original_node["_center"][1]) < 100): score += 2 if score > best_score: best, best_score = n, score return best if best_score >= 3 else None
def node_key(n: dict) -> str: """"{shortClass}|{identity}" — the surface-membership key. Identity priority: text -> content-desc -> resource-id suffix. Returns "" for anonymous nodes (pure layout containers), which are excluded from a surface.""" cls = n.get("class", "").rsplit(".", 1)[-1] ident = (n.get("text", "").strip() or n.get("content-desc", "").strip() or n.get("resource-id", "").rsplit("/", 1)[-1]) return f"{cls}|{ident}" if ident else ""
def and_showing(nodes=None) -> set[str]: """Snapshot the current SURFACE as a set of discriminating element keys. Only on-screen, non-degenerate, identity-bearing nodes count. Take one before and one after a trigger and feed them to and_reach().""" nodes = ui() if nodes is None else nodes s = get_screen_info() out = set() for n in nodes: b = n.get("_bounds") if not b: continue x1, y1, x2, y2 = b if (x2 - x1) < 5 or (y2 - y1) < 5: continue if x2 <= 0 or y2 <= 0 or x1 >= s["width"] or y1 >= s["height"]: continue k = node_key(n) if k: out.add(k) return out
def and_reach(before, after, target: str, source: str | None = None) -> bool: """TRUE-JUMP verdict: the TARGET surface's element newly APPEARED and (if given) the SOURCE surface's element DISAPPEARED. This is what separates a real surface jump from reading an element that was in the tree all along.""" before, after = set(before or []), set(after or []) t = target.strip().lower() appeared = any(t in k.lower() for k in (after - before)) if source is None: return appeared s = source.strip().lower() return (appeared and any(s in k.lower() for k in before) and not any(s in k.lower() for k in after))
def surface_changed(before, after, min_delta: int = 2) -> bool: """Weaker than and_reach: the surface changed materially but you are not naming the target. Use for shape deltas, never to claim a `reach`.""" return len(set(before or []) ^ set(after or [])) >= min_delta
def and_surface_id(nodes=None) -> str: """A stable-ish fingerprint of the current surface, for "did this change?".""" keys = sorted(and_showing(nodes)) return f"{len(keys)}:{hash(tuple(keys)) & 0xFFFFFF:06x}"
# ══════════════════════════════════════════════════════════════════════════════# (4) Interaction# ══════════════════════════════════════════════════════════════════════════════
def tap(x, y) -> None: adb_shell("input", "tap", int(x), int(y)) settle("tap")
def tap_node(node) -> bool: """Tap a node's centre, validating bounds against the real screen first.""" if not node or "_center" not in node: return False x, y = node["_center"] s = get_screen_info() if x < 0 or x > s["width"] or y < 0 or y > s["height"]: return False if "_bounds" in node: x1, y1, x2, y2 = node["_bounds"] if (x2 - x1) < 5 or (y2 - y1) < 5: return False tap(x, y) return True
def tap_text(nodes, text: str) -> bool: n = find_node(nodes, text=text) or find_node_ci(nodes, text) return tap_node(n) if n else False
def is_safe(node) -> bool: """False for destructive controls. Tests mutate real device state, so every exploratory tap must go through this.""" blob = " ".join([node.get("text", ""), node.get("content-desc", ""), node.get("resource-id", "")]).lower() return not any(d in blob for d in DANGEROUS_TEXTS)
def safe_tap(node) -> bool: return tap_node(node) if node and is_safe(node) else False
def long_press(node, ms: int = 800) -> bool: """Long-press = a zero-distance swipe with a duration.""" if not node or "_center" not in node: return False x, y = node["_center"] adb_shell("input", "swipe", x, y, x, y, int(ms)) settle("tap") return True
def swipe(x1, y1, x2, y2, ms: int = 300) -> None: adb_shell("input", "swipe", int(x1), int(y1), int(x2), int(y2), int(ms)) settle("swipe")
def scroll_down(frac: float = 0.5) -> None: s = get_screen_info() swipe(s["center_x"], int(s["height"] * 0.7), s["center_x"], int(s["height"] * (0.7 - frac)))
def scroll_up(frac: float = 0.5) -> None: s = get_screen_info() swipe(s["center_x"], int(s["height"] * 0.3), s["center_x"], int(s["height"] * (0.3 + frac)))
def open_drawer() -> None: s = get_screen_info() swipe(5, s["center_y"], int(s["width"] * 0.8), s["center_y"], ms=400)
def scroll_into_view(text: str, max_swipes: int = 4) -> dict | None: """Scroll until `text` is on screen, RE-DUMPING between swipes. This encodes "after a scroll every previous coordinate is invalid" as code.""" for _ in range(max_swipes + 1): nodes = ui() n = find_node(nodes, text=text) or find_node_ci(nodes, text) if n: return n scroll_down(0.4) return None
def press_key(keycode) -> None: adb_shell("input", "keyevent", keycode) settle("key")
def back() -> None: """Raw BACK. Use and_back() when you are leaving a surface you entered.""" press_key("KEYCODE_BACK")
def home() -> None: press_key("KEYCODE_HOME")
def enter() -> None: press_key("KEYCODE_ENTER")
def keyboard_visible() -> bool: return "mInputShown=true" in adb_shell("dumpsys", "input_method")
def hide_keyboard() -> bool: """Dismiss the soft keyboard without navigating away. Tries, in order: the collapse affordance, an empty region, then BACK — and BACK is only accepted if the surface did NOT change, because BACK can navigate instead.""" if not keyboard_visible(): return True nodes = ui() for n in nodes: blob = (n.get("content-desc", "") + n.get("resource-id", "")).lower() if any(w in blob for w in ("hide", "collapse", "close_keyboard", "back")): if tap_node(n): settle("keyboard") if not keyboard_visible(): return True s = get_screen_info() tap(s["center_x"], int(s["height"] * 0.12)) # top strip is rarely interactive settle("keyboard") if not keyboard_visible(): return True sid = and_surface_id() back() settle("keyboard") if keyboard_visible(): return False if and_surface_id() != sid: print(" [warn] hide_keyboard: BACK also changed the surface") return True
def _quote_for_device(text: str) -> str: """Quote a string for the on-device shell (adb joins argv with spaces).""" return shlex.quote(text)
def type_text(node, text: str, *, method: str = "auto", verify_focus: bool = True) -> bool: """Type into an EditText, safely.
An unfocused EditText silently swallows ALL input (including paste and the ADB-Keyboard broadcast), so this taps the field, re-dumps, and asserts focused="true" before typing — retrying the tap once.
Routing: pure ASCII -> `input text`. Non-ASCII -> Clipper broadcast + paste. method="ime" -> ADB Keyboard, which needs a re-tap after the IME switch (the switch drops focus) and ALWAYS restores the original IME in a finally. """ if not node: return False target = node if verify_focus: ok = False for _ in range(2): if not tap_node(target): return False settle("keyboard") fresh = find_closest_match(ui(), target) or target if fresh.get("focused") == "true": target, ok = fresh, True break target = fresh if not ok: print(" [warn] type_text: field never reported focused=true") else: tap_node(target) settle("keyboard")
is_ascii = all(ord(c) < 128 for c in text) use = method if use == "auto": use = "input" if is_ascii else "clipper"
if use == "input": adb_shell("input", "text", _quote_for_device(text.replace(" ", "%s"))) settle("text") return True
if use == "clipper": adb_shell("am", "broadcast", "-a", "clipper.set", "-e", "text", _quote_for_device(text)) settle("text") press_key(279) # KEYCODE_PASTE settle("text") return True
# method="ime": ADB Keyboard. Some custom views ignore paste, this is the fallback. original = adb_shell("settings", "get", "secure", "default_input_method") try: adb_shell("ime", "set", ADB_KEYBOARD_IME) settle("ime") tap_node(target) # IME switch dropped focus settle("keyboard") adb_shell("am", "broadcast", "-a", "ADB_INPUT_TEXT", "--es", "msg", _quote_for_device(text)) settle("text") return True finally: if original and "null" not in original.lower(): adb_shell("ime", "set", original) # NEVER leave it switched settle("ime")
# ══════════════════════════════════════════════════════════════════════════════# (5) Navigation & the depth family# ══════════════════════════════════════════════════════════════════════════════
def and_reset_depth() -> None: global _DEPTH _DEPTH = 0
def and_enter(surface: str = "") -> int: """Call right AFTER your test navigates into a new surface. This is what backs a declared depth>=1 — and_audit_depth looks for a call from the and_enter*/and_reach* family.""" global _DEPTH _DEPTH += 1 return _DEPTH
def and_back() -> int: """Press BACK and pop one surface.""" global _DEPTH back() _DEPTH = max(0, _DEPTH - 1) return _DEPTH
def and_enter_surface(nodes, target_text: str = "", content_desc: str = "", rid: str = "") -> tuple[bool, str]: """Tap a named trigger, then confirm the surface changed. Counts one surface on success. Returns (ok, note). Prefer and_reach_surface when you can name the destination — that yields jump_kind="reach".""" n = None if target_text: n = find_node(nodes, text=target_text) or find_node_ci(nodes, target_text) if n is None and content_desc: n = find_node(nodes, content_desc=content_desc) if n is None and rid: n = node_by_id(nodes, rid) if n is None: return False, f"setup_failed: trigger not found ({target_text or content_desc or rid})" before = and_showing(nodes) if not tap_node(n): return False, "setup_failed: trigger not tappable" after = and_showing() if not surface_changed(before, after): return False, "behavior_wrong: surface did not change after tapping the trigger" and_enter(target_text or content_desc or rid) return True, ""
def and_reach_surface(node, target: str, source: str | None = None) -> bool: """Tap `node`, then PROVE the jump: `target` appeared and `source` vanished. Counts one surface. This is the only honest way to claim jump_kind="reach".""" before = and_showing() if not tap_node(node): return False after = and_showing() ok = and_reach(before, after, target, source) if ok: and_enter(target) return ok
# ══════════════════════════════════════════════════════════════════════════════# (6) App lifecycle — always keyed on PACKAGE (argv[1]), never a literal# ══════════════════════════════════════════════════════════════════════════════
def launch_app() -> None: adb_shell("monkey", "-p", PACKAGE, "-c", "android.intent.category.LAUNCHER", "1") settle("launch")
def force_stop() -> None: adb_shell("am", "force-stop", PACKAGE) settle("key")
def clear_data() -> None: """Wipe app data. Use to guarantee a clean entry point, never mid-assertion.""" adb_shell("pm", "clear", PACKAGE) settle("key")
def restart_app() -> None: force_stop() launch_app()
def force_stop_and_relaunch() -> None: """The persistence probe: kill the process, relaunch, then assert the state survived. An in-memory-only recreation fails this.""" force_stop() settle("key") launch_app()
def get_current_activity() -> str: out = adb_shell("dumpsys", "activity", "activities") m = re.search(r"mResumedActivity.*?\{[^}]*?([\w.]+/[\w.$]+)", out) if m: return m.group(1) m = re.search(r"mCurrentFocus=.*?\{[^}]*?([\w.]+/[\w.$]+)", adb_shell("dumpsys", "window")) return m.group(1) if m else ""
def is_app_foreground() -> bool: return PACKAGE in get_current_activity() or PACKAGE in adb_shell("dumpsys", "window")
def wait_for_foreground(timeout: int = 10) -> bool: deadline = time.time() + timeout while time.time() < deadline: if is_app_foreground(): return True time.sleep(0.5) return False
# ══════════════════════════════════════════════════════════════════════════════# (7) VLM# ══════════════════════════════════════════════════════════════════════════════
# OpenAI-compatible endpoint. Hardcoded on purpose: the public DashScope native# endpoint rejected the key that pods are provisioned with, so every generated# suite either lost its whole VLM track or shipped a hand-rolled `dashscope.py`# shim to reroute it. This speaks plain chat/completions over the standard library# only — no `pip install`, and the stale shims in the testcases bank can no longer# shadow the transport because nothing imports `dashscope` any more.VLM_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"_VLM_DEFAULT_KEY = "sk-bd0c3f375649439bba62b5b0e8c13057"# Attempts per key. 3 covers the blips seen in practice (empty body, gateway 5xx,# rate-limit bursts) without turning a genuine outage into a 10-minute stall.VLM_RETRIES = int(os.environ.get("VLM_RETRIES", "3"))# Repeating these cannot help: the request itself is wrong (malformed, missing,# too large, or semantically rejected). Everything else 4xx/5xx is worth a retry._VLM_TERMINAL_CODES = {400, 404, 413, 422}
def _vlm_key() -> str: """The judge model's API key: first non-empty of DASHSCOPE_API_KEY, VLM_API_KEY, JUDGE_API_KEY. Empty when none is set.""" for name in ("DASHSCOPE_API_KEY", "VLM_API_KEY", "JUDGE_API_KEY"): v = os.environ.get(name, "").strip() if v: return v return ""
def call_vlm(image_path: str, prompt: str, *, retries: int = 0) -> str | None: """Ask the VLM one question about a local screenshot. Returns the answer text.
Retries transient API failures (empty body, 429, 408/409/425, any 5xx) up to `retries` times — default VLM_RETRIES (3), overridable via the VLM_RETRIES env var. Terminal errors (bad key, malformed/oversized request) are not retried. """ retries = retries or VLM_RETRIES key = _vlm_key() or _VLM_DEFAULT_KEY try: with open(image_path, "rb") as f: b64 = base64.b64encode(f.read()).decode() except Exception as exc: print(f"[VLM] cannot read screenshot {image_path}: {exc}") return None mime = "image/jpeg" if image_path.lower().endswith((".jpg", ".jpeg")) else "image/png" body = json.dumps({ "model": os.environ.get("JUDGE_MODEL", "qwen3.7-plus"), "temperature": 0, "messages": [{"role": "user", "content": [ {"type": "image_url", "image_url": {"url": f"data:{mime};base64,{b64}"}}, {"type": "text", "text": prompt}, ]}], }).encode()
for attempt in range(retries): backoff = 2 * (attempt + 1) req = urllib.request.Request( f"{VLM_BASE_URL}/chat/completions", data=body, headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"}) try: with urllib.request.urlopen(req, timeout=120) as resp: data = json.loads(resp.read().decode()) text = (data["choices"][0]["message"]["content"] or "").strip() if text: return text print(f"[VLM] empty response (attempt {attempt + 1}/{retries})") except urllib.error.HTTPError as exc: detail = exc.read().decode(errors="replace")[:200] print(f"[VLM] HTTP {exc.code} (attempt {attempt + 1}/{retries}): {detail}") if exc.code in (401, 403) or exc.code in _VLM_TERMINAL_CODES: return None # repeating cannot help if exc.code == 429: backoff = 10 * (attempt + 1) # rate limit, not a blip except Exception as exc: # timeout, DNS, reset, bad JSON print(f"[VLM] call failed (attempt {attempt + 1}/{retries}): {exc}") if attempt < retries - 1: time.sleep(backoff) print(f"[VLM] giving up after {retries} attempt(s)") return None
def _vlm_log(results_dir: str, entry: dict) -> None: """Append one attempt to vlm_assertions.json. Called on EVERY vlm_assert exit path, including failures — a `_vlm` case with no entry here then provably never invoked the VLM, which is what build_manifest keys off.""" af = os.path.join(results_dir, "vlm_assertions.json") try: existing = json.load(open(af)) if os.path.exists(af) else [] if not isinstance(existing, list): existing = [] except Exception: existing = [] existing.append(entry) try: _write_json(af, existing) # type: ignore[arg-type] except Exception: try: with open(af, "w") as f: json.dump(existing, f, indent=2, ensure_ascii=False) except Exception as exc: print(f" [warn] vlm_assert: cannot write {af}: {exc}")
def vlm_assert(test_name, question, results_dir=None, expect="YES", *, depth=None, jump_kind="none", tag=None) -> bool: """Screenshot the current screen, ask the VLM one YES/NO question, record it.
`test_name` is auto-suffixed with `_vlm`, which is what routes it to the VLM track in save_results(). `tag` (color|shape|position|size|layout|content) lets and_audit compute the fine-grained share mechanically — always set it.
Ask about a SPECIFIC observable rendered property. A question that a blank screen or any app would pass is worthless. """ if not test_name.endswith("_vlm"): test_name += "_vlm" rd = results_dir or RESULTS_DIR if tag and tag not in VLM_TAGS: print(f" [warn] vlm_assert: unknown tag {tag!r}") ss_path = os.path.join(rd, "screenshots", f"{test_name}.png")
def _fail(msg: str, resp=None, answer="") -> bool: _vlm_log(rd, {"test_name": test_name, "question": question, "screenshot": ss_path, "vlm_response": resp, "vlm_answer": answer, "expected": expect, "passed": False, "tag": tag or "", "error": msg}) return record(test_name, False, msg, depth=depth, jump_kind=jump_kind, tag=tag)
if not screencap(ss_path): return _fail("setup_failed: screenshot capture failed")
prompt = ("Look at this Android app screenshot and answer the following question " "with ONLY 'YES' or 'NO'. Do not explain.\n\n" f"Question: {question}\n\nAnswer (YES or NO):") # An unparseable answer is the same class of flakiness as an empty body, so # re-ask rather than scoring harness noise against the VLM track. answer, resp = "", None for ask in range(VLM_RETRIES): resp = call_vlm(ss_path, prompt) if resp is None: return _fail("setup_failed: VLM API call failed") a = resp.strip().upper() # Whole-word match only: a bare `"NO" in a` also fires on CANNOT / NOT / # NONE / KNOW, turning "Maybe? I cannot tell." into a confident NO and # failing the test on harness noise instead of re-asking. has_yes = re.search(r"\bYES\b", a) is not None has_no = re.search(r"\bNO\b", a) is not None if a.startswith("YES"): answer = "YES" elif a.startswith("NO"): answer = "NO" elif has_yes and not has_no: answer = "YES" elif has_no and not has_yes: answer = "NO" if answer: break print(f"[VLM] unparseable answer {resp!r} (ask {ask + 1}/{VLM_RETRIES})") if not answer: return _fail(f"setup_failed: ambiguous VLM response after {VLM_RETRIES} " f"asks {resp!r}", resp=resp)
passed = answer == expect.upper() record(test_name, passed, (f"VLM: Q='{question}' A={answer} expect={expect}" if passed else f"behavior_wrong: VLM Q='{question}' A={answer} expect={expect}"), depth=depth, jump_kind=jump_kind, expect=f"VLM {expect}: {question}", tag=tag) _vlm_log(rd, {"test_name": test_name, "question": question, "screenshot": ss_path, "vlm_response": resp, "vlm_answer": answer, "expected": expect, "passed": passed, "tag": tag or ""}) return passed
# ══════════════════════════════════════════════════════════════════════════════# (8) Audit / lint — ALL report-only. None of these ever blocks delivery.# ══════════════════════════════════════════════════════════════════════════════
def _load_all(results_dir: str) -> list[dict]: recs, seen_files = [], set() for pat in (os.path.join(results_dir, "android_*_eval.json"), os.path.join(results_dir, "eval_results", "android_*_eval.json")): for path in glob.glob(pat): base = os.path.basename(path) if base in seen_files: continue seen_files.add(base) try: data = json.load(open(path)) except Exception: continue for t in data.get("results", []): if isinstance(t, dict) and "test" in t: recs.append(t) return recs
def and_audit(results_dir: str = "", quotas: dict | None = None) -> dict: """Aggregate declared depth/jump_kind/vlm-tag across the suite and report the quota TARGETS with the concrete gap. GOALS, not a gate.""" results_dir = results_dir or RESULTS_DIR q = quotas or QUOTAS recs = _load_all(results_dir) backfilled = [r for r in recs if r.get("backfilled")] recs = [r for r in recs if not r.get("backfilled")] n = len(recs) if not n: print(f"[and_audit] no records under {results_dir}") return {"total": 0} kinds = [r.get("jump_kind", "none") for r in recs] none_n = sum(1 for k in kinds if k == "none") live_n = sum(1 for k in kinds if k == "liveness") inter = [r for r in recs if r.get("jump_kind") in ("reach", "transition", "value")] ni = len(inter) or 1 d1 = sum(1 for r in inter if int(r.get("depth", 0)) >= 1) d2 = sum(1 for r in inter if int(r.get("depth", 0)) >= 2) val = sum(1 for r in inter if r.get("jump_kind") == "value") vlm = [r for r in recs if r["test"].endswith("_vlm")] fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS) vlm_share = len(vlm) / n
def line(label, got, need, kind): ok = got >= need if kind == "min" else got <= need return ok, (f" [{'ok ' if ok else 'GAP'}] {label}: {got:.0%} " f"({'>=' if kind == 'min' else '<='} {need:.0%})")
lo, hi = q["vlm_share_min"], q["vlm_share_max"] vlm_ok = lo <= vlm_share <= hi if vlm_share < lo: # each added vlm record also grows the denominator: (v+x)/(n+x) >= lo need_more = math.ceil((lo * n - len(vlm)) / (1 - lo)) vlm_hint = (f"under budget by ~{max(1, need_more)} record(s) — allocate more " f"per lane NEXT run; do not re-run to chase it") elif vlm_share > hi: vlm_hint = "over budget — allocate fewer per lane next run" else: vlm_hint = "in budget" vlm_msg = (f" [{'ok ' if vlm_ok else 'GAP'}] VLM BUDGET vlm/total: " f"{len(vlm)}/{n} = {vlm_share:.0%} (target {lo:.0%}-{hi:.0%}) " f"— {vlm_hint}")
checks = [ line("existence(none)/all", none_n / n, q["existence_max"], "max"), line("interactive/all", len(inter) / n, q["interactive_min"], "min"), line("depth>=1 /interactive", d1 / ni, q["depth_ge1_min"], "min"), line("depth>=2 /interactive", d2 / ni, q["depth_ge2_min"], "min"), line("value(tier3)/interactive", val / ni, q["value_min"], "min"), (vlm_ok, vlm_msg), line("vlm fine-grained/vlm", fine / (len(vlm) or 1), q["vlm_fine_min"], "min"), ] print(f"[and_audit] {results_dir} total={n} interactive={len(inter)} " f"none={none_n} liveness={live_n} depth>=1={d1} depth>=2={d2} " f"value={val} vlm={len(vlm)} vlm_fine={fine}") if backfilled: print(f" [!!!] {len(backfilled)} record(s) never reached their assertion " f"(back-filled as failures) — excluded from the ratios above; the " f"100%-pass gate on the original app must catch these") for _ok, msg in checks: print(msg) passed = all(ok for ok, _ in checks) print("[and_audit] " + ("ALL TARGETS MET" if passed else "some targets below — this is a REPORT, not a task: finalize now and fix " "the shortfall in the NEXT run's plan. Re-running the suite to move these " "numbers costs hours and changes nothing about the app under test")) return {"total": n, "interactive": len(inter), "none": none_n, "liveness": live_n, "depth_ge1": d1, "depth_ge2": d2, "value": val, "vlm": len(vlm), "vlm_fine": fine, "vlm_share": round(vlm_share, 4), "backfilled": len(backfilled), "passed": passed, "checks": [m for _o, m in checks]}
def and_lint(results_dir: str = "") -> list[str]: """Flag weak or inconsistent DECLARATIONS.""" results_dir = results_dir or RESULTS_DIR issues, names = [], set() for r in _load_all(results_dir): jk, nm = r.get("jump_kind", "none"), r.get("test", "?") if nm in names: issues.append(f"{nm}: duplicate record name (drifts the denominator)") names.add(nm) if jk not in JUMP_KINDS: issues.append(f"{nm}: unknown jump_kind {jk!r}") if jk in ("reach", "transition", "value") and not str(r.get("expect", "")).strip(): issues.append(f"{nm}: jump_kind={jk} but empty expect " f"(name the specific observed target)") if jk == "liveness": issues.append(f"{nm}: liveness is tier1 — assert the app-authored effect instead") if int(r.get("depth", 0)) < 0: issues.append(f"{nm}: negative depth") msg = str(r.get("message", "")) if not r.get("passed") and not msg.startswith(FAIL_PREFIXES): issues.append(f"{nm}: failure message must start with one of " f"{'/'.join(FAIL_PREFIXES)} (got {msg[:40]!r})") if nm.endswith("_vlm") and not r.get("tag") and not r.get("backfilled"): issues.append(f"{nm}: VLM record has no tag " f"(color|shape|position|size|layout|content)") if issues: print(f"[and_lint] {len(issues)} issue(s):") for i in issues: print(" - " + i) else: print("[and_lint] no issues") return issues
# Non-portable source patterns: they pass on the ORIGINAL app and break on the# RECREATION (different package, different install path). Each is a hard defect._BAD_SOURCE_PATTERNS = [ (r"""["'][a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*){2,}["']""", "hardcodes a package name; use the module-level PACKAGE (argv[1]) — the " "recreation's package differs", ("android.", "androidx.", "java.", "javax.", "com.android.adbkeyboard", "ca.zgrs.clipper", "android.intent.", "com.google.android.inputmethod")), (r"""["'][^"']*\.apk["']|clean\.apk""", "names an APK path; the test must never install or locate the app", ()), (r"/data/data/|/sdcard/Android/data/", "uses a per-package data path, which breaks when the recreation's package " "differs; drive state through the GUI", ()), (r"\btap\(\s*\d{2,}\s*,\s*\d{2,}", "taps a hardcoded pixel coordinate; derive it from a node's _center or " "get_screen_info()", ()), (r"\bpm\s+grant\b|\bappops\s+set\b|\bsettings\s+put\b|\bcontent\s+insert\b", "seeds state outside the GUI; the recreation may not honor it — drive the " "same state through the UI", ()), (r"am\s+start\s+-n\s", "deep-links straight to a component: not portable, and not navigation " "(it cannot back a depth claim)", ()), (r"emulator-\d{4}|127\.0\.0\.1:\d{4}", "hardcodes a device serial; use the module-level DEVICE", ()),]
def and_lint_sources(testgen_dir: str = "") -> list[str]: """Scan authored test/helper .py for NON-PORTABLE patterns and for kit API drift. A clean result means the suite will actually drive the recreation, not just the original.""" testgen_dir = testgen_dir or RESULTS_DIR kit_base = os.path.basename(__file__) py = [p for p in (glob.glob(os.path.join(testgen_dir, "*.py")) + glob.glob(os.path.join(testgen_dir, "tests", "*.py"))) if os.path.basename(p) != kit_base] kit_names = set(globals().keys()) # A sample file the app is supposed to OPEN. Testgen and eval run on DIFFERENT # emulators, so naming one without pushing it means it only ever existed # because someone put it there by hand while exploring. _DEV_PATH_RE = re.compile(r"/sdcard/|/storage/emulated/|\bDCIM\b", re.I) _DOC_RE = re.compile( r"""["'][^"']*\.(?:pdf|epub|mobi|djvu|zim|mp3|mp4|mkv|wav|ogg)["']""", re.I) _fix_files = [f for f in glob.glob(os.path.join(testgen_dir, "fixtures", "**"), recursive=True) if os.path.isfile(f)] issues = [] srcs = {} for p in py: try: srcs[p] = open(p, errors="replace").read() except Exception: continue suite_pushes = any(re.search(r"\b(push_fixtures|fixture_on_device)\b", s) for s in srcs.values()) if _fix_files and not suite_pushes: issues.append( f"fixtures/: {len(_fix_files)} fixture file(s) are authored but NO test " f"calls push_fixtures() — they never reach the device, so every test " f"that opens one records setup_failed. Call it once via run_suite(), " f"or drop the directory.") for p, src in srcs.items(): base = os.path.basename(p) # Strip comments AND docstrings: prose describing the app under test names # files it opens, which is not the same as the code depending on one. scan = re.sub(r'"""[\s\S]*?"""|\'\'\'[\s\S]*?\'\'\'', '""', src) scan = re.sub(r"#[^\n]*", "", scan) # adb is called argv-style — adb_shell("am", "start", "-n", x) — so collapse # the quote-comma-quote separators to read those calls as command lines. flat = re.sub(r"""["']\s*,\s*["']""", " ", scan) if not suite_pushes: for ln in scan.splitlines(): m = _DEV_PATH_RE.search(ln) or _DOC_RE.search(ln) if m: issues.append( f"{base}: needs a sample file on the device " f"[{ln.strip()[:60]}] but the suite never calls " f"push_fixtures() — testgen and eval run on DIFFERENT " f"emulators, so at eval the file is absent. Author the bytes " f"into {os.path.join(testgen_dir, 'fixtures')}/ and let " f"run_suite() push them.") break for pat, why, allow in _BAD_SOURCE_PATTERNS: hit = None for form in (scan, flat): for m in re.finditer(pat, form): cand = m.group(0) if allow and any(a in cand for a in allow): continue hit = cand break if hit: break if hit: issues.append(f"{base}: {why} [{hit[:48]}]") # kit API drift — an import/attr the kit does not define imported: list[str] = [] for m in re.finditer( r"from\s+android_testgen_kit\s+import\s+\(([^)]*)\)", scan, re.S): imported += m.group(1).split(",") for m in re.finditer( r"from\s+android_testgen_kit\s+import\s+([^\n(]+)", scan): imported += m.group(1).split(",") for raw in imported: nm = raw.strip().split(" as ")[0].strip() if nm and nm != "*" and nm not in kit_names: issues.append(f"{base}: imports android_testgen_kit.{nm} which the " f"kit does not define (would ImportError at eval)") for m in re.finditer(r"\bkit\.(\w+)\s*\(", scan): if m.group(1) not in kit_names: issues.append(f"{base}: calls kit.{m.group(1)}() which the kit does " f"not define (would AttributeError at eval)") if issues: print(f"[and_lint_sources] {len(issues)} portability issue(s):") for i in issues: print(" - " + i) else: print("[and_lint_sources] no portability issues") return issues
# ── MEASURED depth cross-check (report-only): does the SOURCE back the DECLARE? ─def _ast_call_name(node) -> str: f = node.func if isinstance(f, ast.Attribute): return f.attr if isinstance(f, ast.Name): return f.id return ""
def _string_locals(fn_node) -> dict[str, str]: """`name = "states_toggle"` inside a test — so record(name, ...) resolves.""" out = {} for n in ast.walk(fn_node): if isinstance(n, ast.Assign) and isinstance(n.value, ast.Constant) \ and isinstance(n.value.value, str): for t in n.targets: if isinstance(t, ast.Name): out[t.id] = n.value.value return out
def _record_names(fn_node) -> list[str]: """Literal record()/vlm_assert() names in this function, preferring the @and_test(expects=(...)) literal when present.""" for dec in getattr(fn_node, "decorator_list", []): if isinstance(dec, ast.Call) and _ast_call_name(dec) == "and_test": for kw in dec.keywords: if kw.arg == "expects" and isinstance(kw.value, (ast.Tuple, ast.List)): return [e.value for e in kw.value.elts if isinstance(e, ast.Constant) and isinstance(e.value, str)] slocals = _string_locals(fn_node) names = [] for n in ast.walk(fn_node): if not (isinstance(n, ast.Call) and _ast_call_name(n) in ("record", "vlm_assert")): continue if not n.args: continue a0 = n.args[0] if isinstance(a0, ast.Constant) and isinstance(a0.value, str): names.append(a0.value) elif isinstance(a0, ast.Name) and a0.id in slocals: names.append(slocals[a0.id]) return names
def _depth_calls(fn_node, local_funcs, budget: int = 2, seen=None): """(fwd, back, reach) depth-family calls, descending `budget` levels into file-local helpers. Cycle-guarded. A LOWER BOUND — never an over-claim.""" seen = seen if seen is not None else set() fwd = bk = rch = 0 relaunch = False for node in ast.walk(fn_node): if not isinstance(node, ast.Call): continue cn = _ast_call_name(node) if DEPTH_FWD_RE.match(cn): fwd += 1 if cn.startswith("and_reach"): rch += 1 elif DEPTH_BACK_RE.match(cn): bk += 1 elif cn in ("launch_app", "restart_app", "force_stop_and_relaunch"): relaunch = True elif budget > 0 and cn in local_funcs and cn not in seen: seen.add(cn) f, b, r = _depth_calls(local_funcs[cn], local_funcs, budget - 1, seen)[:3] fwd, bk, rch = fwd + f, bk + b, rch + r return fwd, bk, rch, relaunch
def and_audit_depth(testgen_dir: str = "", results_dir: str = "") -> list[str]: """MEASURE navigation depth from the test SOURCE (AST) and cross-check the DECLARED depth/jump_kind — so a test cannot just TYPE depth=2. REPORT-ONLY.
Flags a declared depth>=1 or jump_kind="reach" with NO backing call from the depth family and_enter*/and_reach* (directly, in a file-local helper it calls, or anywhere in the module for variable-named records), plus a "reach" that was achieved by relaunching the app rather than navigating. """ testgen_dir = testgen_dir or RESULTS_DIR results_dir = results_dir or testgen_dir files = [p for p in (glob.glob(os.path.join(testgen_dir, "test_android_*.py")) + glob.glob(os.path.join(testgen_dir, "tests", "test_android_*.py")))] per_record, per_module = {}, {} for p in files: try: tree = ast.parse(open(p, errors="replace").read()) except Exception: continue stem = os.path.basename(p)[len("test_android_"):-len(".py")] mod = _MODULE_ALIAS.get(stem, stem) local_funcs = {n.name: n for n in ast.walk(tree) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))} module_backing = any( isinstance(n, ast.Call) and DEPTH_FWD_RE.match(_ast_call_name(n)) for n in ast.walk(tree)) per_module[mod] = {"module_backing": module_backing} for fn in local_funcs.values(): if not fn.name.startswith("test_"): continue fwd, bk, rch, relaunch = _depth_calls(fn, local_funcs) measured = max(0, max((fwd - rch) - bk, 1 if rch >= 1 else 0)) for nm in _record_names(fn): per_record[(mod, nm)] = {"measured_depth": measured, "backing": fwd >= 1, "n_reach": rch, "relaunch": relaunch, "fn": fn.name} issues = [] for r in _load_all(results_dir): nm, jk = r.get("test", "?"), r.get("jump_kind", "none") depth = int(r.get("depth", 0) or 0) strong = depth >= 1 or jk == "reach" hit = None for (mod, rname), v in per_record.items(): if rname == nm: hit = v break if hit is not None: if strong and not hit["backing"]: issues.append(f"{nm} ({hit['fn']}): declared depth={depth}/" f"jump_kind={jk} but NO backing and_enter*/and_reach* " f"call (fake depth)") elif jk == "reach" and hit["n_reach"] == 0: issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but no " f"and_reach* call in its code") elif jk == "reach" and hit["relaunch"]: issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but the function " f"relaunches the app — that is not navigation") elif strong and not any(v.get("module_backing", True) for v in per_module.values()): issues.append(f"{nm}: declared depth={depth}/jump_kind={jk} but no " f"and_enter*/and_reach* call anywhere (fake depth)") if issues: print(f"[and_audit_depth] {len(issues)} fake-depth issue(s) (REPORT-ONLY — " f"fix by adding the and_reach/and_enter you navigated with, or lower " f"the declared depth):") for i in issues: print(" - " + i) else: print("[and_audit_depth] no fake-depth issues " "(declared depth/reach backed by nav calls)") return issues
# ══════════════════════════════════════════════════════════════════════════════# (9) Frozen manifest — the FIXED denominator (ported from RecreationBench v7.2)## Without this, the eval denominator is whatever the candidate happened to emit:# a recreation that crashes a module SHRINKS its own denominator instead of# counting the missing behaviour as failures. The manifest is frozen ONCE per# task from the ORIGINAL app's run and is the denominator authority for every# candidate. Missing tests are injected as `not_run`; extra tests are ignored.# ══════════════════════════════════════════════════════════════════════════════
MANIFEST_NAME = "test_manifest.json"MANIFEST_VERSION = 1
def qualify_name(module: str, test: str) -> str: """`module::test` — two modules may legitimately reuse a short test name.""" return test if "::" in test else f"{module}::{test}"
def _record_status(rec: dict) -> str: if rec.get("status") in ("passed", "failed", "error", "skipped", "not_run"): return rec["status"] return "passed" if rec.get("passed") else "failed"
def _load_by_module(results_dir: str) -> list[tuple[str, dict]]: """Like _load_all but keeps the owning module, so names can be qualified.""" out, seen_files = [], set() for pat in (os.path.join(results_dir, "android_*_eval.json"), os.path.join(results_dir, "eval_results", "android_*_eval.json")): for path in sorted(glob.glob(pat)): base = os.path.basename(path) if base in seen_files: continue seen_files.add(base) try: data = json.load(open(path)) except Exception: continue mod = data.get("module") or base[len("android_"):-len("_eval.json")] for t in data.get("results", []): if isinstance(t, dict) and "test" in t: out.append((str(mod), t)) return out
def _vlm_logged_names(results_dir: str) -> tuple[set[str], bool]: """(names with >=1 logged VLM attempt, whether any log file was found).
Checks the root AND eval_results/ — the agent's self-validation run drives test_verify.sh with --output-dir, which puts the log one level down. """ names, found = set(), False for sub in ("", "eval_results"): p = os.path.join(results_dir, sub, "vlm_assertions.json") if not os.path.isfile(p): continue found = True try: for x in json.load(open(p)): if isinstance(x, dict) and x.get("test_name"): names.add(str(x["test_name"])) except Exception: pass return names, found
def build_manifest(results_dir: str = "", *, task_id: str = "", baseline_model: str = "", out_path: str = "") -> dict: """Freeze the ORIGINAL app's PASSING tests as the denominator.
A test that fails on the original is not a signal about any recreation, so it is moved to `ignored[reason=baseline_fail]` instead of counting against every candidate. This is the only denominator-shrinking mechanism, and it is applied identically to all candidates. """ results_dir = results_dir or RESULTS_DIR logged, log_found = _vlm_logged_names(results_dir) tests, ignored, vlm_assertions = [], [], [] n_unverified = 0 for mod, rec in _load_by_module(results_dir): name = qualify_name(mod, str(rec.get("test", ""))) status = _record_status(rec) entry = {"name": name, "module": mod, "baseline_status": status} is_vlm = name.endswith("_vlm") # A passing _vlm case with no logged attempt never provably reached the # judge on the original app — it must not sit in the VLM denominator that # every recreation is scored against. if is_vlm and status == "passed" and str(rec.get("test", "")) not in logged: n_unverified += 1 ignored.append({"name": name, "module": mod, "reason": "vlm_unverified", "baseline_status": status, "message": "no attempt in vlm_assertions.json — the VLM " "was never provably invoked for this case"}) continue if status == "passed": tests.append(entry) if is_vlm: vlm_assertions.append({"name": name, "module": mod, "tag": rec.get("tag", "")}) else: ignored.append({"name": name, "module": mod, "reason": "baseline_fail", "baseline_status": status, "message": str(rec.get("message", ""))[:300]}) tests.sort(key=lambda t: t["name"]) ignored.sort(key=lambda t: t["name"]) payload = "\n".join(t["name"] for t in tests) pkg = (os.environ.get("ORIG_PACKAGE") or os.environ.get("PACKAGE") or (PACKAGE if "." in PACKAGE else "")) manifest = { "manifest_version": MANIFEST_VERSION, "kit_api_version": KIT_API_VERSION, "task_id": task_id or os.environ.get("INSTANCE_ID", ""), "baseline_model": baseline_model or os.environ.get("MODEL", ""), "baseline_package": pkg, "total": len(tests), "manifest_sha": hashlib.sha256(payload.encode()).hexdigest()[:12], "tests": tests, "ignored": ignored, "vlm_assertions": vlm_assertions, "vlm_total": len(vlm_assertions), "n_vlm_unverified": n_unverified, "vlm_log_found": log_found, } dest = out_path or os.path.join(results_dir, MANIFEST_NAME) tmp = dest + ".tmp" with open(tmp, "w") as f: json.dump(manifest, f, indent=2, ensure_ascii=False) os.replace(tmp, dest) print(f"[build_manifest] {dest} total={manifest['total']} " f"vlm={manifest['vlm_total']} ignored={len(ignored)} " f"sha={manifest['manifest_sha']}") if n_unverified: print(f" [!!!] {n_unverified} passing _vlm case(s) EXCLUDED as " f"vlm_unverified — no attempt logged in vlm_assertions.json" + ("" if log_found else " (no log file found at all — the suite may " "have bypassed the kit's vlm_assert)") + ". They are out of the VLM denominator; fix the VLM path rather " "than accepting the smaller denominator.") base_fail = [i for i in ignored if i["reason"] == "baseline_fail"] if base_fail: print(f" {len(base_fail)} baseline failure(s) excluded from the denominator " f"(they say nothing about a recreation):") for i in base_fail[:20]: print(f" - {i['name']}: {i['message'][:120]}") return manifest
def load_manifest(d: str = "") -> dict | None: """Return the frozen manifest from `d` (or its eval_results/), else None.""" d = d or RESULTS_DIR for p in (os.path.join(d, MANIFEST_NAME), os.path.join(d, "eval_results", MANIFEST_NAME)): if os.path.isfile(p): try: m = json.load(open(p)) except Exception: continue if isinstance(m, dict) and m.get("tests"): return m return None
def score_against_manifest(results_dir: str = "", manifest: dict | None = None) -> dict: """Score a candidate run against the frozen denominator.
denominator = len(manifest["tests"]) regardless of what the candidate emitted. A manifest test the candidate never reported is injected as `not_run` (a non-pass); a test the candidate invented is excluded. A module that crashed on import therefore scores 0/full instead of vanishing. """ results_dir = results_dir or RESULTS_DIR manifest = manifest or load_manifest(results_dir) if not manifest: return {} expected = {t["name"]: t for t in manifest["tests"]} got = {} for mod, rec in _load_by_module(results_dir): got[qualify_name(mod, str(rec.get("test", "")))] = rec
per_test, by_module = {}, {} injected = 0 for name, meta in expected.items(): rec = got.get(name) if rec is None: status, msg = "not_run", "not_run: absent from the candidate's output" injected += 1 else: status, msg = _record_status(rec), str(rec.get("message", "")) per_test[name] = {"status": status, "message": msg[:300]} m = by_module.setdefault(meta.get("module", "?"), {"total": 0, "passed": 0, "not_run": 0}) m["total"] += 1 m["passed"] += status == "passed" m["not_run"] += status == "not_run"
unexpected = sorted(set(got) - set(expected)) total = len(expected) passed = sum(1 for v in per_test.values() if v["status"] == "passed") vlm_names = {a["name"] for a in manifest.get("vlm_assertions", [])} vlm_total = len(vlm_names) vlm_passed = sum(1 for n in vlm_names if per_test.get(n, {}).get("status") == "passed") rule_total = total - vlm_total rule_passed = passed - vlm_passed for m in by_module.values(): m["pass_rate"] = round(m["passed"] / m["total"], 4) if m["total"] else 0.0
out = { "scored_against": "manifest", "manifest_sha": manifest.get("manifest_sha", ""), "manifest_total": total, "total": total, "passed": passed, "pass_rate": round(passed / total, 4) if total else 0.0, "n_injected_not_run": injected, "n_unexpected": len(unexpected), "unexpected": unexpected[:50], "rule": {"total": rule_total, "passed": rule_passed, "pass_rate": round(rule_passed / rule_total, 4) if rule_total else 0.0}, "vlm": {"total": vlm_total, "passed": vlm_passed, "pass_rate": round(vlm_passed / vlm_total, 4) if vlm_total else 0.0}, "by_module": by_module, "per_test": per_test, } print(f"[score_against_manifest] sha={out['manifest_sha']} " f"{passed}/{total} = {out['pass_rate']:.4f} " f"(injected_not_run={injected} unexpected={len(unexpected)}) " f"rule={rule_passed}/{rule_total} vlm={vlm_passed}/{vlm_total}") return out
if __name__ == "__main__": _fns = {"audit": and_audit, "lint": and_lint, "lint_sources": and_lint_sources, "build_manifest": build_manifest} _argv = sys.argv[1:] if _argv[:1] == ["audit_depth"] and len(_argv) >= 2: and_audit_depth(_argv[1], _argv[2] if len(_argv) >= 3 else "") elif _argv[:1] == ["score"] and len(_argv) >= 2: _m = load_manifest(_argv[2]) if len(_argv) >= 3 else load_manifest(_argv[1]) _out = score_against_manifest(_argv[1], _m) if not _out: print("no manifest found — cannot score against a fixed denominator", file=sys.stderr) sys.exit(2) print(json.dumps(_out, ensure_ascii=False)) elif len(_argv) >= 2 and _argv[0] in _fns: _fns[_argv[0]](_argv[1]) else: print("usage: android_testgen_kit.py {audit|lint|lint_sources|build_manifest} <dir>\n" " android_testgen_kit.py audit_depth <testgen_dir> [results_dir]\n" " android_testgen_kit.py score <results_dir> [manifest_dir]")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196{ "module": "text", "total": 18, "passed": 18, "failed": 0, "pass_rate": 1.0, "rule": { "total": 16, "passed": 16, "failed": 0, "pass_rate": 1.0 }, "vlm": { "total": 2, "passed": 2, "failed": 0, "pass_rate": 1.0 }, "vlm_ratio": 0.125, "audit": { "kit_api_version": 1, "existence": 12, "liveness": 0, "interactive": 6, "depth_ge1": 5, "depth_ge2": 2, "value": 0, "vlm_fine": 2 }, "results": [ { "test": "text_points_updates_on_merge", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "points text '0' -> '4' after a scoring move" }, { "test": "text_record_reflects_best", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "record text '0' -> '4' (== points) after play" }, { "test": "text_points_resets_to_zero", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "points text '4' -> '0' after tapping restart" }, { "test": "text_game_header_labels", "passed": true, "message": "", "depth": 1, "jump_kind": "none", "tier": 0, "expect": "exact labels 'Points' and 'Record' shown on GameActivity" }, { "test": "text_mode_label_pages_4to5", "passed": true, "message": "", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "mode label text '4x4' -> '5x5' after btn_next" }, { "test": "text_settings_titles", "passed": true, "message": "", "depth": 1, "jump_kind": "none", "tier": 0, "expect": "titles 'Settings','Select theme','Activate Animation','Activate Screen Lock','Select Color Scheme' all present" }, { "test": "text_theme_summary", "passed": true, "message": "", "depth": 1, "jump_kind": "none", "tier": 0, "expect": "'Select theme' summary text == 'System'" }, { "test": "text_color_scheme_summary", "passed": true, "message": "", "depth": 1, "jump_kind": "none", "tier": 0, "expect": "'Select Color Scheme' summary text == 'Default'" }, { "test": "text_stats_labels", "passed": true, "message": "", "depth": 1, "jump_kind": "none", "tier": 0, "expect": "all 10 stat labels ('Highest Number'..'Right') present exactly" }, { "test": "text_stats_playing_time_format", "passed": true, "message": "", "depth": 1, "jump_kind": "none", "tier": 0, "expect": "time_played1 renders like '0.00 h' (a decimal followed by ' h')" }, { "test": "text_stats_tab_labels", "passed": true, "message": "", "depth": 1, "jump_kind": "none", "tier": 0, "expect": "tab texts exactly '4X4','5X5','6X6','7X7' (uppercase)" }, { "test": "text_help_faq_titles", "passed": true, "message": "", "depth": 1, "jump_kind": "none", "tier": 0, "expect": "FAQ titles incl. 'What is Privacy Friendly App 2048?' present" }, { "test": "text_help_expansion_reveals_body", "passed": true, "message": "", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "body '...privacy friendly version of the well-known original game 2048' appears only after the row is expanded" }, { "test": "text_tutorial_slide1", "passed": true, "message": "", "depth": 1, "jump_kind": "none", "tier": 0, "expect": "slide 1 title 'Welcome!' and body 'In the following slides you will learn how to play the Game 2048.'" }, { "test": "text_tutorial_illustration_vlm", "passed": true, "message": "VLM: Q='Is a large white '2048' shown drawn inside a grid/hash pattern in the centre of the screen?' A=YES expect=YES", "depth": 1, "jump_kind": "none", "tier": 0, "expect": "VLM YES: Is a large white '2048' shown drawn inside a grid/hash pattern in the centre of the screen?", "tag": "shape" }, { "test": "text_tutorial_next_advances_title", "passed": true, "message": "", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "slide title 'Welcome!' -> 'Learn how to move the numbers!' after tapping NEXT" }, { "test": "text_about_labels", "passed": true, "message": "", "depth": 1, "jump_kind": "none", "tier": 0, "expect": "labels 'Version:'/'Authors:', authors 'Saskia Jacob and Julian Wadephul', links 'SECUSO-Website'/'Github-Repo' all present" }, { "test": "text_game_icon_controls_vlm", "passed": true, "message": "VLM: Q='Are there two dark rounded-square icon buttons below the 'Points' and 'Record' labels — a curved undo arrow on the left and a circular refresh/restart arrow on the right?' A=YES expect=YES", "depth": 1, "jump_kind": "none", "tier": 0, "expect": "VLM YES: Are there two dark rounded-square icon buttons below the 'Points' and 'Record' labels — a curved undo arrow on the left and a circular refresh/restart arrow on the right?", "tag": "shape" } ]}1pytest_plugins = ["rb_unify.pytest_rb", "rb_unify.android_bridge"]12pytestpillow1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075#!/usr/bin/env python3"""COMPUTATION lane — Privacy Friendly 2048.
Owns the game's CORE MATH: the input->output transform of a directional move.This lane is the SOLE OWNER of jump_kind="value": every test drives a TRIGGER(a DPAD move / restart / undo) and asserts a SPECIFIC numeric value or count thatthe ORIGINAL app produced — never a value computed from the source.
The initial 2-tile seed and every spawned tile are RANDOM (a new tile is 2 withp=0.9, else 4; its cell is random), so NO absolute point total is hardcoded.Instead every assertion is a read-before / act / read-after DELTA or multisetrelationship that is deterministic regardless of the RNG, and that a shell whichdoes not implement 2048's merge rule cannot satisfy.
GROUND TRUTH — all OBSERVED on the running original before writing (live probing): * Fresh new game (4x4): EXACTLY 2 numeric tiles; points TextView == "0"; undoButton ABSENT. (observed seed [2,4], points 0) * Each non-empty tile is a Button whose text is its value ("2","4","8",...), so every tile value + the score is read straight from the view tree. * MERGE MATH — from GameActivity.handleSwipe*: on a move, `points += (merged value)` for every pair that collapses; then addNumber() spawns ONE tile iff the board changed. Confirmed live, e.g. [2,2,2,8,8] --UP--> [2,2,2,2,16], points delta 16 (the 8+8 merge). * MERGE CONSERVES THE TILE SUM: a+a -> 2a, so after any EFFECTIVE move sum(tiles_after) - sum(tiles_before) is exactly the new tile's value, i.e. it is in {2, 4}. Verified on many moves (sumdelta only ever 0/2/4). * NEW-TILE-PER-MOVE: an effective move adds exactly one tile, so merges = count_before + 1 - count_after. merges==0 => a pure slide with points delta 0; merges>=1 => points delta > 0 and EVEN. Verified. * BLOCKED MOVE (direction already exhausted): NOTHING changes — the tile multiset and points are identical before and after, and no tile spawns. A blocked direction is FOUND by probing each of the four keys and reverting any effective probe with undo (undo restores the exact pre-probe board+points — verified [2,2,4,4]/pts 8 restored verbatim). * record TextView == max(points, previous record), updated LIVE, and NEVER decreases. record survives clear_data (it lives in the statistics file), so it is asserted RELATIVE to the value read at game start, never as an absolute. * restartButton: points -> "0", board re-seeded to EXACTLY 2 tiles, undo gone, NO dialog. Verified (tiles [2,2] pts 0 after restart). * undoButton: appears after the first effective move; tapping it returns points to the exact pre-move value and the button disappears. Verified (4 -> 0). * 5x5 mode (page 1 -> new game): the board grid has strictly MORE cells than 4x4 (Button nodes 29 vs 20), while a fresh 5x5 still seeds exactly 2 tiles.
Failure messages use the taxonomy: setup_failed: / feature_missing: /behavior_wrong:. Every game test crosses Main -> Game (depth=1), backed by theand_enter_game() helper (an and_enter*/and_reach* member) so the depth is real.
VLM BUDGET (exactly 2, both fine-grained): the tile positions/counts and thescore are all dump-readable, so VLM is spent only on genuinely RENDERED layout —the near-empty two-tile grid after restart (position) and the visibly larger 5x5grid vs 4x4 (size). Everything else stays a rule assertion."""import os, sysfrom collections import Countersys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from android_testgen_kit import * # noqa: F403,F401
# ── shared helpers ──────────────────────────────────────────────────────────────
def _boot(): """Clean, package-agnostic entry: force a fresh process, reach the foreground, dismiss the first-run tutorial if (and only if) it appears.""" restart_app() wait_for_foreground(15) _skip_tutorial()
def _skip_tutorial(): n = ui() if node_by_id(n, "btn_skip") or find_node_ci(n, "SKIP"): tap_text(ui(), "SKIP") settle("tap")
def _points(nodes=None): """Current score as an int, or None when the points view is absent.""" n = node_by_id(nodes if nodes is not None else ui(), "points") if n and n.get("text", "").strip().lstrip("-").isdigit(): return int(n["text"].strip()) return None
def _record(nodes=None): """Current best (record) score as an int, or None.""" n = node_by_id(nodes if nodes is not None else ui(), "record") if n and n.get("text", "").strip().lstrip("-").isdigit(): return int(n["text"].strip()) return None
def _tiles(nodes=None): """Sorted list of on-board tile values (each tile is a numeric Button).""" nodes = nodes if nodes is not None else ui() return sorted(int(b["text"]) for b in find_by_class(nodes, "Button") if b.get("text", "").strip().isdigit())
def _cell_count(nodes=None): """Total Button nodes on the game screen (background cells + tiles + toolbar icons). The background grid is one Button per cell, so this scales with n*n and lets a 5x5 board be told apart from a 4x4 one without reading any pixel.""" nodes = nodes if nodes is not None else ui() return len(find_by_class(nodes, "Button"))
def and_enter_game(nodes=None): """Tap button_newGame and CONFIRM the game surface appeared (points view or the board container), counting one crossed surface. Backs depth>=1 for every game test. Returns True on success.""" nodes = nodes if nodes is not None else ui() ng = node_by_id(nodes, "button_newGame") if not ng or not tap_node(ng): return False settle("tap") fresh = ui() if node_by_id(fresh, "points") is None and node_by_id(fresh, "number_field") is None: return False and_enter("game") return True
def _go_to_mode(index): """Page the Main ViewPager to page `index` (0=4x4, 1=5x5, ...). btn_prev is absent on page 0 and btn_next absent on the last page — deterministic stops.""" for _ in range(6): # rewind to page 0 p = node_by_id(ui(), "btn_prev") if not p: break tap_node(p) for _ in range(index): # advance to target nx = node_by_id(ui(), "btn_next") if not nx: break tap_node(nx)
def _tap_restart(): r = node_by_id(ui(), "restartButton") return tap_node(r) if r else False
def _tap_undo(): u = node_by_id(ui(), "undoButton") return tap_node(u) if u else False
_DIRS = ["KEYCODE_DPAD_LEFT", "KEYCODE_DPAD_UP", "KEYCODE_DPAD_RIGHT", "KEYCODE_DPAD_DOWN"]
def _move(key): """Perform one DPAD move and settle so the next ui() reflects the result.""" press_key(key) settle("tap")
def _first_effective_move(max_moves=16): """Cycle the four directions until one CHANGES the board. Returns (tiles_before, points_before, key, tiles_after, points_after) for that move, or None if nothing was effective within the cap (should not happen on a fresh board where at least one direction always moves).""" for i in range(max_moves): bt, bp = _tiles(), _points() key = _DIRS[i % 4] _move(key) at, ap = _tiles(), _points() if at != bt: return bt, bp, key, at, ap return None
def _first_merge_move(max_moves=24): """Cycle directions until a move MERGES at least one pair (points rise). Returns (points_before, key, points_after) for that move, or None.""" for i in range(max_moves): bt, bp = _tiles(), _points() if bp is None: return None key = _DIRS[i % 4] _move(key) at, ap = _tiles(), _points() if ap is not None and ap > bp: return bp, key, ap return None
def _play_effective(n): """Drive up to `n` EFFECTIVE moves (skipping blocked directions), returning how many landed. Used to grow the board / accumulate score deterministically.""" landed = 0 i = 0 while landed < n and i < n * 6: bt = _tiles() _move(_DIRS[i % 4]) if _tiles() != bt: landed += 1 i += 1 return landed
def _find_blocked_direction(rounds=4): """Find a direction that is a NO-OP on the current board and return the before/after reads proving it. A blocked direction always exists on a partly filled board; if all four are effective this grows the board (one effective move) and retries, up to `rounds`. Each effective PROBE is reverted with undo (undo restores the exact pre-probe tiles + points), so the search leaves the board on the state from which the returned direction is blocked.
Returns (key, tiles_before, tiles_after, points_before, points_after) or None. """ for _ in range(rounds): for d in _DIRS: tb, pb = _tiles(), _points() _move(d) ta, pa = _tiles(), _points() if Counter(ta) == Counter(tb): return d, tb, ta, pb, pa # effective probe: revert it so the next candidate starts unchanged if node_by_id(ui(), "undoButton") is not None: _tap_undo() settle("tap") if Counter(_tiles()) != Counter(tb) or _points() != pb: # undo did not restore cleanly — accept this new state and keep # probing from here rather than corrupting the search pass # no blocked direction under this board: make one effective move to change # the configuration, then try again _play_effective(1) return None
# ════════════════════════════════════════════���═════════════════════════════════# 1. Fresh seed — exactly 2 tiles and points == 0# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_fresh_seed_two_tiles",))def test_fresh_seed_two_tiles(): """A brand-new 4x4 game seeds EXACTLY two numeric tiles and shows points "0". The count is deterministic even though the two tile VALUES are random.""" _boot() _go_to_mode(0) if not and_enter_game(): record("computation_fresh_seed_two_tiles", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="value", expect="2 tiles and points 0 on a fresh board") return n = ui() tiles = _tiles(n) pts = _points(n) ok = len(tiles) == 2 and pts == 0 record("computation_fresh_seed_two_tiles", ok, "" if ok else f"behavior_wrong: fresh board has tiles={tiles} points={pts}, " f"expected 2 tiles and points 0", depth=1, jump_kind="value", expect="fresh game: exactly 2 numeric tiles and points == 0")
# ══════════════════════════════════════════════════════════════════════════════# 2. Merge conserves the tile sum — sum delta is exactly the new tile (2 or 4)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_effective_move_sum_delta",))def test_effective_move_conserves_sum(): """The single most RNG-robust value law of 2048: a merge replaces a+a with 2a, so after ANY effective move the total tile sum rises by exactly the one newly spawned tile's value -> sum_after - sum_before is in {2, 4}. Asserted across several effective moves; a recreation that mis-sums merges or spawns the wrong tile breaks this immediately.""" _boot() _go_to_mode(0) if not and_enter_game(): record("computation_effective_move_sum_delta", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="value", expect="sum delta in {2,4} per effective move") return checked = 0 bad = None i = 0 while checked < 4 and i < 30: bt = _tiles() bs = sum(bt) _move(_DIRS[i % 4]) at = _tiles() i += 1 if at == bt: continue # blocked; not an effective move delta = sum(at) - bs checked += 1 if delta not in (2, 4): bad = (bt, at, delta) break ok = checked >= 3 and bad is None record("computation_effective_move_sum_delta", ok, "" if ok else (f"behavior_wrong: sum delta {bad[2]} not in {{2,4}} " f"(before={bad[0]} after={bad[1]})" if bad else f"setup_failed: only {checked} effective moves observed"), depth=1, jump_kind="value", expect="each effective move increases the tile sum by exactly 2 or 4")
# ══════════════════════════════════════════════════════════════════════════════# 3. New-tile-per-move — a pure slide (no merge) adds exactly ONE tile# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_slide_adds_one_tile",))def test_slide_adds_one_tile(): """When an effective move performs NO merge, the tile count rises by exactly 1 (the spawned tile). A pure slide is the case where the count grew; on it the spawned value (sum delta) must be 2 or 4.""" _boot() _go_to_mode(0) if not and_enter_game(): record("computation_slide_adds_one_tile", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="value", expect="a no-merge move adds exactly one tile") return found = False ok = True observed = None i = 0 while not found and i < 30: bt = _tiles() bc = len(bt) _move(_DIRS[i % 4]) at = _tiles() ac = len(at) i += 1 if at == bt: continue if ac == bc + 1: # a pure slide: spawned a tile found = True spawned = sum(at) - sum(bt) ok = spawned in (2, 4) observed = (bt, at, spawned) record("computation_slide_adds_one_tile", found and ok, "" if (found and ok) else ( f"behavior_wrong: slide spawned value {observed[2]} not in {{2,4}} " f"(before={observed[0]} after={observed[1]})" if found else "setup_failed: no pure-slide (count+1) move observed"), depth=1, jump_kind="value", expect="a no-merge move raises tile count by 1, spawning a 2 or a 4")
# ══════════════════════════════════════════════════════════════════════════════# 4. Merge move scores — points delta is positive and even, sum still conserved# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_merge_scores_points",))def test_merge_move_scores_points(): """Drive moves until one MERGES a pair (the tile count does NOT rise, so cells collapsed). On that move points MUST rise by a positive even amount (a sum of doubled tiles), while the tile sum still only rises by the one new tile (2/4). A shell that renders tiles but never adds merge points scores 0 here.""" _boot() _go_to_mode(0) if not and_enter_game(): record("computation_merge_scores_points", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="value", expect="a merge raises points by a positive even delta") return hit = None i = 0 while hit is None and i < 40: bt, bp = _tiles(), _points() bc, bs = len(bt), sum(bt) _move(_DIRS[i % 4]) at, ap = _tiles(), _points() ac, asum = len(at), sum(at) i += 1 if at == bt or bp is None or ap is None: continue merges = bc + 1 - ac # effective move adds 1 tile if merges >= 1: # cells collapsed => a merge dp = ap - bp hit = (bt, at, dp, merges, asum - bs) break ok = hit is not None and hit[2] > 0 and hit[2] % 2 == 0 and hit[4] in (2, 4) record("computation_merge_scores_points", ok, "" if ok else (f"behavior_wrong: merge move points delta={hit[2]} " f"(merges={hit[3]}, sumdelta={hit[4]}, before={hit[0]} " f"after={hit[1]})" if hit else "setup_failed: no merge move observed within cap"), depth=1, jump_kind="value", expect="a merge adds a positive even points delta; tile sum grows by 2/4")
# ══════════════════════════════════════════════════════════════════════════════# 5. Single-pair merge scores exactly twice the merged tile value# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_merge_pair_value",))def test_merge_pair_scores_its_sum(): """A SINGLE-pair merge scores exactly the merged value. We isolate a move that collapses exactly one pair (merges==1) and verify the points delta equals 2 * (a value that was on the board before), i.e. dp is twice an existing tile value and dp >= 4.""" _boot() _go_to_mode(0) if not and_enter_game(): record("computation_merge_pair_value", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="value", expect="a single-pair merge scores 2*value (>=4)") return hit = None i = 0 while hit is None and i < 48: bt, bp = _tiles(), _points() bc = len(bt) _move(_DIRS[i % 4]) at, ap = _tiles(), _points() ac = len(at) i += 1 if at == bt or bp is None or ap is None: continue merges = bc + 1 - ac if merges == 1: dp = ap - bp # the collapsed value v had two copies before; dp must equal 2v for a v # present on the pre-move board. doubled_present = dp in [2 * v for v in set(bt)] hit = (bt, at, dp, doubled_present) break ok = hit is not None and hit[2] >= 4 and hit[2] % 2 == 0 and hit[3] record("computation_merge_pair_value", ok, "" if ok else (f"behavior_wrong: single-pair merge delta={hit[2]} is not " f"2*(an on-board value) (before={hit[0]} after={hit[1]})" if hit else "setup_failed: no single-pair merge observed"), depth=1, jump_kind="value", expect="single-pair merge scores exactly twice the merged tile value")
# ══════════════════════════════════════════════════════════════════════════════# 6. Blocked move — nothing changes (multiset AND points identical)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_blocked_move_no_change",))def test_blocked_move_no_change(): """Find a direction that is already exhausted, then press it: the move is a NO-OP -> the tile multiset and points are byte-identical before and after. This is the negative arm: the answer (a change) must be ABSENT. The blocked direction is discovered by probing (any effective probe is reverted with undo), so this is deterministic regardless of the random board.""" _boot() _go_to_mode(0) if not and_enter_game(): record("computation_blocked_move_no_change", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="value", expect="a blocked move changes nothing") return _play_effective(3) # grow so a blocked dir exists blocked = _find_blocked_direction() if blocked is None: record("computation_blocked_move_no_change", False, "setup_failed: no blocked direction found to probe", depth=1, jump_kind="value", expect="a blocked move changes nothing") return key, tb, ta, pb, pa = blocked ok = Counter(tb) == Counter(ta) and pb == pa and pb is not None record("computation_blocked_move_no_change", ok, "" if ok else f"behavior_wrong: blocked {key[-4:]} changed state " f"(tiles {tb}->{ta}, points {pb}->{pa})", depth=1, jump_kind="value", expect="a blocked move leaves the tile multiset and points identical")
# ══════════════════════════════════════════════════════════════════════════════# 7. Blocked move spawns NO tile (count invariance for the negative case)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_blocked_move_no_new_tile",))def test_blocked_move_no_new_tile(): """The counterpart to the new-tile-per-move law: a blocked move must add NO tile. We find an exhausted direction and confirm the tile COUNT is unchanged across it. This discriminates a recreation that spawns a tile on EVERY key regardless of whether the board moved.""" _boot() _go_to_mode(0) if not and_enter_game(): record("computation_blocked_move_no_new_tile", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="value", expect="a blocked move adds no tile") return _play_effective(3) blocked = _find_blocked_direction() if blocked is None: record("computation_blocked_move_no_new_tile", False, "setup_failed: no blocked direction found to probe", depth=1, jump_kind="value", expect="a blocked move adds no tile") return key, tb, ta, _pb, _pa = blocked ok = len(tb) == len(ta) record("computation_blocked_move_no_new_tile", ok, "" if ok else f"behavior_wrong: blocked {key[-4:]} changed tile count " f"{len(tb)}->{len(ta)} (a tile was spawned on a no-op move)", depth=1, jump_kind="value", expect="a blocked move leaves the tile count unchanged (no new tile)")
# ══════════════════════════════════════════════════════════════════════════════# 8. record == max(points, starting record) after scoring beyond it# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_record_is_max",))def test_record_equals_max(): """record is the running maximum of the score. Read the record at game start (it may be non-zero, persisted from earlier play), then play until points strictly EXCEED it: at that instant record must equal points. record is asserted RELATIVE to its observed start value, never as an absolute.""" _boot() _go_to_mode(0) if not and_enter_game(): record("computation_record_is_max", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="value", expect="record tracks points once points exceed it") return start_rec = _record() if start_rec is None: record("computation_record_is_max", False, "setup_failed: could not read the record view", depth=1, jump_kind="value", expect="record tracks points once points exceed it") return # Alternate directions to accumulate score until points strictly exceed the # record read at game start; at that instant record must have caught up to it. last = None exceeded = False i = 0 while last is None and i < 80: _move(_DIRS[i % 4]) p = _points() or 0 r = _record() or 0 i += 1 if p > start_rec: last = (p, r) exceeded = (r == p) if last is None: record("computation_record_is_max", False, f"setup_failed: points never exceeded the start record {start_rec}", depth=1, jump_kind="value", expect="record == points once points first exceed the old record") return record("computation_record_is_max", exceeded, "" if exceeded else f"behavior_wrong: after points {last[0]} exceeded start " f"record {start_rec}, record was {last[1]} (expected == points)", depth=1, jump_kind="value", expect="record == points at the moment points first exceed the old record")
# ══════════════════════════════════════════════════════════════════════════════# 9. record never decreases across a scoring move# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_record_monotonic",))def test_record_monotonic(): """The record is monotonic non-decreasing: across a whole sequence of moves it only ever rises or holds, never drops — even as points climb. Sampled after each of several moves.""" _boot() _go_to_mode(0) if not and_enter_game(): record("computation_record_monotonic", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="value", expect="record never decreases across moves") return r_prev = _record() if r_prev is None: record("computation_record_monotonic", False, "setup_failed: could not read the record view", depth=1, jump_kind="value", expect="record never decreases across moves") return ok = True drop = None for i in range(12): _move(_DIRS[i % 4]) r = _record() if r is None: continue if r < r_prev: ok = False drop = (r_prev, r) break r_prev = r record("computation_record_monotonic", ok, "" if ok else f"behavior_wrong: record decreased {drop[0]}->{drop[1]}", depth=1, jump_kind="value", expect="record is non-decreasing across a sequence of moves")
# ══════════════════════════════════════════════════════════════════════════════# 10. restart resets points to 0 and re-seeds to exactly 2 tiles# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_restart_resets", "computation_restart_two_tiles_vlm"))def test_restart_resets_points(): """Play until the board has grown (more than 2 tiles and/or points > 0), tap restartButton, then assert points == 0 and EXACTLY 2 numeric tiles remain, with no confirmation dialog. A positive->reset transition asserted by value.""" _boot() _go_to_mode(0) if not and_enter_game(): record("computation_restart_resets", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="value", expect="points 0 and 2 tiles after restart") vlm_assert("computation_restart_two_tiles", "unreachable", RESULTS_DIR, depth=1, jump_kind="value", tag="position") return _play_effective(5) grew = len(_tiles()) > 2 or (_points() or 0) > 0 if not _tap_restart(): record("computation_restart_resets", False, "setup_failed: restartButton not found/tappable", depth=1, jump_kind="value", expect="points 0 and 2 tiles after restart") vlm_assert("computation_restart_two_tiles", "unreachable", RESULTS_DIR, depth=1, jump_kind="value", tag="position") return settle("tap") n = ui() pts = _points(n) tiles = _tiles(n) ok = grew and pts == 0 and len(tiles) == 2 record("computation_restart_resets", ok, "" if ok else f"behavior_wrong: after restart points={pts} tiles={tiles} " f"(grew_before={grew}); expected points 0 and 2 tiles", depth=1, jump_kind="value", expect="restart -> points == 0 and exactly 2 tiles") # VLM: after restart the grid is nearly empty — only two tiles sit on it. vlm_assert("computation_restart_two_tiles", "Does the game grid show exactly two numbered tiles, with every " "other cell empty?", RESULTS_DIR, depth=1, jump_kind="value", tag="position")
# ══════════════════════════════════════════════════════════════════════════════# 11. undo restores the exact pre-move points# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_undo_restores_points",))def test_undo_restores_points(): """Make a move that CHANGES the score, capture the pre-move points, tap undoButton, and assert points return to exactly that pre-move value (and the undo affordance disappears). Deterministic on points regardless of the random tile the move spawned.""" _boot() _go_to_mode(0) if not and_enter_game(): record("computation_undo_restores_points", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="value", expect="points return to the pre-move value after undo") return merge = _first_merge_move() if merge is None: record("computation_undo_restores_points", False, "setup_failed: no scoring move produced within cap", depth=1, jump_kind="value", expect="points return to the pre-move value after undo") return pre_move, _key, post_move = merge had_undo = node_by_id(ui(), "undoButton") is not None _tap_undo() after = _points() undo_gone = node_by_id(ui(), "undoButton") is None ok = had_undo and post_move > pre_move and after == pre_move and undo_gone record("computation_undo_restores_points", ok, "" if ok else f"behavior_wrong: undo did not restore points to {pre_move} " f"(post_move={post_move}, after_undo={after}, " f"undo_present_before={had_undo}, undo_gone_after={undo_gone})", depth=1, jump_kind="value", expect="points return to the pre-move value after undo")
# ══════════════════════════════════════════════════════════════════════════════# 12. undo restores the exact pre-move tile count# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_undo_restores_tile_count",))def test_undo_restores_tile_count(): """Undo reverts the board, so the tile COUNT returns to its pre-move value. We capture the count immediately before an effective move, perform it (count changes), undo, and assert the count matches the pre-move count. (Count, not multiset: the pre-move board already carried a random tile from the prior move, but its COUNT before this move is a fixed number we read.)""" _boot() _go_to_mode(0) if not and_enter_game(): record("computation_undo_restores_tile_count", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="value", expect="tile count returns to pre-move value after undo") return # first make one effective move so the undo button exists, then measure a # SECOND effective move's pre-count (so pre-state is deterministic post-spawn). if _first_effective_move() is None: record("computation_undo_restores_tile_count", False, "setup_failed: no effective first move", depth=1, jump_kind="value", expect="tile count returns to pre-move value after undo") return pre = None moved_to = None i = 0 while pre is None and i < 20: bt = _tiles() bc = len(bt) _move(_DIRS[i % 4]) at = _tiles() i += 1 if at != bt: pre = bc moved_to = len(at) if pre is None: record("computation_undo_restores_tile_count", False, "setup_failed: no second effective move", depth=1, jump_kind="value", expect="tile count returns to pre-move value after undo") return had_undo = node_by_id(ui(), "undoButton") is not None _tap_undo() after = len(_tiles()) ok = had_undo and after == pre record("computation_undo_restores_tile_count", ok, "" if ok else f"behavior_wrong: undo tile count {after} != pre-move {pre} " f"(moved_to={moved_to}, undo_present={had_undo})", depth=1, jump_kind="value", expect="tile count returns to the pre-move count after undo")
# ══════════════════════════════════════════════════════════════════════════════# 13. undo is once-per-move — the delta is applied exactly once# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_undo_once",))def test_undo_applies_once(): """Undo reverts a SINGLE move: after one undo the points sit at the pre-move value and the undo button is gone, so a second undo cannot drive points below that value. Confirms the revert is applied exactly once (not repeatedly).""" _boot() _go_to_mode(0) if not and_enter_game(): record("computation_undo_once", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="value", expect="undo restores once; no double revert") return merge = _first_merge_move() if merge is None: record("computation_undo_once", False, "setup_failed: no scoring move produced", depth=1, jump_kind="value", expect="undo restores once; no double revert") return pre_move, _key, _post = merge _tap_undo() after_first = _points() gone = node_by_id(ui(), "undoButton") is None # attempt a second undo — button should be absent, points must not drop further _tap_undo() after_second = _points() ok = after_first == pre_move and gone and after_second == pre_move record("computation_undo_once", ok, "" if ok else f"behavior_wrong: undo not once-only (pre={pre_move}, " f"after1={after_first}, undo_gone={gone}, after2={after_second})", depth=1, jump_kind="value", expect="one undo restores the pre-move points; a second cannot lower them")
# ══════════════════════════════════════════════════════════════════════════════# 14. Multi-move accumulation — total points equal the summed per-move deltas# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_points_accumulate",))def test_points_accumulate(): """Points accumulate additively: over a run of moves the FINAL score equals the sum of every per-move delta observed along the way (each delta is >= 0). This ties many individual merges into one exact end-to-end total, computed purely from before/after reads — no source arithmetic.""" _boot() _go_to_mode(0) if not and_enter_game(): record("computation_points_accumulate", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="value", expect="final points == sum of per-move deltas") return start = _points() if start is None: record("computation_points_accumulate", False, "setup_failed: could not read points", depth=1, jump_kind="value", expect="final points == sum of per-move deltas") return running = start bad = None for i in range(16): b = _points() _move(_DIRS[i % 4]) a = _points() if a is None or b is None: continue d = a - b if d < 0: bad = (b, a) break running += d final = _points() ok = bad is None and final is not None and final == running and final >= start record("computation_points_accumulate", ok, "" if ok else (f"behavior_wrong: a per-move delta went negative " f"{bad[0]}->{bad[1]}" if bad else f"behavior_wrong: final points {final} != summed deltas {running}"), depth=1, jump_kind="value", expect="final score equals the running sum of non-negative per-move deltas")
# ══════════════════════════════════════════════════════════════════════════════# 15. Merge reduces the count of the merged value (a merge does not grow count)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_merge_collapses_pair",))def test_merge_collapses_pair(): """A merge collapses cells: on a scoring move the total tile count does NOT increase (it stays equal or drops), even though a new tile also spawned. Contrast with a pure slide where the count strictly increases. This asserts the concrete count arithmetic of a merge.""" _boot() _go_to_mode(0) if not and_enter_game(): record("computation_merge_collapses_pair", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="value", expect="a merge move does not raise the tile count") return hit = None i = 0 while hit is None and i < 40: bt, bp = _tiles(), _points() bc = len(bt) _move(_DIRS[i % 4]) at, ap = _tiles(), _points() ac = len(at) i += 1 if at == bt or bp is None or ap is None: continue if ap > bp: # a merge happened hit = (bc, ac, ap - bp) break ok = hit is not None and hit[1] <= hit[0] record("computation_merge_collapses_pair", ok, "" if ok else (f"behavior_wrong: merge (points +{hit[2]}) raised tile " f"count {hit[0]}->{hit[1]}" if hit else "setup_failed: no merge move observed"), depth=1, jump_kind="value", expect="on a scoring (merge) move the tile count does not increase")
# ══════════════════════════════════════════════════════════════════════════════# 16. Two consecutive no-merge slides raise the count by two# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_two_slides_add_two",))def test_two_slides_add_two_tiles(): """Two effective NO-MERGE moves each spawn one tile, so the count rises by exactly 1 on each. We look for two count-increasing moves and assert each raised the count by exactly one.""" _boot() _go_to_mode(0) if not and_enter_game(): record("computation_two_slides_add_two", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="value", expect="two no-merge moves add exactly two tiles") return counts = [] i = 0 start_c = len(_tiles()) while len(counts) < 2 and i < 24: bc = len(_tiles()) _move(_DIRS[i % 4]) ac = len(_tiles()) i += 1 if ac == bc + 1: # a pure slide (spawn, no merge) counts.append((bc, ac)) ok = len(counts) == 2 and counts[0][1] == counts[0][0] + 1 and \ counts[1][1] == counts[1][0] + 1 record("computation_two_slides_add_two", ok, "" if ok else f"behavior_wrong: two slides did not each add one tile " f"(start={start_c}, transitions={counts})", depth=1, jump_kind="value", expect="each of two no-merge moves raises the tile count by exactly one")
# ══════════════════════════════════════════════════════════════════════════════# 17. Restarted game is fresh AND live — a move after restart adds a tile# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_restart_then_move",))def test_restart_then_move_adds_tile(): """After restart the board is a fresh 2-tile seed AND still computes: the very next effective move raises the tile count past 2 (a spawned tile) and points stay >= 0. Confirms the re-seed is a live game, not a frozen snapshot.""" _boot() _go_to_mode(0) if not and_enter_game(): record("computation_restart_then_move", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="value", expect="a move after restart grows the board past 2 tiles") return _play_effective(4) if not _tap_restart(): record("computation_restart_then_move", False, "setup_failed: restartButton not found", depth=1, jump_kind="value", expect="a move after restart grows the board past 2 tiles") return settle("tap") seed = _tiles() grew = False for i in range(10): _move(_DIRS[i % 4]) if len(_tiles()) > 2: grew = True break p = _points() or 0 ok = len(seed) == 2 and grew and p >= 0 record("computation_restart_then_move", ok, "" if ok else f"behavior_wrong: re-seeded game not live " f"(seed_tiles={seed}, grew_past_2={grew}, points={p})", depth=1, jump_kind="value", expect="after restart the seed is 2 tiles and a move grows it past 2")
# ══════════════════════════════════════════════════════════════════════════════# 18. Undo then replay — points can rise again above the reverted value# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_undo_then_replay",))def test_undo_then_replay(): """After an undo returns points to the pre-move value, the game is fully live: subsequent effective moves can raise points again (>= the reverted value). This proves undo restores STATE, not a dead/frozen board.""" _boot() _go_to_mode(0) if not and_enter_game(): record("computation_undo_then_replay", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="value", expect="points can rise again after an undo") return merge = _first_merge_move() if merge is None: record("computation_undo_then_replay", False, "setup_failed: no scoring move produced", depth=1, jump_kind="value", expect="points can rise again after an undo") return pre_move, _k, _post = merge _tap_undo() reverted = _points() if reverted is None: record("computation_undo_then_replay", False, "setup_failed: points unreadable after undo", depth=1, jump_kind="value", expect="points can rise again after an undo") return # play on and try to score again above the reverted value replayed = reverted for i in range(24): _move(_DIRS[i % 4]) p = _points() or 0 if p > reverted: replayed = p break ok = reverted == pre_move and replayed >= reverted record("computation_undo_then_replay", ok, "" if ok else f"behavior_wrong: after undo to {pre_move}, replay points " f"reached {replayed} (expected to rise back to >= {reverted})", depth=1, jump_kind="value", expect="after undo restores points, further moves raise them again")
# ══════════════════════════════════════════════════════════════════════════════# 19. 5x5 mode — a larger grid than 4x4, still seeded with exactly 2 tiles# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_5x5_larger_grid", "computation_5x5_grid_vlm"))def test_5x5_grid_larger(): """Starting a game on the 5x5 page yields a board with strictly MORE cells than 4x4 (the background grid is one Button per cell: observed 29 vs 20), while a fresh 5x5 board still seeds exactly 2 numeric tiles. Confirms mode selection drives the board dimension, and the seed rule is mode-independent.""" _boot() _go_to_mode(0) if not and_enter_game(): record("computation_5x5_larger_grid", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="value", expect="5x5 grid has more cells than 4x4") vlm_assert("computation_5x5_grid", "unreachable", RESULTS_DIR, depth=1, jump_kind="value", tag="size") return cells4 = _cell_count() tiles4 = len(_tiles()) and_back() settle("tap") _go_to_mode(1) if not and_enter_game(): record("computation_5x5_larger_grid", False, "setup_failed: could not start a new 5x5 game", depth=1, jump_kind="value", expect="5x5 grid has more cells than 4x4") vlm_assert("computation_5x5_grid", "unreachable", RESULTS_DIR, depth=1, jump_kind="value", tag="size") return n5 = ui() cells5 = _cell_count(n5) tiles5 = len(_tiles(n5)) ok = cells5 > cells4 and tiles5 == 2 and tiles4 == 2 record("computation_5x5_larger_grid", ok, "" if ok else f"behavior_wrong: 5x5 cells={cells5} not > 4x4 cells={cells4}, " f"or seed tiles wrong (4x4={tiles4}, 5x5={tiles5})", depth=1, jump_kind="value", expect="5x5 board has more cells than 4x4; both seed exactly 2 tiles") # VLM: a 5x5 board is visibly a larger grid (five columns) than the 4x4 default. vlm_assert("computation_5x5_grid", "Is the game board a square grid with five columns and five rows " "of cells (a 5 by 5 grid)?", RESULTS_DIR, depth=1, jump_kind="value", tag="size")
# ══════════════════════════════════════════════════════════════════════════════# 20. Board sum only ever grows by 0/2/4 across a whole run (global conservation)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_sum_growth_bounded",))def test_sum_growth_bounded(): """Global form of the merge-conservation law: across a run of moves the total tile sum increases by 0 (blocked) or exactly 2/4 (one spawn) per step and NEVER jumps by more, so the end sum equals the start sum plus the spawned tiles. We assert every per-step sum delta stays in {0, 2, 4}.""" _boot() _go_to_mode(0) if not and_enter_game(): record("computation_sum_growth_bounded", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="value", expect="every per-move sum delta is in {0,2,4}") return bad = None steps = 0 for i in range(18): bs = sum(_tiles()) _move(_DIRS[i % 4]) asum = sum(_tiles()) d = asum - bs steps += 1 if d not in (0, 2, 4): bad = (bs, asum, d) break ok = bad is None and steps >= 10 record("computation_sum_growth_bounded", ok, "" if ok else (f"behavior_wrong: per-move sum delta {bad[2]} outside {{0,2,4}} " f"(sum {bad[0]}->{bad[1]})" if bad else f"setup_failed: only {steps} moves sampled"), depth=1, jump_kind="value", expect="every per-move tile-sum delta is 0 (blocked) or 2/4 (one spawn)")
TESTS = [ test_fresh_seed_two_tiles, # 1 test_effective_move_conserves_sum, # 2 test_slide_adds_one_tile, # 3 test_merge_move_scores_points, # 4 test_merge_pair_scores_its_sum, # 5 test_blocked_move_no_change, # 6 test_blocked_move_no_new_tile, # 7 test_record_equals_max, # 8 test_record_monotonic, # 9 test_restart_resets_points, # 10 + VLM two-tiles (position) test_undo_restores_points, # 11 test_undo_restores_tile_count, # 12 test_undo_applies_once, # 13 test_points_accumulate, # 14 test_merge_collapses_pair, # 15 test_two_slides_add_two_tiles, # 16 test_restart_then_move_adds_tile, # 17 test_undo_then_replay, # 18 test_5x5_grid_larger, # 19 + VLM 5x5 grid (size) test_sum_growth_bounded, # 20]
if __name__ == "__main__": run_suite(TESTS, "computation")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012#!/usr/bin/env python3"""INTERACTION lane — Privacy Friendly 2048.
Owns EFFECT-BY-CONSEQUENCE on user DATA: multi-step (3+) sequences, multi-recordintegrity, and DATA persistence across process death. The "data" here is the savedgame (board tiles + points), the per-mode statistics rows, and the continue-gameavailability that a saved game creates.
Everything asserted was OBSERVED on the running original (recon.md + live probing).CONTRACTS CONFIRMED empirically on the device before writing: * Game start: points TextView (id points) == "0"; board has EXACTLY 2 numeric tiles; each non-empty tile is a Button whose text is its value; restartButton present; undoButton ABSENT until the first effective move. * A DPAD move that changes the board adds exactly one new tile and (on a merge) adds the merged sum to points. A blocked move changes nothing. * UNDO (undoButton): reverts the last move -> points returns to the pre-move value, and the button disappears (once per move). NOTE: the tile MULTISET is NOT a reliable undo invariant (the pre-move board already carried a random new-tile from the prior move), so undo is asserted on POINTS equality, which is deterministic. Confirmed: merge move points 0->4, undo -> points back to 0. * RESTART (restartButton): points -> "0", board re-seeded to EXACTLY 2 tiles, no dialog. Non-destructive to statistics/records. * PERSISTENCE contract (confirmed all three arms): - graceful back() to Main writes the save (onPause); - kill AFTER back (force_stop_and_relaunch) -> continue ENABLED and restores the EXACT points + tile multiset (48 / [2,4,4,16] restored verbatim); - kill WITHOUT a prior back -> the save is skipped -> continue stays DISABLED (from a clean clear_data() start). This is the discriminating arm: an in-memory-only recreation cannot pass the survive-after-back test. * STATS (StatsActivity, per-mode tab; suffix n: 1=4x4, 2=5x5): after playing 4x4 on a clean baseline, moves_All1/moves_L1 increase from 0, highest_number1 / highest_score1 reflect play, undo_number1 increments after an undo; and the 5x5 tab (suffix 2) stays 0 -> multi-mode integrity. Blocked moves make exact counts nondeterministic, so counts are asserted as >= the clean-baseline floor.
Long-press: 2048 has NO long-press / context-menu feature (verified — tiles are notlong-clickable), so none is invented. The overflow "More options" menu inStatsActivity is the one real context menu; opening it is safe (its single item isdestructive, so it is never tapped)."""import os, syssys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from android_testgen_kit import * # noqa: F403,F401
# ── shared helpers ──────────────────────────────────────────────────────────────
SRC_MAIN = "START NEW GAME" # button_newGame text — Main-only marker
def _boot(): """Clean-but-package-agnostic entry: restart, reach foreground, dismiss a possible first-run tutorial. Tolerates the tutorial being present OR absent.""" restart_app() wait_for_foreground(15) _skip_tutorial()
def _boot_clean(): """clear_data() first for a virgin database (fresh stats / no saved game), then launch and skip the tutorial if it appears.""" clear_data() launch_app() wait_for_foreground(15) _skip_tutorial()
def _skip_tutorial(): n = ui() if node_by_id(n, "btn_skip") or find_node_ci(n, "SKIP"): tap_text(ui(), "SKIP") settle("tap")
def _points(nodes=None): """Current score as an int, or None if the points view is absent.""" n = node_by_id(nodes if nodes is not None else ui(), "points") if n and n.get("text", "").strip().lstrip("-").isdigit(): return int(n["text"].strip()) return None
def _tiles(nodes=None): """Sorted multiset of on-board tile values (each tile is a numeric Button).""" nodes = nodes if nodes is not None else ui() return sorted(int(b["text"]) for b in find_by_class(nodes, "Button") if b.get("text", "").strip().isdigit())
def and_enter_game(nodes=None): """Tap button_newGame and CONFIRM the game surface appeared (board + points), counting one crossed surface. Returns True on success. Backs depth>=1.""" nodes = nodes if nodes is not None else ui() ng = node_by_id(nodes, "button_newGame") if not ng or not tap_node(ng): return False settle("tap") fresh = ui() if node_by_id(fresh, "points") is None and node_by_id(fresh, "number_field") is None: return False and_enter("game") return True
def and_enter_continue(nodes=None): """Tap button_continueGame and CONFIRM the game surface appeared. Backs a depth crossing for the resume half of a persistence sequence.""" nodes = nodes if nodes is not None else ui() cg = node_by_id(nodes, "button_continueGame") if not cg or not tap_node(cg): return False settle("tap") fresh = ui() if node_by_id(fresh, "points") is None and node_by_id(fresh, "number_field") is None: return False and_enter("game_resumed") return True
def and_reach_stats(): """Main -> drawer -> Statistics, PROVING the jump (a tab strip / stat row appeared and the Main-only START NEW GAME vanished). Counts one surface.""" db = find_node(ui(), content_desc="Open navigation drawer") if not db or not tap_node(db): return False settle("tap") item = find_node_ci(ui(), "Statistics") if not item: return False before = and_showing() if not tap_node(item): return False after = and_showing() if not and_reach(before, after, "4x4", SRC_MAIN): # fall back to a weaker confirmation: any per-mode stat row present if node_by_id(ui(), "moves_All1") is None: return False and_enter("statistics") return True
def _stat_int(suffix): """Read a StatsActivity stat value (e.g. 'moves_All1') as an int, else None.""" n = node_by_id(ui(), suffix) if n and n.get("text", "").strip().lstrip("-").isdigit(): return int(n["text"].strip()) return None
def _select_stats_tab(label): """Tap a stats tab by its content-desc (4x4/5x5/6x6/7x7).""" t = find_node(ui(), content_desc=label) if t: tap_node(t) settle("tap")
def _play_moves(n_left_up): """Drive n_left_up * (LEFT,UP) DPAD moves on the current game surface. LEFT+UP reliably produces merges on a fresh 4x4 (verified: reaches points>0 quickly).""" for _ in range(n_left_up): press_key("KEYCODE_DPAD_LEFT") press_key("KEYCODE_DPAD_UP")
def _play_until_points(cap=12): """Alternate LEFT/UP until points>0 (a merge happened) or cap iters. Returns the points reached (int) — deterministic way to force score>0.""" for i in range(cap): press_key("KEYCODE_DPAD_LEFT" if i % 2 == 0 else "KEYCODE_DPAD_UP") p = _points() if p and p > 0: return p return _points() or 0
def _tap_restart(): r = node_by_id(ui(), "restartButton") return tap_node(r) if r else False
def _tap_undo(): u = node_by_id(ui(), "undoButton") return tap_node(u) if u else False
def _go_to_mode(index): """Page the Main ViewPager to page `index` (0=4x4,1=5x5,...). btn_prev is absent on page 0, btn_next absent on the last page — deterministic stops.""" for _ in range(6): # rewind to page 0 p = node_by_id(ui(), "btn_prev") if not p: break tap_node(p) for _ in range(index): # advance to target nx = node_by_id(ui(), "btn_next") if not nx: break tap_node(nx)
# ══════════════════════════════════════════════════════════════════════════════# 1. FLAGSHIP — data survives process death (back saves, kill preserves)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_persist_after_kill", "interaction_persist_board_restored_vlm"))def test_persistence_across_process_death(): """Play -> back (saves) -> kill+relaunch -> continue restores EXACT points and tile multiset. The single most discriminating test: an in-memory-only recreation cannot reproduce the board after the process is killed.""" _boot_clean() _go_to_mode(0) if not and_enter_game(): record("interaction_persist_after_kill", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="transition", expect="game surface") vlm_assert("interaction_persist_board_restored", "unreachable", depth=1, jump_kind="transition", tag="content") return _play_moves(6) P, T = _points(), _tiles() if P is None or not T: record("interaction_persist_after_kill", False, "setup_failed: could not read points/tiles after play", depth=1, jump_kind="transition", expect="game surface") vlm_assert("interaction_persist_board_restored", "unreachable", depth=1, jump_kind="transition", tag="content") return and_back() # to Main -> onPause writes save settle("tap") force_stop_and_relaunch() # process death; file persists wait_for_foreground(15) _skip_tutorial() _go_to_mode(0) resumed = and_enter_continue() P2, T2 = (_points(), _tiles()) if resumed else (None, None) ok = resumed and P2 == P and T2 == T record("interaction_persist_after_kill", ok, "" if ok else f"behavior_wrong: expected points={P} tiles={T}, " f"got points={P2} tiles={T2} after kill+continue", depth=2, jump_kind="transition", expect=f"continue restores points={P} tiles={T} after process death") # VLM: the restored board is a populated grid, not empty vlm_assert("interaction_persist_board_restored", "Does the game board show multiple numbered tiles (a populated " "grid), i.e. it is NOT an empty grid?", depth=2, jump_kind="transition", tag="content")
# ══════════════════════════════════════════════════════════════════════════════# 2. Kill WITHOUT back does not save (the negative arm)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_kill_without_back_not_saved",))def test_kill_without_back_not_saved(): """Clean -> play -> force_stop WITHOUT back -> relaunch: continue is still DISABLED (SIGKILL skips onPause, so nothing was written). Proves the save is tied to a graceful pause, not to merely having played.""" _boot_clean() _go_to_mode(0) cg0 = node_by_id(ui(), "button_continueGame") disabled_before = cg0 is not None and cg0.get("enabled") == "false" if not and_enter_game(): record("interaction_kill_without_back_not_saved", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="transition", expect="continue disabled after kill") return _play_moves(6) played = (_points() or 0) >= 0 and len(_tiles()) >= 2 force_stop_and_relaunch() # NO back first -> not saved wait_for_foreground(15) _skip_tutorial() _go_to_mode(0) cg = node_by_id(ui(), "button_continueGame") disabled_after = cg is not None and cg.get("enabled") == "false" ok = disabled_before and played and disabled_after record("interaction_kill_without_back_not_saved", ok, "" if ok else f"behavior_wrong: continue not disabled after kill " f"without back (before_disabled={disabled_before}, " f"after_disabled={disabled_after})", depth=1, jump_kind="transition", expect="continue DISABLED after play then kill-without-back")
# ══════════════════════════════════════════════════════════════════════════════# 3. Continue availability flips from a saved game (play + back)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_continue_enable_after_play_back",))def test_continue_enables_after_play_and_back(): """Clean -> continue DISABLED -> new game -> a move -> back: continue becomes ENABLED. The saved-game creation is the data consequence (before->after flip).""" _boot_clean() _go_to_mode(0) cg0 = node_by_id(ui(), "button_continueGame") disabled_before = cg0 is not None and cg0.get("enabled") == "false" if not and_enter_game(): record("interaction_continue_enable_after_play_back", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="transition", expect="continue enabled after back") return _play_moves(2) and_back() # to Main -> writes save settle("tap") cg = node_by_id(ui(), "button_continueGame") enabled_after = cg is not None and cg.get("enabled") == "true" ok = disabled_before and enabled_after record("interaction_continue_enable_after_play_back", ok, "" if ok else f"behavior_wrong: continue did not flip disabled->enabled " f"(before_disabled={disabled_before}, " f"after_enabled={enabled_after})", depth=1, jump_kind="transition", expect="continue enabled=true after play then back")
# ══════════════════════════════════════════════════════════════════════════════# 4. Undo reverts the last move's POINTS# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_undo_reverts_points", "interaction_undo_board_reverted_vlm"))def test_undo_reverts_points(): """New game -> make a MERGE move (points rise) -> undo -> points return to the pre-move value. Deterministic on points; also the undo button vanishes.""" _boot_clean() _go_to_mode(0) if not and_enter_game(): record("interaction_undo_reverts_points", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="transition", expect="points reverted by undo") vlm_assert("interaction_undo_board_reverted", "unreachable", depth=1, jump_kind="transition", tag="content") return # find a single move that INCREASES points (a merge); capture the pre-move value prev = _points() or 0 pre_move = None for i in range(14): press_key("KEYCODE_DPAD_LEFT" if i % 2 == 0 else "KEYCODE_DPAD_UP") cur = _points() or 0 if cur > prev: pre_move = prev break prev = cur if pre_move is None: record("interaction_undo_reverts_points", False, "setup_failed: no scoring move produced within cap", depth=1, jump_kind="transition", expect="points reverted by undo") vlm_assert("interaction_undo_board_reverted", "unreachable", depth=1, jump_kind="transition", tag="content") return had_undo = node_by_id(ui(), "undoButton") is not None _tap_undo() after = _points() undo_gone = node_by_id(ui(), "undoButton") is None ok = had_undo and after == pre_move and undo_gone record("interaction_undo_reverts_points", ok, "" if ok else f"behavior_wrong: undo did not restore points to " f"{pre_move} (got {after}, undo_present_before={had_undo}, " f"undo_gone_after={undo_gone})", depth=1, jump_kind="transition", expect=f"points return to {pre_move} after undo") vlm_assert("interaction_undo_board_reverted", "Does the game board still show numbered tiles on the grid after " "the undo (a non-empty board)?", depth=1, jump_kind="transition", tag="content")
# ══════════════════════════════════════════════════════════════════════════════# 5. Undo removes the undoButton affordance (once-per-move) + VLM icon# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_undo_once_per_move", "interaction_undo_icon_visible_vlm"))def test_undo_is_once_per_move(): """undoButton is ABSENT at game start, APPEARS after the first effective move, and is GONE again after a single undo — the once-per-move data affordance.""" _boot_clean() _go_to_mode(0) if not and_enter_game(): record("interaction_undo_once_per_move", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="transition", expect="undo absent->present->absent") vlm_assert("interaction_undo_icon_visible", "unreachable", depth=1, jump_kind="transition", tag="shape") return absent_start = node_by_id(ui(), "undoButton") is None _play_moves(3) present_after_move = node_by_id(ui(), "undoButton") is not None # VLM: the undo (↶) icon is a rendered affordance top-right after a move vlm_assert("interaction_undo_icon_visible", "Is there a curved counter-clockwise undo arrow icon visible near " "the top of the screen?", depth=1, jump_kind="transition", tag="shape") _tap_undo() gone_after_undo = node_by_id(ui(), "undoButton") is None ok = absent_start and present_after_move and gone_after_undo record("interaction_undo_once_per_move", ok, "" if ok else f"behavior_wrong: undo affordance lifecycle wrong " f"(absent_start={absent_start}, " f"present_after_move={present_after_move}, " f"gone_after_undo={gone_after_undo})", depth=1, jump_kind="transition", expect="undoButton absent -> present after move -> absent after undo")
# ════════════════════════════════════════════════════════════════════════���═════# 6. Restart re-seeds the board (points->0, exactly 2 tiles)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_restart_reseeds_board", "interaction_restart_two_tiles_vlm"))def test_restart_reseeds_board(): """Play until the board grows (points>0, >2 tiles) -> tap restartButton -> points == 0 and EXACTLY 2 numeric tiles, with no dialog.""" _boot_clean() _go_to_mode(0) if not and_enter_game(): record("interaction_restart_reseeds_board", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="transition", expect="points=0 and 2 tiles") vlm_assert("interaction_restart_two_tiles", "unreachable", depth=1, jump_kind="transition", tag="content") return _play_until_points() _play_moves(3) grew = (_points() or 0) > 0 or len(_tiles()) > 2 if not _tap_restart(): record("interaction_restart_reseeds_board", False, "setup_failed: restartButton not found/tappable", depth=1, jump_kind="transition", expect="points=0 and 2 tiles") vlm_assert("interaction_restart_two_tiles", "unreachable", depth=1, jump_kind="transition", tag="content") return settle("tap") pts_after = _points() tiles_after = _tiles() ok = grew and pts_after == 0 and len(tiles_after) == 2 record("interaction_restart_reseeds_board", ok, "" if ok else f"behavior_wrong: after restart expected points=0 and " f"2 tiles, got points={pts_after} tiles={tiles_after} " f"(grew_before={grew})", depth=1, jump_kind="transition", expect="points=0 and exactly 2 tiles after restart") # VLM: the board shows exactly two tiles on an otherwise empty grid vlm_assert("interaction_restart_two_tiles", "Does the game board show exactly two numbered tiles, with all " "the other grid cells empty?", depth=1, jump_kind="transition", tag="position")
# ══════════════════════════════════════════════════════════════════════════════# 7. After restart the game is fresh AND still playable (3+ step sequence)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_restart_then_playable",))def test_restart_then_playable(): """Play -> restart (2 tiles) -> a fresh DPAD move still adds a tile (2->3) and the undo affordance re-appears: the re-seeded game is genuinely live, not a frozen snapshot.""" _boot_clean() _go_to_mode(0) if not and_enter_game(): record("interaction_restart_then_playable", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="transition", expect="tile count 2->3 after restart") return _play_until_points() if not _tap_restart(): record("interaction_restart_then_playable", False, "setup_failed: restartButton not found", depth=1, jump_kind="transition", expect="tile count 2->3 after restart") return settle("tap") tiles_seed = _tiles() # make effective moves until the tile count grows past the 2-tile seed grew = False for i in range(8): press_key("KEYCODE_DPAD_LEFT" if i % 2 == 0 else "KEYCODE_DPAD_UP") if len(_tiles()) > len(tiles_seed): grew = True break undo_back = node_by_id(ui(), "undoButton") is not None ok = len(tiles_seed) == 2 and grew and undo_back record("interaction_restart_then_playable", ok, "" if ok else f"behavior_wrong: re-seeded game not playable " f"(seed_tiles={tiles_seed}, grew={grew}, " f"undo_back={undo_back})", depth=1, jump_kind="transition", expect="a move after restart adds a tile (2->3) and undo returns")
# ══════════════════════════════════════════════════════════════════════════════# 8. Accumulated multi-move score persists (variant of flagship, emphasis on sum)# ════════════════════════════════════════════════════════════════════��═════════
@and_test(expects=("interaction_accumulated_score_persists", "interaction_merged_tiles_colored_vlm"))def test_accumulated_score_persists(): """Many moves accumulate a score>0 -> back -> kill+relaunch -> continue: the exact accumulated points survive. Distinct from #1 in emphasising that a multi-merge total (not just any board) is preserved.""" _boot_clean() _go_to_mode(0) if not and_enter_game(): record("interaction_accumulated_score_persists", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="transition", expect="accumulated points survive") vlm_assert("interaction_merged_tiles_colored", "unreachable", depth=1, jump_kind="transition", tag="color") return _play_until_points() _play_moves(6) P = _points() # VLM: after merges the board shows higher-value colored tiles vlm_assert("interaction_merged_tiles_colored", "Do the numbered tiles on the board have colored (non-white) " "backgrounds?", depth=1, jump_kind="transition", tag="color") if not P or P <= 0: record("interaction_accumulated_score_persists", False, "setup_failed: score never rose above 0", depth=1, jump_kind="transition", expect="accumulated points survive") return and_back() settle("tap") force_stop_and_relaunch() wait_for_foreground(15) _skip_tutorial() _go_to_mode(0) resumed = and_enter_continue() P2 = _points() if resumed else None ok = resumed and P2 == P and P2 > 0 record("interaction_accumulated_score_persists", ok, "" if ok else f"behavior_wrong: accumulated points {P} not preserved " f"across kill (got {P2})", depth=2, jump_kind="transition", expect=f"points={P} (>0) survive back+kill+continue")
# ══════════════════════════════════════════════════════════════════════════════# 9. Stats: move counters increment after play (clean baseline, depth 2)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_stats_moves_increment", "interaction_stats_nonzero_vlm"))def test_stats_moves_increment(): """Clean -> play 4x4 (several LEFT + UP) -> back -> drawer -> Statistics (4x4 tab): moves_All1 and moves_L1 have risen from the clean 0 baseline. Counts are asserted as >=1 (blocked moves make the exact count nondeterministic).""" _boot_clean() _go_to_mode(0) if not and_enter_game(): record("interaction_stats_moves_increment", False, "setup_failed: could not start a new 4x4 game", depth=2, jump_kind="transition", expect="moves_All1 >= 1") vlm_assert("interaction_stats_nonzero", "unreachable", depth=2, jump_kind="transition", tag="content") return # ensure at least a few LEFT moves are effective for _ in range(4): press_key("KEYCODE_DPAD_LEFT") _play_moves(2) and_back() # to Main (also writes save) settle("tap") if not and_reach_stats(): record("interaction_stats_moves_increment", False, "setup_failed: could not reach Statistics", depth=2, jump_kind="transition", expect="moves_All1 >= 1") vlm_assert("interaction_stats_nonzero", "unreachable", depth=2, jump_kind="transition", tag="content") return _select_stats_tab("4x4") moves_all = _stat_int("moves_All1") moves_left = _stat_int("moves_L1") ok = moves_all is not None and moves_all >= 1 and \ moves_left is not None and moves_left >= 1 record("interaction_stats_moves_increment", ok, "" if ok else f"behavior_wrong: 4x4 stats did not reflect play " f"(moves_All1={moves_all}, moves_L1={moves_left})", depth=2, jump_kind="transition", expect="moves_All1>=1 and moves_L1>=1 after 4x4 play") # VLM: the stat rows show non-zero numeric values, not a blank/zeroed screen vlm_assert("interaction_stats_nonzero", "Does this statistics screen display numeric values in its rows " "(numbers other than only zeros)?", depth=2, jump_kind="transition", tag="content")
# ══════════════════════════════════════════════════════════════════════════════# 10. Stats: highest number reflects play# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_stats_highest_number",))def test_stats_highest_number_reflects_play(): """Clean -> play until a tile >= 4 exists -> back -> Stats 4x4: highest_number1 >= 4 (the merged max is recorded).""" _boot_clean() _go_to_mode(0) if not and_enter_game(): record("interaction_stats_highest_number", False, "setup_failed: could not start a new 4x4 game", depth=2, jump_kind="transition", expect="highest_number1 >= 4") return max_tile = 0 for i in range(14): press_key("KEYCODE_DPAD_LEFT" if i % 2 == 0 else "KEYCODE_DPAD_UP") t = _tiles() max_tile = max([0] + t) if max_tile >= 4: break and_back() settle("tap") if not and_reach_stats(): record("interaction_stats_highest_number", False, "setup_failed: could not reach Statistics", depth=2, jump_kind="transition", expect="highest_number1 >= 4") return _select_stats_tab("4x4") hn = _stat_int("highest_number1") ok = max_tile >= 4 and hn is not None and hn >= 4 record("interaction_stats_highest_number", ok, "" if ok else f"behavior_wrong: highest_number1={hn} does not reflect " f"board max {max_tile} (expected >=4)", depth=2, jump_kind="transition", expect=f"highest_number1>=4 (board reached {max_tile})")
# ══════════════════════════════════════════════════════════════════════════════# 11. Stats: highest score matches the points reached# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_stats_highest_score",))def test_stats_highest_score_matches_points(): """Clean -> play to points P>0 -> back -> Stats 4x4: highest_score1 == P (the game's best score for this mode is the score we just achieved from zero).""" _boot_clean() _go_to_mode(0) if not and_enter_game(): record("interaction_stats_highest_score", False, "setup_failed: could not start a new 4x4 game", depth=2, jump_kind="transition", expect="highest_score1 == points") return _play_until_points() _play_moves(3) P = _points() or 0 and_back() settle("tap") if not and_reach_stats(): record("interaction_stats_highest_score", False, "setup_failed: could not reach Statistics", depth=2, jump_kind="transition", expect="highest_score1 == points") return _select_stats_tab("4x4") hs = _stat_int("highest_score1") ok = P > 0 and hs is not None and hs == P record("interaction_stats_highest_score", ok, "" if ok else f"behavior_wrong: highest_score1={hs} != achieved " f"points {P}", depth=2, jump_kind="transition", expect=f"highest_score1 == {P}")
# ══════════════════════════════════════════════════════════════════════════════# 12. Multi-mode stat integrity — playing 4x4 does not touch 5x5 (multi-record)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_stats_mode_isolation",))def test_stats_mode_isolation(): """Clean -> play ONLY 4x4 -> back -> Stats: 4x4 moves_All1 > 0 while 5x5 moves_All2 == 0. Separate per-mode records: one mode's play must not leak into another's statistics.""" _boot_clean() _go_to_mode(0) if not and_enter_game(): record("interaction_stats_mode_isolation", False, "setup_failed: could not start a new 4x4 game", depth=2, jump_kind="transition", expect="4x4>0 while 5x5==0") return _play_moves(4) and_back() settle("tap") if not and_reach_stats(): record("interaction_stats_mode_isolation", False, "setup_failed: could not reach Statistics", depth=2, jump_kind="transition", expect="4x4>0 while 5x5==0") return _select_stats_tab("4x4") m4 = _stat_int("moves_All1") _select_stats_tab("5x5") m5 = _stat_int("moves_All2") ok = m4 is not None and m4 > 0 and m5 == 0 record("interaction_stats_mode_isolation", ok, "" if ok else f"behavior_wrong: mode isolation broken " f"(4x4 moves_All1={m4}, 5x5 moves_All2={m5})", depth=2, jump_kind="transition", expect="4x4 moves_All1>0 and 5x5 moves_All2==0")
# ══════════════════════════════════════════════════════════════════════════════# 13. Stats: undo counter increments after an undo# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_stats_undo_counter",))def test_stats_undo_counter_increments(): """Clean -> play 4x4, use the undo button once -> back -> Stats 4x4: undo_number1 >= 1 (using undo is persisted as a data statistic).""" _boot_clean() _go_to_mode(0) if not and_enter_game(): record("interaction_stats_undo_counter", False, "setup_failed: could not start a new 4x4 game", depth=2, jump_kind="transition", expect="undo_number1 >= 1") return _play_moves(3) used_undo = _tap_undo() and_back() settle("tap") if not and_reach_stats(): record("interaction_stats_undo_counter", False, "setup_failed: could not reach Statistics", depth=2, jump_kind="transition", expect="undo_number1 >= 1") return _select_stats_tab("4x4") un = _stat_int("undo_number1") ok = used_undo and un is not None and un >= 1 record("interaction_stats_undo_counter", ok, "" if ok else f"behavior_wrong: undo_number1={un} did not record the " f"undo (used_undo={used_undo})", depth=2, jump_kind="transition", expect="undo_number1 >= 1 after using undo")
# ══════════════════════════════════════════════════════════════════════════════# 14. Continue restores into the correct MODE (5x5 persistence)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_continue_mode_correct", "interaction_5x5_larger_grid_vlm"))def test_continue_restores_5x5_mode(): """Play a 5x5 game -> back -> kill+relaunch -> continue on the 5x5 page: the exact points and tile multiset restore, proving mode-correct persistence (the save is keyed per mode, not global).""" _boot_clean() _go_to_mode(1) # page to 5x5 if not and_enter_game(): record("interaction_continue_mode_correct", False, "setup_failed: could not start a new 5x5 game", depth=2, jump_kind="transition", expect="5x5 points/tiles restored") vlm_assert("interaction_5x5_larger_grid", "unreachable", depth=2, jump_kind="transition", tag="size") return _play_until_points() _play_moves(5) P, T = _points(), _tiles() # VLM: a mid-game 5x5 board is a larger grid than the 4x4 default vlm_assert("interaction_5x5_larger_grid", "Is the game board a large square grid with five columns and five " "rows of cells?", depth=2, jump_kind="transition", tag="size") if P is None or not T: record("interaction_continue_mode_correct", False, "setup_failed: could not read 5x5 points/tiles", depth=2, jump_kind="transition", expect="5x5 points/tiles restored") return and_back() settle("tap") force_stop_and_relaunch() wait_for_foreground(15) _skip_tutorial() _go_to_mode(1) # back to the 5x5 page resumed = and_enter_continue() P2, T2 = (_points(), _tiles()) if resumed else (None, None) ok = resumed and P2 == P and T2 == T record("interaction_continue_mode_correct", ok, "" if ok else f"behavior_wrong: 5x5 continue did not restore " f"points={P} tiles={T} (got points={P2} tiles={T2})", depth=2, jump_kind="transition", expect=f"5x5 continue restores points={P} tiles={T}")
# ══════════════════════════════════════════════════════════════════════════════# 15. Two independent saved games coexist (4x4 and 5x5) — strong multi-record# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_two_saved_games",))def test_two_independent_saved_games(): """Play 4x4 (points P4) + back, then play 5x5 (points P5) + back: BOTH modes' continue buttons are enabled, AND continuing 4x4 restores P4 (not P5). Distinct per-mode save files must not overwrite one another.""" _boot_clean() # --- 4x4 game --- _go_to_mode(0) if not and_enter_game(): record("interaction_two_saved_games", False, "setup_failed: could not start a new 4x4 game", depth=2, jump_kind="transition", expect="4x4 continue restores its own P4") return _play_until_points() _play_moves(3) P4 = _points() and_back() settle("tap") # --- 5x5 game --- _go_to_mode(1) if not and_enter_game(): record("interaction_two_saved_games", False, "setup_failed: could not start a new 5x5 game", depth=2, jump_kind="transition", expect="4x4 continue restores its own P4") return _play_until_points() _play_moves(3) P5 = _points() and_back() settle("tap") # both modes enabled? _go_to_mode(1) cg5 = node_by_id(ui(), "button_continueGame") enabled5 = cg5 is not None and cg5.get("enabled") == "true" _go_to_mode(0) cg4 = node_by_id(ui(), "button_continueGame") enabled4 = cg4 is not None and cg4.get("enabled") == "true" # continue 4x4 -> must restore P4, not P5 resumed = and_enter_continue() P4_restored = _points() if resumed else None ok = (P4 is not None and P5 is not None and enabled4 and enabled5 and resumed and P4_restored == P4) record("interaction_two_saved_games", ok, "" if ok else f"behavior_wrong: two-save integrity failed " f"(P4={P4} P5={P5} enabled4={enabled4} enabled5={enabled5} " f"4x4_restored={P4_restored})", depth=2, jump_kind="transition", expect=f"both modes enabled; 4x4 continue restores points={P4}")
# ══════════════════════════════════════════════════════════════════════════════# 16. Continue is repeatable — resume, back, resume again preserves the board# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_continue_repeatable",))def test_continue_repeatable(): """Play -> back -> continue (resume) -> back -> continue again: the board and points survive TWO round-trips through Main, and later moves are still applied on top of the restored state (a 3+ surface data sequence).""" _boot_clean() _go_to_mode(0) if not and_enter_game(): record("interaction_continue_repeatable", False, "setup_failed: could not start a new 4x4 game", depth=2, jump_kind="transition", expect="board survives two resumes") return _play_until_points() _play_moves(3) P0 = _points() and_back() # save #1 settle("tap") if not and_enter_continue(): # resume #1 record("interaction_continue_repeatable", False, "setup_failed: first continue failed", depth=2, jump_kind="transition", expect="board survives two resumes") return P1 = _points() and_back() # save #2 settle("tap") if not and_enter_continue(): # resume #2 record("interaction_continue_repeatable", False, "setup_failed: second continue failed", depth=3, jump_kind="transition", expect="board survives two resumes") return P2 = _points() ok = P0 is not None and P0 > 0 and P1 == P0 and P2 == P0 record("interaction_continue_repeatable", ok, "" if ok else f"behavior_wrong: points not stable across two resumes " f"(P0={P0} resume1={P1} resume2={P2})", depth=3, jump_kind="transition", expect=f"points={P0} preserved across resume->back->resume")
# ══════════════════════════════════════════════════════════════════════════════# 17. Restart clears the saved game's continue state? -> restart is in-game only# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_restart_then_persist",))def test_restart_then_persist(): """Play -> restart (board back to seed) -> play again -> back -> kill+relaunch -> continue restores the POST-restart game, not the pre-restart one. Confirms the restart's re-seed is the state that gets persisted (a 3+ step sequence).""" _boot_clean() _go_to_mode(0) if not and_enter_game(): record("interaction_restart_then_persist", False, "setup_failed: could not start a new 4x4 game", depth=2, jump_kind="transition", expect="post-restart game persists") return _play_until_points() _play_moves(4) # a "high" pre-restart score if not _tap_restart(): record("interaction_restart_then_persist", False, "setup_failed: restartButton not found", depth=2, jump_kind="transition", expect="post-restart game persists") return settle("tap") # play a fresh, short post-restart game _play_moves(2) P_post = _points() T_post = _tiles() and_back() settle("tap") force_stop_and_relaunch() wait_for_foreground(15) _skip_tutorial() _go_to_mode(0) resumed = and_enter_continue() P2, T2 = (_points(), _tiles()) if resumed else (None, None) ok = resumed and P2 == P_post and T2 == T_post record("interaction_restart_then_persist", ok, "" if ok else f"behavior_wrong: continue did not restore the " f"post-restart game points={P_post} tiles={T_post} " f"(got points={P2} tiles={T2})", depth=2, jump_kind="transition", expect=f"continue restores post-restart points={P_post} tiles={T_post}")
# ══════════════════════════════════════════════════════════════════════════════# 18. Stats overflow (context) menu — sole owner; open only, never tap the item# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_stats_overflow_menu",))def test_stats_overflow_menu_opens(): """The overflow ('More options') menu in StatsActivity is the app's one real context menu. Opening it reveals a menu item that is ABSENT from the plain Stats surface (the single destructive 'Reset Statistics' entry). We open it and confirm the item appeared — we NEVER tap it (it is destructive).""" _boot_clean() if not and_reach_stats(): record("interaction_stats_overflow_menu", False, "setup_failed: could not reach Statistics", depth=2, jump_kind="transition", expect="overflow menu item appears") return before = and_showing() of = find_node(ui(), content_desc="More options") if of is None: # some builds expose it as a plain overflow button without that desc for n in ui(): if "overflow" in (n.get("content-desc", "") + n.get("resource-id", "")).lower(): of = n break if of is None or not tap_node(of): record("interaction_stats_overflow_menu", False, "feature_missing: no overflow/context menu control on Statistics", depth=2, jump_kind="transition", expect="overflow menu item appears") return settle("tap") after = and_showing() # a menu item appeared that was not on the plain stats surface item = find_node_ci(ui(), "Reset Statistics") appeared = item is not None or surface_changed(before, after, min_delta=1) # leave the menu WITHOUT tapping the destructive item back() settle("tap") ok = appeared record("interaction_stats_overflow_menu", ok, "" if ok else "behavior_wrong: overflow menu did not open / no item " "appeared", depth=2, jump_kind="transition", expect="overflow opens revealing a menu item over the Stats surface")
# ══════════════════════════════════════════════════════════════════════════════# 19. VLM — restart icon affordance on the game screen# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_restart_icon_visible_vlm",))def test_restart_icon_visible(): """The restart (⟳) icon is a rendered affordance on the game toolbar. It is an icon-only control (empty text), so its RENDERING is a genuine VLM question.""" _boot_clean() _go_to_mode(0) if not and_enter_game(): vlm_assert("interaction_restart_icon_visible", "unreachable", depth=1, jump_kind="transition", tag="shape") return vlm_assert("interaction_restart_icon_visible", "Is there a circular refresh / restart arrow icon visible near the " "top-right of the game screen?", depth=1, jump_kind="transition", tag="shape")
TESTS = [ test_persistence_across_process_death, # flagship test_kill_without_back_not_saved, test_continue_enables_after_play_and_back, test_undo_reverts_points, test_undo_is_once_per_move, test_restart_reseeds_board, test_restart_then_playable, test_accumulated_score_persists, test_stats_moves_increment, test_stats_highest_number_reflects_play, test_stats_highest_score_matches_points, test_stats_mode_isolation, test_stats_undo_counter_increments, test_continue_restores_5x5_mode, test_two_independent_saved_games, test_continue_repeatable, test_restart_then_persist, test_stats_overflow_menu_opens, test_restart_icon_visible,]
if __name__ == "__main__": run_suite(TESTS, "interaction")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599#!/usr/bin/env python3"""NAVIGATION lane — Privacy Friendly 2048.
Sole owner of surface REACHABILITY and back-stack integrity: every jump is provenwith and_reach() — the TARGET surface's discriminating element APPEARED *and* theSOURCE surface's element DISAPPEARED — so a screen that was already in the tree cannever be mistaken for one that was navigated to. This lane carries the suite'sdepth>=2 chains (drawer -> Settings -> a preference dialog; Main -> Game -> back).
Everything asserted here was OBSERVED on the running original (see recon.md + liveprobing). Key facts that drive the marker choices below: * button_newGame carries text "START NEW GAME" -> node_key "Button|START NEW GAME" * button_continueGame carries text "CONTINUE GAME" * restartButton has no text/desc -> node_key falls back to id suffix "restartButton" * "START NEW GAME" is Main-only: it VANISHES on every drawer destination, so it is the universal source marker. (view_pager is NOT — TutorialActivity has its own.) * btn_prev is absent from the dump on page 0; btn_next is absent on the last page. * Behind a Settings AlertDialog the settings list rows leave the dump, so the dialog option ("Dark"/"Original") appearing while "Activate Animation" disappears is a genuine depth-2 surface reach."""import os, syssys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from android_testgen_kit import * # noqa: F403,F401
# ── shared helpers ──────────────────────────────────────────────────────────────
SRC_MAIN = "START NEW GAME" # Main-only key fragment (button_newGame text)
def _boot(): """Clean entry point every test: restart, reach foreground, dismiss a possible first-run tutorial. Tolerates the tutorial being present OR absent.""" restart_app() fg = wait_for_foreground(15) n = ui() if node_by_id(n, "btn_skip") or find_node_ci(n, "SKIP"): tap_text(ui(), "SKIP") settle("tap") return fg
def _mode_label(nodes): for x in nodes: if x.get("class", "").endswith("TextView") and x.get("text", "") in ( "4x4", "5x5", "6x6", "7x7"): return x.get("text", "") return ""
def _goto_first_mode(): """Page the MainActivity ViewPager back to page 0 (4x4). btn_prev is INVISIBLE (absent from the dump) on page 0, which is the deterministic stop condition.""" for _ in range(6): p = node_by_id(ui(), "btn_prev") if not p: break tap_node(p) settle("tap") return ui()
def _open_drawer(nodes): """Open the nav drawer from a screen that has the hamburger. Returns True on tap.""" db = find_node(nodes, content_desc="Open navigation drawer") return tap_node(db) if db else False
def and_reach_drawer(item, target, source=SRC_MAIN): """Main -> (open drawer) -> tap `item`, then PROVE the destination surface: `target` appeared and `source` (a Main-only key) vanished. Counts one surface, so it BACKS a depth>=1 reach. The and_reach_* NAME is what the depth audit reads.
before is snapshotted on MAIN (pre-drawer) so the verdict compares Main against the landed destination — the transient open-drawer overlay is irrelevant.""" before = and_showing() if not _open_drawer(ui()): return False settle("tap") if not tap_text(ui(), item): return False after = and_showing() ok = and_reach(before, after, target, source) if ok: and_enter(target) return ok
def and_reach_game_new(nodes): """Main -> GameActivity via START NEW GAME. Proves restartButton appeared and the launcher's START NEW GAME vanished. Counts one surface (backs depth>=1).""" btn = node_by_id(nodes, "button_newGame") return bool(btn) and and_reach_surface(btn, "restartButton", SRC_MAIN)
def _numeric_tiles(nodes): return [b for b in find_by_class(nodes, "Button") if b.get("text", "").strip().isdigit()]
def _play_a_few_moves(): """Deterministic effective moves via DPAD (recon: DPAD drives handleSwipe*).""" for k in ("KEYCODE_DPAD_LEFT", "KEYCODE_DPAD_UP", "KEYCODE_DPAD_LEFT", "KEYCODE_DPAD_UP"): press_key(k)
# ══════════════════════════════════════════════════════════════════════════════# (A) Top-level destinations reached from the drawer (depth 1, jump_kind="reach")# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("nav_reach_statistics", "nav_reach_statistics_vlm"))def test_reach_statistics(): _boot() ok = and_reach_drawer("Statistics", "Highest Number") record("nav_reach_statistics", ok, "" if ok else "feature_missing: Statistics surface not reached " "(its 'Highest Number' did not appear or Main's START NEW GAME stayed)", depth=1, jump_kind="reach", expect="StatsActivity: 'Highest Number' appears; Main 'START NEW GAME' gone") vlm_assert("nav_reach_statistics", "Is a horizontal row of tab labels shown across the top of the " "screen, with rows of statistics listed below it?", RESULTS_DIR, depth=1, jump_kind="reach", tag="position")
@and_test(expects=("nav_reach_settings", "nav_reach_settings_vlm"))def test_reach_settings(): _boot() ok = and_reach_drawer("Settings", "Select theme") record("nav_reach_settings", ok, "" if ok else "feature_missing: Settings surface not reached " "('Select theme' did not appear or Main's START NEW GAME stayed)", depth=1, jump_kind="reach", expect="SettingsActivity: 'Select theme' appears; Main 'START NEW GAME' gone") vlm_assert("nav_reach_settings", "Is this a settings screen showing a vertical list of preference " "rows, each with a title line?", RESULTS_DIR, depth=1, jump_kind="reach", tag="position")
@and_test(expects=("nav_reach_help", "nav_reach_help_vlm"))def test_reach_help(): _boot() ok = and_reach_drawer("Help", "What is the goal of this game?") record("nav_reach_help", ok, "" if ok else "feature_missing: Help surface not reached " "(FAQ row did not appear or Main's START NEW GAME stayed)", depth=1, jump_kind="reach", expect="HelpActivity: FAQ row 'What is the goal of this game?' appears; " "Main 'START NEW GAME' gone") vlm_assert("nav_reach_help", "Is the screen a vertical list of question rows, one per line, " "like an FAQ / help list?", RESULTS_DIR, depth=1, jump_kind="reach", tag="layout")
@and_test(expects=("nav_reach_about", "nav_reach_about_vlm"))def test_reach_about(): _boot() # "Version:" is an About-only label; textFieldVersionName is its value field. ok = and_reach_drawer("About", "Version:") record("nav_reach_about", ok, "" if ok else "feature_missing: About surface not reached " "('Version:' did not appear or Main's START NEW GAME stayed)", depth=1, jump_kind="reach", expect="AboutActivity: 'Version:' label appears; Main 'START NEW GAME' gone") vlm_assert("nav_reach_about", "Does this screen show app information text such as a version " "number, author names, and a license paragraph?", RESULTS_DIR, depth=1, jump_kind="reach", tag="content")
@and_test(expects=("nav_reach_tutorial", "nav_reach_tutorial_vlm"))def test_reach_tutorial(): _boot() # Tutorial slide 1 title "Welcome!" is unique to TutorialActivity. ok = and_reach_drawer("Tutorial", "Welcome!") record("nav_reach_tutorial", ok, "" if ok else "feature_missing: Tutorial surface not reached " "('Welcome!' did not appear or Main's START NEW GAME stayed)", depth=1, jump_kind="reach", expect="TutorialActivity: slide title 'Welcome!' appears; " "Main 'START NEW GAME' gone") vlm_assert("nav_reach_tutorial", "Are there SKIP and NEXT buttons at the bottom of the screen " "below an introduction slide?", RESULTS_DIR, depth=1, jump_kind="reach", tag="position")
@and_test(expects=("nav_reach_game_new", "nav_reach_game_new_vlm"))def test_reach_game_new(): _boot() _goto_first_mode() ok = and_reach_game_new(ui()) record("nav_reach_game_new", ok, "" if ok else "feature_missing: GameActivity not reached from " "START NEW GAME (restartButton absent or START NEW GAME stayed)", depth=1, jump_kind="reach", expect="GameActivity: restartButton appears; Main 'START NEW GAME' gone") vlm_assert("nav_reach_game_new", "Is there a left-pointing back/up arrow at the top-left of the " "screen, above a grid of square game tiles?", RESULTS_DIR, depth=1, jump_kind="reach", tag="position")
# ══════════════════════════════════════════════════════════════════════════════# (B) Back-stack returns (jump_kind="transition" — the SOURCE surface comes back)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("nav_back_game_to_main",))def test_back_game_to_main(): """Game -> BACK -> Main. and_back() presses BACK and pops one surface; the verdict is that Main's START NEW GAME reappeared and Game's restartButton left.""" _boot() _goto_first_mode() if not and_reach_game_new(ui()): record("nav_back_game_to_main", False, "setup_failed: could not open the game to test BACK", depth=1, jump_kind="transition", expect="Main restored (START NEW GAME back, restartButton gone)") return before = and_showing() # on Game and_back() # BACK, pop one surface after = and_showing() ok = and_reach(before, after, target=SRC_MAIN, source="restartButton") record("nav_back_game_to_main", ok, "" if ok else "behavior_wrong: BACK did not return Game -> Main " "(START NEW GAME not restored or restartButton still present)", depth=1, jump_kind="transition", expect="MainActivity restored: 'START NEW GAME' reappears, " "restartButton disappears")
@and_test(expects=("nav_back_stats_to_main",))def test_back_stats_to_main(): """Stats -> BACK -> Main.""" _boot() if not and_reach_drawer("Statistics", "Highest Number"): record("nav_back_stats_to_main", False, "setup_failed: could not reach Statistics to test BACK", depth=1, jump_kind="transition", expect="Main restored (START NEW GAME back, 'Highest Number' gone)") return before = and_showing() # on Stats and_back() after = and_showing() ok = and_reach(before, after, target=SRC_MAIN, source="Highest Number") record("nav_back_stats_to_main", ok, "" if ok else "behavior_wrong: BACK did not return Stats -> Main " "(START NEW GAME not restored or 'Highest Number' still present)", depth=1, jump_kind="transition", expect="MainActivity restored: 'START NEW GAME' reappears, " "'Highest Number' disappears")
@and_test(expects=("nav_back_settings_to_main",))def test_back_settings_to_main(): """Settings -> BACK -> Main.""" _boot() if not and_reach_drawer("Settings", "Select theme"): record("nav_back_settings_to_main", False, "setup_failed: could not reach Settings to test BACK", depth=1, jump_kind="transition", expect="Main restored (START NEW GAME back, 'Select theme' gone)") return before = and_showing() and_back() after = and_showing() ok = and_reach(before, after, target=SRC_MAIN, source="Select theme") record("nav_back_settings_to_main", ok, "" if ok else "behavior_wrong: BACK did not return Settings -> Main " "(START NEW GAME not restored or 'Select theme' still present)", depth=1, jump_kind="transition", expect="MainActivity restored: 'START NEW GAME' reappears, " "'Select theme' disappears")
@and_test(expects=("nav_back_about_to_main",))def test_back_about_to_main(): """About -> BACK -> Main. About's toolbar uses 'Navigate up', but the hardware BACK still returns to Main (verified on the running app).""" _boot() if not and_reach_drawer("About", "Version:"): record("nav_back_about_to_main", False, "setup_failed: could not reach About to test BACK", depth=1, jump_kind="transition", expect="Main restored (START NEW GAME back, 'Version:' gone)") return before = and_showing() and_back() after = and_showing() ok = and_reach(before, after, target=SRC_MAIN, source="Version:") record("nav_back_about_to_main", ok, "" if ok else "behavior_wrong: BACK did not return About -> Main " "(START NEW GAME not restored or 'Version:' still present)", depth=1, jump_kind="transition", expect="MainActivity restored: 'START NEW GAME' reappears, " "'Version:' disappears")
# ══════════════════════════════════════════════════════════════════════════════# (C) In-surface ViewPager paging on MainActivity (transition, depth 0)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("nav_pager_next_4to5",))def test_pager_next_4to5(): """btn_next advances the mode label 4x4 -> 5x5. In-surface state flip (no new surface), so jump_kind='transition', depth 0.""" _boot() _goto_first_mode() before = and_showing() start_label = _mode_label(ui()) nx = node_by_id(ui(), "btn_next") tapped = tap_node(nx) if nx else False settle("tap") after = and_showing() end_label = _mode_label(ui()) ok = bool(tapped and start_label == "4x4" and end_label == "5x5" and and_reach(before, after, target="5x5", source="4x4")) record("nav_pager_next_4to5", ok, "" if ok else f"behavior_wrong: btn_next did not page 4x4->5x5 " f"(start={start_label}, end={end_label})", depth=0, jump_kind="transition", expect="mode label '5x5' appears and '4x4' disappears after btn_next")
@and_test(expects=("nav_pager_prev_5to4",))def test_pager_prev_5to4(): """From 5x5, btn_prev returns the mode label to 4x4.""" _boot() _goto_first_mode() nx = node_by_id(ui(), "btn_next") if not (nx and tap_node(nx)): record("nav_pager_prev_5to4", False, "setup_failed: could not page forward to 5x5 first", depth=0, jump_kind="transition", expect="mode label '4x4' restored after btn_prev from 5x5") return settle("tap") before = and_showing() start_label = _mode_label(ui()) pv = node_by_id(ui(), "btn_prev") tapped = tap_node(pv) if pv else False settle("tap") after = and_showing() end_label = _mode_label(ui()) ok = bool(tapped and start_label == "5x5" and end_label == "4x4" and and_reach(before, after, target="4x4", source="5x5")) record("nav_pager_prev_5to4", ok, "" if ok else f"behavior_wrong: btn_prev did not page 5x5->4x4 " f"(start={start_label}, end={end_label})", depth=0, jump_kind="transition", expect="mode label '4x4' appears and '5x5' disappears after btn_prev")
@and_test(expects=("nav_pager_to_last_7x7", "nav_pager_last_arrow_vlm"))def test_pager_to_last(): """btn_next x3 reaches 7x7 (last page); on the last page btn_next disappears from the tree entirely, while btn_prev is present.""" _boot() _goto_first_mode() before = and_showing() steps = 0 for _ in range(3): nx = node_by_id(ui(), "btn_next") if not (nx and tap_node(nx)): break settle("tap") steps += 1 after = and_showing() end_label = _mode_label(ui()) next_gone = node_by_id(ui(), "btn_next") is None prev_present = node_by_id(ui(), "btn_prev") is not None ok = bool(steps == 3 and end_label == "7x7" and next_gone and prev_present and and_reach(before, after, target="7x7", source="4x4")) record("nav_pager_to_last_7x7", ok, "" if ok else f"behavior_wrong: paging to last page not as observed " f"(label={end_label}, next_gone={next_gone}, prev_present={prev_present})", depth=0, jump_kind="transition", expect="mode label '7x7'; btn_next absent on the last page; btn_prev present") vlm_assert("nav_pager_last_arrow", "Is there a right-pointing next arrow on the RIGHT edge next to the " "mode preview? Answer NO if only a left-pointing arrow is present.", RESULTS_DIR, expect="NO", depth=0, jump_kind="transition", tag="position")
# ══════════════════════════════════════════════════════════════════════════════# (D) Stats tab switching (transition, already on Stats so depth 1)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("nav_stats_tab_4to5",))def test_stats_tab_switch(): """On StatsActivity, tapping the 5X5 tab swaps the visible stat id set: the 4x4 tab shows *number1 ids, the 5x5 tab shows *number2 ids. Same surface -> the tab content flip is a 'transition'; depth 1 because we are already on Stats.""" _boot() if not and_reach_drawer("Statistics", "Highest Number"): record("nav_stats_tab_4to5", False, "setup_failed: could not reach Statistics to switch tabs", depth=1, jump_kind="transition", expect="5x5 tab content (highest_number2) present after tapping 5X5") return had_tab1 = node_by_id(ui(), "highest_number1") is not None tab5 = find_node(ui(), text="5X5") tapped = tap_node(tab5) if tab5 else False settle("tap") now = ui() has_tab2 = node_by_id(now, "highest_number2") is not None ok = bool(had_tab1 and tapped and has_tab2) record("nav_stats_tab_4to5", ok, "" if ok else f"behavior_wrong: 5X5 tab did not switch stat content " f"(had highest_number1={had_tab1}, now highest_number2={has_tab2})", depth=1, jump_kind="transition", expect="tapping 5X5 tab reveals the 5x5 stat ids (highest_number2)")
# ══════════════════════════════════════════════════════════════════════════════# (E) Deep chains (depth>=2 — this lane's territory; >=3 provided)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("nav_deep_theme_dialog", "nav_deep_theme_dialog_vlm"))def test_deep_theme_dialog(): """Main -> (drawer) Settings -> tap 'Select theme' -> theme AlertDialog. Two surfaces are crossed before the assertion (Settings, then the dialog). Behind the dialog the settings list rows leave the dump, so the dialog radio 'Dark' appearing while 'Activate Animation' disappears is a real depth-2 surface reach. Cancels afterwards to leave no dialog open.""" _boot() if not and_reach_drawer("Settings", "Select theme"): record("nav_deep_theme_dialog", False, "setup_failed: could not reach Settings for the theme dialog", depth=2, jump_kind="reach", expect="theme dialog: 'Dark' appears; 'Activate Animation' gone") vlm_assert("nav_deep_theme_dialog", "Is a pop-up dialog titled 'Select theme' shown with radio " "options stacked vertically?", RESULTS_DIR, depth=2, jump_kind="reach", tag="shape") return row = find_node(ui(), text="Select theme") ok = row is not None and and_reach_surface(row, "Dark", "Activate Animation") record("nav_deep_theme_dialog", ok, "" if ok else "feature_missing: theme dialog did not open over Settings " "('Dark' absent or the settings list stayed visible)", depth=2, jump_kind="reach", expect="theme AlertDialog: option 'Dark' appears; settings row " "'Activate Animation' disappears") vlm_assert("nav_deep_theme_dialog", "Is a pop-up dialog titled 'Select theme' shown with radio options " "(System / Light / Dark) stacked vertically?", RESULTS_DIR, depth=2, jump_kind="reach", tag="shape") # clean up: dismiss the dialog if tap_text(ui(), "CANCEL"): settle("tap")
@and_test(expects=("nav_deep_color_dialog",))def test_deep_color_dialog(): """Main -> (drawer) Settings -> tap 'Select Color Scheme' -> color AlertDialog. depth 2 reach: option 'Original' appears while 'Activate Animation' disappears. Cancels afterwards.""" _boot() if not and_reach_drawer("Settings", "Select Color Scheme"): record("nav_deep_color_dialog", False, "setup_failed: could not reach Settings for the color dialog", depth=2, jump_kind="reach", expect="color dialog: 'Original' appears; 'Activate Animation' gone") return row = find_node(ui(), text="Select Color Scheme") ok = row is not None and and_reach_surface(row, "Original", "Activate Animation") record("nav_deep_color_dialog", ok, "" if ok else "feature_missing: color-scheme dialog did not open over " "Settings ('Original' absent or the settings list stayed visible)", depth=2, jump_kind="reach", expect="color AlertDialog: option 'Original' appears; settings row " "'Activate Animation' disappears") if tap_text(ui(), "CANCEL"): settle("tap")
@and_test(expects=("nav_deep_game_roundtrip",))def test_deep_game_roundtrip(): """Main -> START NEW GAME -> Game -> BACK -> Main. A there-and-back chain that crosses the Game surface; the final assertion is that Main was restored. The round trip also arms Continue (BACK triggers save()), which the next test uses.""" _boot() _goto_first_mode() if not and_reach_game_new(ui()): record("nav_deep_game_roundtrip", False, "setup_failed: could not open the game for the round trip", depth=2, jump_kind="transition", expect="Main restored after BACK from Game (START NEW GAME back)") return on_game = and_showing() _play_a_few_moves() # make it a real game before leaving and_back() # Game -> Main (pops the crossed surface) on_main = and_showing() ok = and_reach(on_game, on_main, target=SRC_MAIN, source="restartButton") record("nav_deep_game_roundtrip", ok, "" if ok else "behavior_wrong: round trip did not restore Main " "(START NEW GAME not back or restartButton still present)", depth=2, jump_kind="transition", expect="after Main->Game->BACK the MainActivity is restored: " "'START NEW GAME' present, restartButton gone")
@and_test(expects=("nav_deep_stats_tab_content",))def test_deep_stats_tab_content(): """Main -> (drawer) Stats -> tap 5X5 tab -> assert the 5x5 stat content. Two surfaces crossed (Stats reach, then the tab-content flip) before the assertion.""" _boot() if not and_reach_drawer("Statistics", "Highest Number"): record("nav_deep_stats_tab_content", False, "setup_failed: could not reach Statistics", depth=2, jump_kind="transition", expect="5x5 tab stat ids (highest_number2) shown after tapping 5X5") return and_enter("stats-4x4-tab") # already crossed into Stats' first tab tab5 = find_node(ui(), text="5X5") before = and_showing() tapped = tap_node(tab5) if tab5 else False settle("tap") now = ui() after = and_showing() # the 5x5 tab exposes highest_number2 / moves_L2 ids has2 = (node_by_id(now, "highest_number2") is not None and node_by_id(now, "moves_L2") is not None) changed = surface_changed(before, after) ok = bool(tapped and has2 and changed) record("nav_deep_stats_tab_content", ok, "" if ok else f"behavior_wrong: 5X5 tab content not shown " f"(highest_number2+moves_L2={has2}, surface_changed={changed})", depth=2, jump_kind="transition", expect="5X5 tab reveals highest_number2 and moves_L2 stat fields")
@and_test(expects=("nav_reach_continue_game",))def test_reach_continue_game(): """Setup: play a game and BACK (arms Continue via save()). Then the real jump: tap the now-enabled CONTINUE GAME and assert GameActivity is reached — restartButton appears and the launcher's CONTINUE GAME vanishes. We navigate to a game we set up, then assert the JUMP (not the game creation).""" _boot() _goto_first_mode() if not and_reach_game_new(ui()): record("nav_reach_continue_game", False, "setup_failed: could not open a game to arm Continue", depth=1, jump_kind="reach", expect="GameActivity via CONTINUE GAME: restartButton appears") return _play_a_few_moves() and_back() # graceful save arms Continue cont = node_by_id(ui(), "button_continueGame") if not cont or cont.get("enabled") != "true": record("nav_reach_continue_game", False, f"setup_failed: CONTINUE GAME not enabled after play+back " f"(enabled={cont.get('enabled') if cont else 'missing'})", depth=1, jump_kind="reach", expect="GameActivity via CONTINUE GAME: restartButton appears") return ok = and_reach_surface(cont, "restartButton", "CONTINUE GAME") record("nav_reach_continue_game", ok, "" if ok else "behavior_wrong: CONTINUE GAME did not reach GameActivity " "(restartButton absent or CONTINUE GAME stayed)", depth=1, jump_kind="reach", expect="GameActivity: restartButton appears; 'CONTINUE GAME' disappears")
TESTS = [ # (A) reaches test_reach_statistics, test_reach_settings, test_reach_help, test_reach_about, test_reach_tutorial, test_reach_game_new, # (B) back-stack returns test_back_game_to_main, test_back_stats_to_main, test_back_settings_to_main, test_back_about_to_main, # (C) in-surface paging test_pager_next_4to5, test_pager_prev_5to4, test_pager_to_last, # (D) stats tabs test_stats_tab_switch, # (E) deep chains test_deep_theme_dialog, test_deep_color_dialog, test_deep_game_roundtrip, test_deep_stats_tab_content, test_reach_continue_game,]
if __name__ == "__main__": run_suite(TESTS, "navigation")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984#!/usr/bin/env python3"""STATE-CHANGE lane — Privacy Friendly 2048.
Sole owner of CHECKED / SELECTED / ENABLED / FOCUSED transitions PAIRED WITH theirapp-authored consequence, of page-level state machines, of conditionalenable/disable, and of SETTINGS / mode PERSISTENCE across a revisit or processdeath. A bare `checked==true` with no trigger and no consequence is never shipped:every case FLIPS or OBSERVES a state as the result of a user action, then assertsthe consequence, then restores the baseline.
Everything asserted was OBSERVED on the running original (recon.md + live probing): * SettingsActivity is a ListView of preference rows (ids title / summary / switch_widget). Two Switch prefs, BOTH default checked="true": "Activate Animation" and "Activate Screen Lock". The correct Switch is the switch_widget whose y is NEAREST the target title's y (never [0]). Toggling flips checked and PERSISTS across a Settings revisit. * "Select theme" row: tap -> AlertDialog System(checked)/Light/Dark. Selecting Dark updates the row summary to "Dark" IN PLACE (activity stays SettingsActivity, the whole UI repaints to a dark palette) and persists. Restore -> System. * "Select Color Scheme" row: tap -> Default(checked)/Original. Selecting Original updates the summary to "Original" and repaints the tile/preview palette (Default = blue gradient, Original = classic orange/tan). Restore -> Default. * CONTINUE-GAME conditional enable: on THIS emulator the 4x4 save survives clear_data, but 5x5/6x6/7x7 have NO save, so button_continueGame is enabled="false" there. Playing a 5x5 game and pressing BACK (graceful save) flips it to enabled="true". * undoButton (GameActivity) is ABSENT from the tree at game start and APPEARS after the first EFFECTIVE move (a blocked move does NOT reveal it). * restartButton resets points -> "0" (state-machine consequence, no dialog). * Drawer item checked: "Main" checked="true" on MainActivity; after navigating to Settings, "Settings" is checked="true" and "Main" checked="false". * StatsActivity tabs (content-desc 4x4/5x5/6x6/7x7): tapping a tab selects it and swaps the visible stat id set (*number1 -> *number2).
LAUNCH QUIRK: restart_app() may RESUME GameActivity (the 4x4 save). _to_main()backs out until button_newGame is present, so every test starts from a realMainActivity regardless of the resumed task."""import os, syssys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from android_testgen_kit import * # noqa: F403,F401
# ── shared helpers ──────────────────────────────────────────────────────────────
def _skip_tutorial(): n = ui() if node_by_id(n, "btn_skip") or find_node_ci(n, "SKIP"): tap_text(ui(), "SKIP") settle("tap")
def _to_main(): """Launch and guarantee we land on MainActivity. restart_app() can resume GameActivity (a saved 4x4 game), so back out until START NEW GAME is present.""" restart_app() wait_for_foreground(15) _skip_tutorial() for _ in range(4): if node_by_id(ui(), "button_newGame") is not None: return True back() settle("tap") return node_by_id(ui(), "button_newGame") is not None
def _open_drawer(): """Open the nav drawer from a surface that carries the hamburger (Main, Stats, Settings, Help). Returns True on a successful tap.""" db = find_node(ui(), content_desc="Open navigation drawer") return tap_node(db) if db else False
def and_enter_settings(): """Main -> drawer -> Settings. CONFIRMS SettingsActivity appeared (the 'Select theme' row is present) and counts one crossed surface, so it BACKS a depth>=1 declaration. Returns True on success.""" if not _open_drawer(): return False settle("tap") if not tap_text(ui(), "Settings"): return False settle("tap") wait_for_foreground(10) ok = find_node(ui(), text="Select theme") is not None if ok: and_enter("settings") return ok
def and_reach_settings(): """_to_main() then and_enter_settings() — a self-contained reach used by tests that need a fresh Settings surface. Returns True on success.""" if not _to_main(): return False return and_enter_settings()
def and_enter_game_mode(mode_index): """Main -> page to `mode_index` (0=4x4..3=7x7) -> START NEW GAME. CONFIRMS the game surface (restartButton present) and counts one crossed surface (backs depth>=1). Returns True on success.""" _goto_mode(mode_index) ng = node_by_id(ui(), "button_newGame") if not ng or not tap_node(ng): return False settle("tap") if node_by_id(ui(), "restartButton") is None: return False and_enter("game") return True
def and_reach_stats(): """Main -> drawer -> Statistics. CONFIRMS a per-mode tab appeared (content-desc '4x4') and counts one crossed surface (backs depth>=1). Returns True.""" if not _open_drawer(): return False settle("tap") if not tap_text(ui(), "Statistics"): return False settle("tap") wait_for_foreground(10) ok = (find_node(ui(), content_desc="4x4") is not None or node_by_id(ui(), "highest_number1") is not None) if ok: and_enter("statistics") return ok
def and_enter_theme_dialog(): """From SettingsActivity, tap 'Select theme' and CONFIRM the AlertDialog opened (radio option 'Dark' present while the settings row 'Activate Animation' left the tree). Counts one crossed surface, so a depth=2 theme test is honestly backed. Returns True.""" row = find_node(ui(), text="Select theme") if not row or not tap_node(row): return False settle("tap") fresh = ui() opened = (find_node_ci(fresh, "Dark") is not None and find_node(fresh, text="Activate Animation") is None) if opened: and_enter("theme_dialog") return opened
def and_enter_color_dialog(): """From SettingsActivity, tap 'Select Color Scheme' and CONFIRM the AlertDialog opened (radio 'Original' present while 'Activate Animation' left the tree). Counts one crossed surface (backs depth=2). Returns True.""" row = find_node(ui(), text="Select Color Scheme") if not row or not tap_node(row): return False settle("tap") fresh = ui() opened = (find_node_ci(fresh, "Original") is not None and find_node(fresh, text="Activate Animation") is None) if opened: and_enter("color_dialog") return opened
def _goto_mode(index): """Page the Main ViewPager to page `index`. btn_prev is absent on page 0 and btn_next absent on the last page — deterministic stops.""" for _ in range(6): p = node_by_id(ui(), "btn_prev") if not p: break tap_node(p) settle("tap") for _ in range(index): nx = node_by_id(ui(), "btn_next") if not nx: break tap_node(nx) settle("tap")
def _switch_for(nodes, title_text): """The switch_widget belonging to a preference row, chosen as the Switch whose y is NEAREST the row title's y. Never assumes document order — there are two Switch prefs and [0] is not necessarily the one meant.""" titles = [x for x in nodes if x.get("resource-id", "").rsplit("/", 1)[-1] == "title" and x.get("text", "") == title_text] if not titles or "_bounds" not in titles[0]: return None ty = titles[0]["_bounds"][1] sws = [x for x in nodes if x.get("resource-id", "").rsplit("/", 1)[-1] == "switch_widget" and "_bounds" in x] if not sws: return None return min(sws, key=lambda s: abs(s["_bounds"][1] - ty))
def _summary_for(nodes, title_text): """The summary TextView directly BELOW a preference row's title (nearest summary with a greater y). Reads the app-authored consequence text of a theme / color selection.""" titles = [x for x in nodes if x.get("resource-id", "").rsplit("/", 1)[-1] == "title" and x.get("text", "") == title_text] if not titles or "_bounds" not in titles[0]: return None ty = titles[0]["_bounds"][1] sums = [x for x in nodes if x.get("resource-id", "").rsplit("/", 1)[-1] == "summary" and "_bounds" in x and x["_bounds"][1] > ty] if not sums: return None return min(sums, key=lambda s: s["_bounds"][1] - ty)
def _drawer_item(nodes, label): """A drawer CheckedTextView (design_menu_item_text) by its text.""" for x in nodes: if (x.get("resource-id", "").rsplit("/", 1)[-1] == "design_menu_item_text" and x.get("text", "") == label): return x return None
def _tiles(nodes=None): nodes = nodes if nodes is not None else ui() return sorted(int(b["text"]) for b in find_by_class(nodes, "Button") if b.get("text", "").strip().isdigit())
def _points(nodes=None): n = node_by_id(nodes if nodes is not None else ui(), "points") if n and n.get("text", "").strip().isdigit(): return int(n["text"].strip()) return None
def _effective_move(): """Make ONE move that changes the board (tries each DPAD direction until the tile multiset changes). Returns True if the board changed. Needed because a blocked move produces no undo affordance and no new tile.""" for k in ("KEYCODE_DPAD_LEFT", "KEYCODE_DPAD_UP", "KEYCODE_DPAD_RIGHT", "KEYCODE_DPAD_DOWN", "KEYCODE_DPAD_UP", "KEYCODE_DPAD_LEFT"): before = _tiles() press_key(k) if _tiles() != before: return True return False
def _play_until_points(cap=14): """Alternate LEFT/UP until points>0 (a merge happened) or cap iters.""" for i in range(cap): press_key("KEYCODE_DPAD_LEFT" if i % 2 == 0 else "KEYCODE_DPAD_UP") p = _points() if p and p > 0: return p return _points() or 0
def _set_theme(option): """From SettingsActivity, open the theme dialog and select `option` (System/Light/Dark). Returns the resulting 'Select theme' summary text (or "").""" row = find_node(ui(), text="Select theme") if not row or not tap_node(row): return "" settle("tap") if not tap_text(ui(), option): # dialog failed to open; dismiss anything transient return "" settle("tap") settle("tap") s = _summary_for(ui(), "Select theme") return s.get("text", "") if s else ""
def _set_color(option): """From SettingsActivity, open the color dialog and select `option` (Default/Original). Returns the resulting 'Select Color Scheme' summary.""" row = find_node(ui(), text="Select Color Scheme") if not row or not tap_node(row): return "" settle("tap") if not tap_text(ui(), option): return "" settle("tap") settle("tap") s = _summary_for(ui(), "Select Color Scheme") return s.get("text", "") if s else ""
# ══════════════════════════════════════════════════════════════════════════════# A. Settings Switch toggles — sole-owner CHECKED, flip + PERSIST# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_animation_toggle", "states_animation_switch_on_off_vlm"))def test_animation_switch_toggles(): """'Activate Animation' Switch: read checked BEFORE, tap it, re-ui(), assert checked FLIPPED true->false. The Switch's own checked flip IS the observable consequence of a preference Switch (there is no separate widget). Restores the original checked value at the end so the baseline is untouched.""" if not and_reach_settings(): record("states_animation_toggle", False, "setup_failed: could not reach Settings", depth=1, jump_kind="transition", expect="Activate Animation checked true->false") vlm_assert("states_animation_switch_on_off", "unreachable", RESULTS_DIR, depth=1, jump_kind="transition", tag="position") return sw = _switch_for(ui(), "Activate Animation") if sw is None: record("states_animation_toggle", False, "feature_missing: no 'Activate Animation' switch", depth=1, jump_kind="transition", expect="Activate Animation checked true->false") vlm_assert("states_animation_switch_on_off", "unreachable", RESULTS_DIR, depth=1, jump_kind="transition", tag="position") return before = sw.get("checked") # VLM (on the ORIGINAL 'true' state): the toggle thumb sits at the ON (right) side. vlm_assert("states_animation_switch_on_off", "In this settings list, is the ON/OFF toggle switch next to " "'Activate Animation' in its ON state, with the thumb slid to the " "RIGHT end of its track?", RESULTS_DIR, depth=1, jump_kind="transition", tag="position") tap_node(sw) settle("tap") after = (_switch_for(ui(), "Activate Animation") or {}).get("checked") ok = before == "true" and after == "false" record("states_animation_toggle", ok, "" if ok else f"behavior_wrong: checked did not flip true->false " f"(before={before}, after={after})", depth=1, jump_kind="transition", expect="'Activate Animation' Switch checked true->false after tap") # restore cur = _switch_for(ui(), "Activate Animation") if cur is not None and cur.get("checked") != before: tap_node(cur) settle("tap")
@and_test(expects=("states_animation_persists_revisit",))def test_animation_persists_across_revisit(): """Flip 'Activate Animation' OFF, LEAVE Settings to Main, RE-ENTER Settings, assert the Switch retained the flipped (false) value — settings persistence, this lane's territory. Restores the default (true) at the end.""" if not and_reach_settings(): record("states_animation_persists_revisit", False, "setup_failed: could not reach Settings", depth=1, jump_kind="transition", expect="animation checked stays false after a Settings revisit") return sw = _switch_for(ui(), "Activate Animation") if sw is None: record("states_animation_persists_revisit", False, "feature_missing: no 'Activate Animation' switch", depth=1, jump_kind="transition", expect="animation checked stays false after a Settings revisit") return original = sw.get("checked") if original != "false": # ensure we start from ON then flip OFF tap_node(sw) settle("tap") flipped = (_switch_for(ui(), "Activate Animation") or {}).get("checked") # leave to Main, then re-enter Settings and_back() # Settings -> Main settle("tap") revisit_ok = and_enter_settings() persisted = (_switch_for(ui(), "Activate Animation") or {}).get("checked") ok = flipped == "false" and revisit_ok and persisted == "false" record("states_animation_persists_revisit", ok, "" if ok else f"behavior_wrong: OFF state not persisted across revisit " f"(flipped={flipped}, after_revisit={persisted})", depth=1, jump_kind="transition", expect="'Activate Animation' checked=false persists after Main->Settings revisit") # restore to the default (true) cur = _switch_for(ui(), "Activate Animation") if cur is not None and cur.get("checked") != "true": tap_node(cur) settle("tap")
@and_test(expects=("states_screenlock_toggle",))def test_screenlock_switch_toggles(): """'Activate Screen Lock' Switch: checked flips true->false on tap. Picks the correct Switch by its neighbouring title (NOT document order). Restores.""" if not and_reach_settings(): record("states_screenlock_toggle", False, "setup_failed: could not reach Settings", depth=1, jump_kind="transition", expect="Activate Screen Lock checked true->false") return sw = _switch_for(ui(), "Activate Screen Lock") if sw is None: record("states_screenlock_toggle", False, "feature_missing: no 'Activate Screen Lock' switch", depth=1, jump_kind="transition", expect="Activate Screen Lock checked true->false") return before = sw.get("checked") tap_node(sw) settle("tap") after = (_switch_for(ui(), "Activate Screen Lock") or {}).get("checked") ok = before == "true" and after == "false" record("states_screenlock_toggle", ok, "" if ok else f"behavior_wrong: screen-lock checked did not flip " f"true->false (before={before}, after={after})", depth=1, jump_kind="transition", expect="'Activate Screen Lock' Switch checked true->false after tap") cur = _switch_for(ui(), "Activate Screen Lock") if cur is not None and cur.get("checked") != before: tap_node(cur) settle("tap")
@and_test(expects=("states_screenlock_persists_revisit",))def test_screenlock_persists_across_revisit(): """Flip 'Activate Screen Lock' OFF, revisit Settings, assert it stayed OFF. Restores the default (true).""" if not and_reach_settings(): record("states_screenlock_persists_revisit", False, "setup_failed: could not reach Settings", depth=1, jump_kind="transition", expect="screen-lock checked stays false across a Settings revisit") return sw = _switch_for(ui(), "Activate Screen Lock") if sw is None: record("states_screenlock_persists_revisit", False, "feature_missing: no 'Activate Screen Lock' switch", depth=1, jump_kind="transition", expect="screen-lock checked stays false across a Settings revisit") return if sw.get("checked") != "false": tap_node(sw) settle("tap") flipped = (_switch_for(ui(), "Activate Screen Lock") or {}).get("checked") and_back() # -> Main settle("tap") revisit_ok = and_enter_settings() persisted = (_switch_for(ui(), "Activate Screen Lock") or {}).get("checked") ok = flipped == "false" and revisit_ok and persisted == "false" record("states_screenlock_persists_revisit", ok, "" if ok else f"behavior_wrong: screen-lock OFF not persisted " f"(flipped={flipped}, after_revisit={persisted})", depth=1, jump_kind="transition", expect="'Activate Screen Lock' checked=false persists across revisit") cur = _switch_for(ui(), "Activate Screen Lock") if cur is not None and cur.get("checked") != "true": tap_node(cur) settle("tap")
# ══════════════════════════════════════════════════════════════════════════════# B. Theme selection — radio selection + summary consequence + persist (+ VLM)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_theme_summary_changes", "states_theme_dark_applied_vlm", "states_theme_system_restored_vlm"))def test_theme_selection_changes_summary(): """Open the theme dialog (depth 2), read the current summary, select Dark, and assert the row summary CHANGED to 'Dark' (the app-authored consequence). Two VLM checks bracket the palette: dark-applied, then light-again after restore. Restores the theme to System (the baseline) at the very end.""" if not and_reach_settings(): record("states_theme_summary_changes", False, "setup_failed: could not reach Settings", depth=2, jump_kind="transition", expect="theme summary System->Dark") vlm_assert("states_theme_dark_applied", "unreachable", RESULTS_DIR, depth=2, jump_kind="transition", tag="color") vlm_assert("states_theme_system_restored", "unreachable", RESULTS_DIR, depth=1, jump_kind="transition", tag="color") return summ0 = _summary_for(ui(), "Select theme") before = summ0.get("text", "") if summ0 else "" if not and_enter_theme_dialog(): record("states_theme_summary_changes", False, "feature_missing: theme dialog did not open", depth=2, jump_kind="transition", expect="theme summary System->Dark") vlm_assert("states_theme_dark_applied", "unreachable", RESULTS_DIR, depth=2, jump_kind="transition", tag="color") vlm_assert("states_theme_system_restored", "unreachable", RESULTS_DIR, depth=1, jump_kind="transition", tag="color") return if tap_text(ui(), "Dark"): settle("tap") settle("tap") summ1 = _summary_for(ui(), "Select theme") after = summ1.get("text", "") if summ1 else "" ok = before == "System" and after == "Dark" record("states_theme_summary_changes", ok, "" if ok else f"behavior_wrong: theme summary did not change to Dark " f"(before={before!r}, after={after!r})", depth=2, jump_kind="transition", expect="'Select theme' summary System->Dark after picking Dark") # VLM #1 — the WHOLE settings screen is now a dark palette (dark bg, light text) vlm_assert("states_theme_dark_applied", "Is this settings screen drawn with a DARK theme, i.e. a near-black " "or dark-grey background behind light-coloured text?", RESULTS_DIR, depth=2, jump_kind="transition", tag="color") # restore to System, then VLM #2 — back to a light palette _set_theme("System") summ2 = _summary_for(ui(), "Select theme") restored = summ2.get("text", "") if summ2 else "" if restored != "System": # last-ditch: make sure baseline is restored _set_theme("System") vlm_assert("states_theme_system_restored", "Is this settings screen drawn with a LIGHT theme, i.e. a white or " "light background behind dark-coloured text?", RESULTS_DIR, depth=1, jump_kind="transition", tag="color")
@and_test(expects=("states_theme_persists_revisit",))def test_theme_persists_across_revisit(): """Select Light, LEAVE Settings, RE-ENTER, assert the summary still reads 'Light' — the theme choice persists. Restores to System at the end.""" if not and_reach_settings(): record("states_theme_persists_revisit", False, "setup_failed: could not reach Settings", depth=1, jump_kind="transition", expect="theme summary stays 'Light' across a Settings revisit") return chosen = _set_theme("Light") if chosen != "Light": record("states_theme_persists_revisit", False, "feature_missing: could not select the 'Light' theme", depth=1, jump_kind="transition", expect="theme summary stays 'Light' across a Settings revisit") _set_theme("System") return and_back() # Settings -> Main settle("tap") revisit_ok = and_enter_settings() summ = _summary_for(ui(), "Select theme") persisted = summ.get("text", "") if summ else "" ok = revisit_ok and persisted == "Light" record("states_theme_persists_revisit", ok, "" if ok else f"behavior_wrong: theme 'Light' not persisted across " f"revisit (after_revisit={persisted!r})", depth=1, jump_kind="transition", expect="'Select theme' summary stays 'Light' after Main->Settings revisit") _set_theme("System") # restore baseline
# ══════════════════════════════════════════════════════════════════════════════# C. Color Scheme — radio selection + summary + persist + palette VLM# ════════��═════════════════════════════════════════════════════════════════════
@and_test(expects=("states_color_summary_changes", "states_color_original_tiles_vlm", "states_color_default_tiles_vlm"))def test_color_selection_changes_summary(): """Open the color dialog (depth 2), select Original, assert the summary changed Default->Original. Then two palette VLM checks on a real game board: Original = orange/tan tiles, Default = blue tiles. Restores color scheme to Default.""" if not and_reach_settings(): record("states_color_summary_changes", False, "setup_failed: could not reach Settings", depth=2, jump_kind="transition", expect="color summary Default->Original") vlm_assert("states_color_original_tiles", "unreachable", RESULTS_DIR, depth=2, jump_kind="transition", tag="color") vlm_assert("states_color_default_tiles", "unreachable", RESULTS_DIR, depth=2, jump_kind="transition", tag="color") return summ0 = _summary_for(ui(), "Select Color Scheme") before = summ0.get("text", "") if summ0 else "" if not and_enter_color_dialog(): record("states_color_summary_changes", False, "feature_missing: color-scheme dialog did not open", depth=2, jump_kind="transition", expect="color summary Default->Original") vlm_assert("states_color_original_tiles", "unreachable", RESULTS_DIR, depth=2, jump_kind="transition", tag="color") vlm_assert("states_color_default_tiles", "unreachable", RESULTS_DIR, depth=2, jump_kind="transition", tag="color") return if tap_text(ui(), "Original"): settle("tap") settle("tap") summ1 = _summary_for(ui(), "Select Color Scheme") after = summ1.get("text", "") if summ1 else "" ok = before == "Default" and after == "Original" record("states_color_summary_changes", ok, "" if ok else f"behavior_wrong: color summary did not change to Original " f"(before={before!r}, after={after!r})", depth=2, jump_kind="transition", expect="'Select Color Scheme' summary Default->Original after picking Original") # VLM #1 — start a game and observe the ORIGINAL (orange/tan) tile palette if and_reach_settings_to_game(0): vlm_assert("states_color_original_tiles", "On this 2048 game board, are the numbered tiles coloured in the " "classic warm ORANGE / TAN / beige palette (NOT blue)?", RESULTS_DIR, depth=2, jump_kind="transition", tag="color") else: vlm_assert("states_color_original_tiles", "unreachable", RESULTS_DIR, depth=2, jump_kind="transition", tag="color") # switch back to Default, start a game, observe the BLUE palette default_ok = False if and_reach_settings(): default_ok = _set_color("Default") == "Default" if default_ok and and_reach_settings_to_game(0): vlm_assert("states_color_default_tiles", "On this 2048 game board, are the numbered tiles coloured in a " "BLUE / blue-gradient palette (NOT orange or tan)?", RESULTS_DIR, depth=2, jump_kind="transition", tag="color") else: vlm_assert("states_color_default_tiles", "unreachable", RESULTS_DIR, depth=2, jump_kind="transition", tag="color")
def and_reach_settings_to_game(mode_index): """Leave the current Settings surface back to Main, then start a new game in `mode_index`. Backs the surface crossings. Returns True once the board shows.""" and_back() # Settings -> Main settle("tap") if node_by_id(ui(), "button_newGame") is None: if not _to_main(): return False return and_enter_game_mode(mode_index)
@and_test(expects=("states_color_persists_revisit", "states_color_preview_changed_vlm"))def test_color_persists_across_revisit(): """Select Original, revisit Settings, assert the summary still reads 'Original' (color-scheme persistence). A VLM check confirms the MainActivity mode-preview image is NOT the default blue after the switch. Restores to Default.""" if not and_reach_settings(): record("states_color_persists_revisit", False, "setup_failed: could not reach Settings", depth=1, jump_kind="transition", expect="color summary stays 'Original' across a Settings revisit") vlm_assert("states_color_preview_changed", "unreachable", RESULTS_DIR, depth=1, jump_kind="transition", tag="color") return chosen = _set_color("Original") if chosen != "Original": record("states_color_persists_revisit", False, "feature_missing: could not select 'Original' color scheme", depth=1, jump_kind="transition", expect="color summary stays 'Original' across a Settings revisit") _set_color("Default") vlm_assert("states_color_preview_changed", "unreachable", RESULTS_DIR, depth=1, jump_kind="transition", tag="color") return and_back() # Settings -> Main settle("tap") revisit_ok = and_enter_settings() summ = _summary_for(ui(), "Select Color Scheme") persisted = summ.get("text", "") if summ else "" ok = revisit_ok and persisted == "Original" record("states_color_persists_revisit", ok, "" if ok else f"behavior_wrong: color 'Original' not persisted across " f"revisit (after_revisit={persisted!r})", depth=1, jump_kind="transition", expect="'Select Color Scheme' summary stays 'Original' after revisit") # VLM — the Main preview image reflects the Original palette (warm, not blue) and_back() # Settings -> Main settle("tap") if node_by_id(ui(), "button_newGame") is None: _to_main() vlm_assert("states_color_preview_changed", "On this home screen, is the small 2048 board preview image drawn in " "warm ORANGE / TAN colours rather than blue?", RESULTS_DIR, depth=1, jump_kind="transition", tag="color") # restore color scheme to Default if and_reach_settings(): _set_color("Default")
# ══════════════════════════════════════════════════════════════════════════════# D. CONTINUE-GAME conditional enable (state machine, transition)# ══════════════════════════════════════════════════════════════════════════════
def _continue_disabled_here(): """True iff button_continueGame is present and enabled='false' on the current Main page (no saved game for this mode).""" cg = node_by_id(ui(), "button_continueGame") return cg is not None and cg.get("enabled") == "false"
def _find_disabled_mode(): """Scan Main pages 0..3 (4x4..7x7) and return the FIRST mode index whose button_continueGame is disabled, i.e. that mode has no saved game yet. Returns None if every mode already has a save. Portable: on a fresh eval emulator no mode has a save, so this simply returns 0; on a contaminated dev emulator it skips modes whose save survived and finds one that is still virgin.""" _goto_mode(0) if _continue_disabled_here(): return 0 for i in range(1, 4): nx = node_by_id(ui(), "btn_next") if not nx or not tap_node(nx): break settle("tap") if _continue_disabled_here(): return i return None
@and_test(expects=("states_continue_enable_transition",))def test_continue_enable_transition(): """CONTINUE-GAME is a conditional-enable state machine: for a mode with NO saved game button_continueGame is enabled='false'; playing that mode and pressing BACK (graceful save) flips it to enabled='true'. The mode is DISCOVERED at runtime (first mode whose continue is disabled), so the test is immune to which modes a prior run may have saved. A shell that never persists cannot flip this.""" if not _to_main(): record("states_continue_enable_transition", False, "setup_failed: could not reach MainActivity", depth=1, jump_kind="transition", expect="continueGame enabled false->true after play+back") return mode = _find_disabled_mode() if mode is None: record("states_continue_enable_transition", False, "setup_failed: no mode has a disabled Continue to observe the " "flip from (every mode already holds a saved game)", depth=1, jump_kind="transition", expect="continueGame enabled false->true after play+back") return # confirm the discovered mode is disabled right now disabled_before = _continue_disabled_here() if not and_enter_game_mode(mode): record("states_continue_enable_transition", False, f"setup_failed: could not start a new game in mode index {mode}", depth=1, jump_kind="transition", expect="continueGame enabled false->true after play+back") return moved = _effective_move() and_back() # Game -> Main; onPause writes the save settle("tap") _goto_mode(mode) # back to the same page cg = node_by_id(ui(), "button_continueGame") enabled_after = cg is not None and cg.get("enabled") == "true" ok = moved and disabled_before and enabled_after record("states_continue_enable_transition", ok, "" if ok else f"behavior_wrong: continueGame did not flip " f"disabled->enabled for mode index {mode} (moved={moved}, " f"before_disabled={disabled_before}, " f"after_enabled={enabled_after})", depth=1, jump_kind="transition", expect="button_continueGame enabled false->true after playing an " "unsaved mode then pressing back")
# ══════════════════════════════════════════════════════════════════════════════# E. undoButton INVISIBLE -> VISIBLE (GameActivity state machine)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_undo_button_appears",))def test_undo_button_invisible_to_visible(): """undoButton is ABSENT from the tree at game start and APPEARS after the first EFFECTIVE move — an invisible->visible page-state transition. Asserts the same GameActivity throughout so it is a state change, not a navigation. The undo affordance is fully dump-readable, so this stays a RULE assertion (no VLM).""" if not _to_main(): record("states_undo_button_appears", False, "setup_failed: could not reach MainActivity", depth=1, jump_kind="transition", expect="undoButton absent->present after first effective move") return if not and_enter_game_mode(0): record("states_undo_button_appears", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="transition", expect="undoButton absent->present after first effective move") return act = get_current_activity() absent_before = node_by_id(ui(), "undoButton") is None moved = _effective_move() present_after = node_by_id(ui(), "undoButton") is not None same_activity = get_current_activity() == act ok = absent_before and moved and present_after and same_activity record("states_undo_button_appears", ok, "" if ok else f"behavior_wrong: undoButton lifecycle wrong " f"(absent_before={absent_before}, moved={moved}, " f"present_after={present_after}, same_activity={same_activity})", depth=1, jump_kind="transition", expect="undoButton absent at start -> present after first effective move (same GameActivity)")
# ══════════════════════════════════════════════════════════════════════════════# F. restartButton resets points to 0 (state-machine consequence)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_restart_zeros_points",))def test_restart_resets_points_to_zero(): """Game-in-progress (points>0) -> tap restartButton -> the state machine returns to a fresh board with points == '0'. A dump-readable numeric consequence, so a RULE assertion (not VLM). Same GameActivity throughout.""" if not _to_main(): record("states_restart_zeros_points", False, "setup_failed: could not reach MainActivity", depth=1, jump_kind="transition", expect="points ->0 after restart") return if not and_enter_game_mode(0): record("states_restart_zeros_points", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="transition", expect="points ->0 after restart") return act = get_current_activity() reached = _play_until_points() pts_before = _points() rb = node_by_id(ui(), "restartButton") if not rb or not tap_node(rb): record("states_restart_zeros_points", False, "setup_failed: restartButton not found/tappable", depth=1, jump_kind="transition", expect="points ->0 after restart") return settle("tap") pts_after = _points() same_activity = get_current_activity() == act ok = (pts_before is not None and pts_before > 0 and pts_after == 0 and same_activity) record("states_restart_zeros_points", ok, "" if ok else f"behavior_wrong: restart did not zero points " f"(before={pts_before}, after={pts_after}, " f"same_activity={same_activity})", depth=1, jump_kind="transition", expect=f"points {pts_before}->0 after tapping restartButton")
# ══════════════════════════════════════════════════════════════════════════════# G. Drawer item CHECKED tracks the active surface (sole-owner CHECKED)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_drawer_checked_follows_surface", "states_drawer_selected_highlight_vlm"))def test_drawer_checked_follows_active_surface(): """On MainActivity the drawer 'Main' item is checked=true and 'Settings' is false. Navigate to Settings, open the drawer there, and assert the checked state MOVED: 'Settings' is now checked=true and 'Main' is checked=false. A VLM check confirms the selected item is visually highlighted.""" if not _to_main(): record("states_drawer_checked_follows_surface", False, "setup_failed: could not reach MainActivity", depth=1, jump_kind="transition", expect="drawer checked Main->Settings across a surface change") vlm_assert("states_drawer_selected_highlight", "unreachable", RESULTS_DIR, depth=1, jump_kind="transition", tag="color") return # drawer on Main if not _open_drawer(): record("states_drawer_checked_follows_surface", False, "setup_failed: no drawer button on MainActivity", depth=1, jump_kind="transition", expect="drawer checked Main->Settings across a surface change") vlm_assert("states_drawer_selected_highlight", "unreachable", RESULTS_DIR, depth=1, jump_kind="transition", tag="color") return settle("tap") dn_main = ui() main_checked_on_main = (_drawer_item(dn_main, "Main") or {}).get("checked") settings_checked_on_main = (_drawer_item(dn_main, "Settings") or {}).get("checked") # navigate to Settings via the open drawer if not tap_text(ui(), "Settings"): record("states_drawer_checked_follows_surface", False, "setup_failed: could not tap 'Settings' in the drawer", depth=1, jump_kind="transition", expect="drawer checked Main->Settings across a surface change") vlm_assert("states_drawer_selected_highlight", "unreachable", RESULTS_DIR, depth=1, jump_kind="transition", tag="color") return settle("tap") wait_for_foreground(10) and_enter("settings") # one crossed surface -> backs depth>=1 # drawer on Settings if not _open_drawer(): record("states_drawer_checked_follows_surface", False, "setup_failed: no drawer button on SettingsActivity", depth=1, jump_kind="transition", expect="drawer checked Main->Settings across a surface change") vlm_assert("states_drawer_selected_highlight", "unreachable", RESULTS_DIR, depth=1, jump_kind="transition", tag="color") return settle("tap") dn_set = ui() main_checked_on_set = (_drawer_item(dn_set, "Main") or {}).get("checked") settings_checked_on_set = (_drawer_item(dn_set, "Settings") or {}).get("checked") ok = (main_checked_on_main == "true" and settings_checked_on_main == "false" and settings_checked_on_set == "true" and main_checked_on_set == "false") record("states_drawer_checked_follows_surface", ok, "" if ok else f"behavior_wrong: drawer checked did not follow surface " f"(on Main: Main={main_checked_on_main} " f"Settings={settings_checked_on_main}; on Settings: " f"Main={main_checked_on_set} Settings={settings_checked_on_set})", depth=1, jump_kind="transition", expect="drawer checked flips Main(true)->Settings(true) after navigating to Settings") # VLM — the currently-selected drawer item is visually highlighted vs the rest vlm_assert("states_drawer_selected_highlight", "In this open navigation drawer, is the 'Settings' menu row visually " "highlighted (a coloured/tinted background or coloured text) that " "sets it apart from the other menu rows?", RESULTS_DIR, depth=1, jump_kind="transition", tag="color") back() # close the drawer settle("tap")
# ══════════════════════════════════════════════════════════════════════════════# H. Stats tab SELECTED state + content swap (transition)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_stats_tab_selected", "states_stats_tab_highlight_vlm"))def test_stats_tab_selected_and_content_swaps(): """On StatsActivity, tapping the 5x5 tab flips its selected state true and swaps the visible stat id set (highest_number1 -> highest_number2). Asserts BOTH the selected transition and the content consequence. A VLM check confirms the active tab is visually highlighted (indicator/colour).""" if not _to_main() or not and_reach_stats(): record("states_stats_tab_selected", False, "setup_failed: could not reach Statistics", depth=1, jump_kind="transition", expect="5x5 tab selected true; stat set 1->2") vlm_assert("states_stats_tab_highlight", "unreachable", RESULTS_DIR, depth=1, jump_kind="transition", tag="color") return tab4 = find_node(ui(), content_desc="4x4") tab4_sel_before = tab4.get("selected") if tab4 else None had_set1 = node_by_id(ui(), "highest_number1") is not None tab5 = find_node(ui(), content_desc="5x5") if tab5 is None or not tap_node(tab5): record("states_stats_tab_selected", False, "feature_missing: no '5x5' stats tab", depth=1, jump_kind="transition", expect="5x5 tab selected true; stat set 1->2") vlm_assert("states_stats_tab_highlight", "unreachable", RESULTS_DIR, depth=1, jump_kind="transition", tag="color") return settle("tap") now = ui() tab5_after = find_node(now, content_desc="5x5") tab5_sel_after = tab5_after.get("selected") if tab5_after else None tab4_after = find_node(now, content_desc="4x4") tab4_sel_after = tab4_after.get("selected") if tab4_after else None has_set2 = node_by_id(now, "highest_number2") is not None ok = (had_set1 and tab5_sel_after == "true" and tab4_sel_after == "false" and has_set2) record("states_stats_tab_selected", ok, "" if ok else f"behavior_wrong: 5x5 tab selection/content did not " f"transition (tab4_sel_before={tab4_sel_before}, " f"tab5_sel_after={tab5_sel_after}, " f"tab4_sel_after={tab4_sel_after}, " f"had_set1={had_set1}, has_set2={has_set2})", depth=1, jump_kind="transition", expect="tapping 5x5 tab: selected true (4x4 false) and stat ids *number1->*number2") # VLM — the active tab is visually highlighted (indicator bar / coloured label) vlm_assert("states_stats_tab_highlight", "In this row of tabs (4x4 / 5x5 / 6x6 / 7x7), is the '5x5' tab " "visually highlighted as the active tab, e.g. by a coloured " "underline indicator or a differently-coloured label, compared with " "the other tabs?", RESULTS_DIR, depth=1, jump_kind="transition", tag="color")
TESTS = [ # A. Settings switches (flip + persist) — sole-owner CHECKED test_animation_switch_toggles, test_animation_persists_across_revisit, test_screenlock_switch_toggles, test_screenlock_persists_across_revisit, # B. Theme (radio selection + summary + persist + VLM palette) test_theme_selection_changes_summary, test_theme_persists_across_revisit, # C. Color scheme (radio selection + summary + persist + VLM palette) test_color_selection_changes_summary, test_color_persists_across_revisit, # D. Continue-game conditional enable (state machine) test_continue_enable_transition, # E. undoButton invisible -> visible test_undo_button_invisible_to_visible, # F. restart zeros points test_restart_resets_points_to_zero, # G. drawer checked tracks active surface test_drawer_checked_follows_active_surface, # H. stats tab selected + content swap test_stats_tab_selected_and_content_swaps,]
if __name__ == "__main__": run_suite(TESTS, "states")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403#!/usr/bin/env python3"""STRUCTURE lane — Privacy Friendly 2048.
Owns exactly two things: 1) the GATE (app launches, MainActivity's top-level surfaces exist), kept to <=30% of tests as jump_kind="none"; 2) tree-SHAPE deltas — an interaction that adds/removes a CLASS of widget, a window layer, or grows a grid — recorded as the shape delta only and reversed.
Everything read from the running original: node counts, container ids, and gridsizes were all OBSERVED (see recon.md + live probing). No content/value/stateassertions live here — those are other lanes."""import os, syssys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from android_testgen_kit import * # noqa: F403,F401
# ── shared helpers ──────────────────────────────────────────────────────────────
def _boot(): """Clean entry point every test: restart, reach foreground, dismiss a possible first-run tutorial. Tolerates the tutorial being present OR absent.""" restart_app() fg = wait_for_foreground(15) n = ui() if node_by_id(n, "btn_skip") or find_node_ci(n, "SKIP"): tap_text(ui(), "SKIP") settle("tap") return fg
def _mode_label(nodes): for x in nodes: if x.get("class", "").endswith("TextView") and x.get("text", "") in ( "4x4", "5x5", "6x6", "7x7"): return x.get("text", "") return ""
def _goto_first_mode(): """Page the MainActivity ViewPager back to page 0 (4x4). btn_prev is INVISIBLE on page 0, so its disappearance is the deterministic stop condition.""" for _ in range(6): p = node_by_id(ui(), "btn_prev") if not p: break tap_node(p) settle("tap") return ui()
def _numeric_tiles(nodes): """Board tiles that currently hold a value are Buttons whose text is a number.""" return [b for b in find_by_class(nodes, "Button") if b.get("text", "").strip().isdigit()]
def and_enter_game(nodes): """Navigate Main -> GameActivity via START NEW GAME and confirm the board surface replaced the launcher. Counts one surface (backs depth>=1).""" btn = node_by_id(nodes, "button_newGame") if not btn: return False before = and_showing(nodes) if not tap_node(btn): return False after = and_showing() # board present AND the launcher's newGame gone == a real surface change if node_by_id(ui(), "number_field") and surface_changed(before, after): and_enter("game") return True return False
def and_enter_drawer_item(nodes, item): """Open the nav drawer from Main and tap a menu item, confirming the surface changed. Counts one surface (backs depth>=1).""" db = find_node(nodes, content_desc="Open navigation drawer") if not db: return False before = and_showing(nodes) tap_node(db) settle("tap") if not tap_text(ui(), item): return False after = and_showing() if surface_changed(before, after): and_enter(item) return True return False
# ══════════════════════════════════════════════════════════════════════════════# GATE (jump_kind="none") — kept to a minority of the suite# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("structure_gate_launch",))def test_gate_launch(): fg = _boot() n = ui() ok = bool(fg and node_by_id(n, "drawer_layout") and node_by_id(n, "view_pager") and node_by_id(n, "button_newGame") and node_by_id(n, "button_continueGame") and node_by_id(n, "toolbar") and find_node(n, content_desc="Open navigation drawer")) record("structure_gate_launch", ok, "" if ok else "setup_failed: MainActivity top-level surfaces " "(drawer_layout/view_pager/newGame/continueGame/toolbar) not all present", depth=0, jump_kind="none")
@and_test(expects=("structure_gate_main_vlm",))def test_gate_main_vlm(): _boot() _goto_first_mode() vlm_assert("structure_gate_main", "Is there a game mode preview card in the upper area and two wide " "buttons stacked near the bottom of the screen?", RESULTS_DIR, depth=0, jump_kind="none", tag="layout")
@and_test(expects=("structure_main_dots_vlm",))def test_main_dots_vlm(): _boot() _goto_first_mode() # layoutDots holds one bullet per mode; on 4x4 the first dot is the active one. vlm_assert("structure_main_dots", "Is there a horizontal row of exactly 4 small round page-indicator " "dots below the preview image?", RESULTS_DIR, depth=0, jump_kind="none", tag="shape")
# ══════════════════════════════════════════════════════════════════════════════# SHAPE deltas# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("structure_drawer_opens", "structure_drawer_opens_vlm"))def test_drawer_opens(): """Opening the nav drawer adds a whole window layer: nav_view + a RecyclerView with 6 CheckedTextView menu rows. Closing removes them again.""" _boot() n = ui() before_menu = len(find_by_class(n, "CheckedTextView")) before_nav = bool(node_by_id(n, "nav_view")) tap_node(find_node(n, content_desc="Open navigation drawer")) settle("tap") o = ui() open_menu = len(find_by_class(o, "CheckedTextView")) open_nav = bool(node_by_id(o, "nav_view")) # reverse it back() settle("tap") close_menu = len(find_by_class(ui(), "CheckedTextView")) ok = (before_menu == 0 and not before_nav and open_nav and open_menu == 6 and close_menu == 0) record("structure_drawer_opens", ok, "" if ok else f"behavior_wrong: drawer shape delta not as observed " f"(menu {before_menu}->{open_menu}->{close_menu}, nav {before_nav}->{open_nav})", depth=0, jump_kind="transition", expect="nav_view+6 CheckedTextView appear on open, gone on close") # re-open for the visual check tap_node(find_node(ui(), content_desc="Open navigation drawer")) settle("tap") vlm_assert("structure_drawer_opens", "Is a vertical navigation menu panel of about six labeled rows shown " "on the left side of the screen?", RESULTS_DIR, depth=0, jump_kind="transition", tag="position")
@and_test(expects=("structure_game_board_appears", "structure_game_board_appears_vlm"))def test_game_board_appears(): """Main -> Game changes the tree shape: the launcher's START NEW GAME button is replaced by a number_field board holding many tile Buttons.""" _boot() n = _goto_first_mode() had_newgame = bool(node_by_id(n, "button_newGame")) entered = and_enter_game(n) g = ui() board = bool(node_by_id(g, "number_field")) n_buttons = len(find_by_class(g, "Button")) gone_newgame = node_by_id(g, "button_newGame") is None ok = bool(had_newgame and entered and board and gone_newgame and n_buttons >= 16) record("structure_game_board_appears", ok, "" if ok else f"behavior_wrong: board did not replace launcher " f"(board={board}, buttons={n_buttons}, newGame_gone={gone_newgame})", depth=1, jump_kind="transition", expect="number_field with >=16 Buttons appears; button_newGame disappears") vlm_assert("structure_game_board_appears", "Is a 4 by 4 grid of equally sized square cells shown in the " "middle of the screen?", RESULTS_DIR, depth=1, jump_kind="transition", tag="shape")
@and_test(expects=("structure_board_size_grows", "structure_board_size_grows_vlm"))def test_board_size_grows(): """A 5x5 board is structurally larger than a 4x4 one: the board holds more tile Buttons. Observed 4x4 -> 20 Buttons, 5x5 -> 29 Buttons (delta 9).""" _boot() _goto_first_mode() if not and_enter_game(ui()): record("structure_board_size_grows", False, "setup_failed: could not open 4x4 game", depth=1, jump_kind="transition", expect="5x5 board has more tile Buttons than 4x4") vlm_assert("structure_board_size_grows", "Is the grid of tiles 5 columns wide and 5 rows tall?", RESULTS_DIR, depth=1, jump_kind="transition", tag="shape") return b4 = len(find_by_class(ui(), "Button")) back() settle("tap") n = _boot() # clean, then page to 5x5 (mode selection persists, so force it) n = _goto_first_mode() nx = node_by_id(n, "btn_next") tapped = tap_node(nx) if nx else False settle("tap") label5 = _mode_label(ui()) entered5 = and_enter_game(ui()) b5 = len(find_by_class(ui(), "Button")) ok = bool(tapped and label5 == "5x5" and entered5 and b5 > b4 and (b5 - b4) >= 5) record("structure_board_size_grows", ok, "" if ok else f"behavior_wrong: board Button count did not grow with " f"mode (4x4={b4}, 5x5={b5}, label={label5})", depth=1, jump_kind="transition", expect=f"5x5 board Buttons ({b5}) > 4x4 board Buttons ({b4})") vlm_assert("structure_board_size_grows", "Is the grid of tiles 5 columns wide and 5 rows tall?", RESULTS_DIR, depth=1, jump_kind="transition", tag="shape")
@and_test(expects=("structure_restart_reseeds", "structure_game_tile_color_vlm"))def test_restart_reseeds(): """restartButton re-seeds the board: after a move that changes the board (tiles become fewer/merged or one more appears), tapping restart returns the board to exactly 2 numeric tiles. Pure shape count — never reads a tile value.""" _boot() _goto_first_mode() if not and_enter_game(ui()): record("structure_restart_reseeds", False, "setup_failed: could not open game", depth=1, jump_kind="transition", expect="restart returns board to 2 numeric tiles") vlm_assert("structure_game_tile_color", "Do the tiles that contain numbers have a solid fill color that " "clearly differs from the empty background cells?", RESULTS_DIR, depth=1, jump_kind="transition", tag="color") return fresh = len(_numeric_tiles(ui())) # make effective moves so the board differs from its seed for k in ("KEYCODE_DPAD_UP", "KEYCODE_DPAD_LEFT", "KEYCODE_DPAD_RIGHT"): press_key(k) after_moves = len(_numeric_tiles(ui())) rb = node_by_id(ui(), "restartButton") tapped = tap_node(rb) if rb else False settle("tap") reseeded = len(_numeric_tiles(ui())) ok = bool(fresh == 2 and tapped and reseeded == 2) record("structure_restart_reseeds", ok, "" if ok else f"behavior_wrong: restart did not re-seed to 2 tiles " f"(fresh={fresh}, after_moves={after_moves}, reseeded={reseeded})", depth=1, jump_kind="transition", expect="numeric tiles: 2 fresh -> board changes on moves -> 2 after restart") vlm_assert("structure_game_tile_color", "Do the tiles that contain numbers have a solid fill color that " "clearly differs from the empty background cells?", RESULTS_DIR, depth=1, jump_kind="transition", tag="color")
@and_test(expects=("structure_settings_list",))def test_settings_list(): """SettingsActivity shows a ListView of preference rows: >=4 title TextViews and the 2 Switch widgets (Animation, Screen Lock).""" _boot() entered = and_enter_drawer_item(ui(), "Settings") s = ui() lists = len(find_by_class(s, "ListView")) titles = len([x for x in s if x.get("resource-id", "").endswith("/title")]) switches = len(find_by_class(s, "Switch")) ok = bool(entered and lists >= 1 and titles >= 4 and switches == 2) record("structure_settings_list", ok, "" if ok else f"feature_missing: settings list shape wrong " f"(ListView={lists}, title rows={titles}, Switch={switches})", depth=1, jump_kind="transition", expect="ListView with >=4 preference title rows and exactly 2 Switch widgets")
@and_test(expects=("structure_stats_tabs", "structure_stats_tabs_vlm"))def test_stats_tabs(): """StatsActivity shows a 4-tab selector (content-desc 4x4/5x5/6x6/7x7) above a content area dense with stat TextViews (>=8).""" _boot() entered = and_enter_drawer_item(ui(), "Statistics") s = ui() tabs = len([x for x in s if x.get("content-desc", "") in ("4x4", "5x5", "6x6", "7x7")]) texts = len(find_by_class(s, "TextView")) ok = bool(entered and tabs == 4 and texts >= 8) record("structure_stats_tabs", ok, "" if ok else f"feature_missing: stats shape wrong " f"(mode tabs={tabs}, TextView={texts})", depth=1, jump_kind="transition", expect="4 mode tabs (4x4..7x7) + >=8 stat TextViews") vlm_assert("structure_stats_tabs", "Is a horizontal row of tab labels positioned across the top of " "the screen, with rows of statistics below it?", RESULTS_DIR, depth=1, jump_kind="transition", tag="position")
@and_test(expects=("structure_help_expand", "structure_help_expand_vlm"))def test_help_expand(): """HelpActivity is an ExpandableListView of 9 question rows. Expanding one adds a body TextView to the tree (TextView count grows by 1); collapsing removes it.""" _boot() entered = and_enter_drawer_item(ui(), "Help") h = ui() groups = len([x for x in h if x.get("resource-id", "").endswith("/listTitle")]) exp_list = len(find_by_class(h, "ExpandableListView")) before_tv = len(find_by_class(h, "TextView")) titles = [x for x in h if x.get("resource-id", "").endswith("/listTitle")] grew = collapsed_back = False after_tv = before_tv if titles: tap_node(titles[0]) settle("tap") after_tv = len(find_by_class(ui(), "TextView")) grew = after_tv == before_tv + 1 # collapse by tapping the same row again t2 = [x for x in ui() if x.get("resource-id", "").endswith("/listTitle")] if t2: tap_node(t2[0]) settle("tap") collapsed_back = len(find_by_class(ui(), "TextView")) == before_tv ok = bool(entered and exp_list >= 1 and groups == 9 and grew and collapsed_back) record("structure_help_expand", ok, "" if ok else f"behavior_wrong: help expand delta wrong " f"(groups={groups}, TextView {before_tv}->{after_tv}, " f"collapsed_back={collapsed_back})", depth=1, jump_kind="transition", expect="9 listTitle rows; expanding a row adds 1 body TextView, " "collapsing removes it") vlm_assert("structure_help_expand", "Is the screen a vertical list of question rows, one per line, like " "an FAQ or expandable help list?", RESULTS_DIR, depth=1, jump_kind="transition", tag="layout")
@and_test(expects=("structure_about_scroll",))def test_about_scroll(): """AboutActivity is a single ScrollView holding many static TextViews (>=6): title, Version/Authors labels, license paragraph, and two link rows.""" _boot() entered = and_enter_drawer_item(ui(), "About") a = ui() scrolls = len(find_by_class(a, "ScrollView")) texts = len(find_by_class(a, "TextView")) ok = bool(entered and scrolls >= 1 and texts >= 6) record("structure_about_scroll", ok, "" if ok else f"feature_missing: about shape wrong " f"(ScrollView={scrolls}, TextView={texts})", depth=1, jump_kind="transition", expect="ScrollView with >=6 static TextViews")
@and_test(expects=("structure_tutorial_slider",))def test_tutorial_slider(): """TutorialActivity is a ViewPager slide deck: a page indicator (layoutDots) and SKIP + NEXT buttons frame the swipeable pager.""" _boot() entered = and_enter_drawer_item(ui(), "Tutorial") t = ui() pager = len(find_by_class(t, "ViewPager")) dots = bool(node_by_id(t, "layoutDots")) skip = bool(node_by_id(t, "btn_skip")) nxt = bool(node_by_id(t, "btn_next")) ok = bool(entered and pager >= 1 and dots and skip and nxt) record("structure_tutorial_slider", ok, "" if ok else f"feature_missing: tutorial shape wrong " f"(ViewPager={pager}, dots={dots}, skip={skip}, next={nxt})", depth=1, jump_kind="transition", expect="ViewPager + layoutDots + SKIP + NEXT buttons")
TESTS = [ test_gate_launch, test_gate_main_vlm, test_main_dots_vlm, test_drawer_opens, test_game_board_appears, test_board_size_grows, test_restart_reseeds, test_settings_list, test_stats_tabs, test_help_expand, test_about_scroll, test_tutorial_slider,]
if __name__ == "__main__": run_suite(TESTS, "structure")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697#!/usr/bin/env python3"""TEXT / CONTENT lane — Privacy Friendly 2048.
Sole owner of EXACT-STRING equality: the words an interaction PRODUCES (a scorethat changes as you play, a body paragraph an FAQ expansion reveals, a slide titlethat a NEXT tap swaps) and the app-unique static labels a recreation must get right(screen titles, section headers, preference titles, stat labels). Cedes the numericDELTA to computation, the checked bit to states, reachability to navigation — thislane asserts only the RENDERED STRING.
Every string below was READ off the running original before it was asserted (casingand spacing verified on-device — recon's approximations were re-derived): * GameActivity header labels are exactly "Points" and "Record"; the `points` TextView starts "0" and rises to a numeric string on a merge; on a clean DB the `record` TextView also starts "0" and tracks max(points). A restart puts `points` back to the exact string "0". * MainActivity mode label is exactly "4x4"; btn_next swaps it to exactly "5x5". * SettingsActivity title "Settings"; preference titles "Select theme", "Activate Animation", "Activate Screen Lock", "Select Color Scheme"; the theme summary reads "System" and the colour-scheme summary reads "Default" by default (summaries share id `summary`, so they are located by their sibling title). * StatsActivity labels: "Highest Number","Highest Score","Playing Time", "Used Undo-Button","Total Amount of Swipes","Time per Swipe","Up","Down","Left", "Right"; `time_played1` renders in the format "0.00 h" (ends " h"); tab TEXT is UPPERCASE "4X4"/"5X5"/"6X6"/"7X7" (content-desc is the lowercase form). * HelpActivity FAQ group titles are the exact 9 strings (id `listTitle`); tapping the first row PRODUCES a body TextView (id `expandedListItem`) beginning "The Privacy Friendly App 2048 is a privacy friendly version of the well-known original game 2048." * TutorialActivity slide 1 title "Welcome!" + body "In the following slides you will learn how to play the Game 2048."; NEXT advances the title to "Learn how to move the numbers!". * AboutActivity labels "Version:" and "Authors:", author names "Saskia Jacob and Julian Wadephul", link texts "SECUSO-Website" and "Github-Repo". The version VALUE ("v 1.4.2") is source-derived and is NEVER asserted.
Two VLM questions (this lane's ceiling), both genuinely NOT in the view tree: * the undo/restart icon-only controls on the game toolbar (empty text + desc), and * the drawn "2048" grid illustration on tutorial slide 1 (a Canvas/vector image)."""import os, syssys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from android_testgen_kit import * # noqa: F403,F401
# ── shared helpers ──────────────────────────────────────────────────────────────
SRC_MAIN = "START NEW GAME" # button_newGame text — Main-only marker
def _boot(): """Clean entry: restart, reach foreground, dismiss a possible first-run tutorial. Tolerates the tutorial being present OR absent (recon note).""" restart_app() wait_for_foreground(15) _skip_tutorial()
def _boot_clean(): """clear_data() first for a virgin DB (record/stats reset to 0), then launch and skip the tutorial if it appears. Used only where a 0-baseline is asserted.""" clear_data() launch_app() wait_for_foreground(15) _skip_tutorial()
def _skip_tutorial(): n = ui() if node_by_id(n, "btn_skip") or find_node_ci(n, "SKIP"): tap_text(ui(), "SKIP") settle("tap")
def all_text(nodes): return " | ".join(n.get("text", "") for n in nodes if n.get("text"))
def _norm(s): return (s or "").strip()
def _points_str(nodes=None): n = node_by_id(nodes if nodes is not None else ui(), "points") return _norm(n.get("text")) if n else None
def _record_str(nodes=None): n = node_by_id(nodes if nodes is not None else ui(), "record") return _norm(n.get("text")) if n else None
def _mode_label(nodes): for x in nodes: if x.get("class", "").endswith("TextView") and x.get("text", "") in ( "4x4", "5x5", "6x6", "7x7"): return x.get("text", "") return ""
def _goto_first_mode(): """Page the Main ViewPager back to page 0 (4x4). btn_prev is absent on page 0.""" for _ in range(6): p = node_by_id(ui(), "btn_prev") if not p: break tap_node(p) settle("tap") return ui()
def _summary_for(title): """Value of the `summary` TextView that sits directly under the preference row whose title == `title`. Both rows share id `summary`, so match by y-position: the summary is the `summary`-id node whose top y is just below the title's.""" nodes = ui() trow = None for n in nodes: if n.get("resource-id", "").rsplit("/", 1)[-1] == "title" \ and _norm(n.get("text")) == title: trow = n break if trow is None: return None ty = trow.get("_bounds", (0, 0, 0, 0))[1] best, best_dy = None, 10 ** 9 for n in nodes: if n.get("resource-id", "").rsplit("/", 1)[-1] != "summary": continue sy = n.get("_bounds", (0, 0, 0, 0))[1] dy = sy - ty if 0 <= dy < best_dy: best, best_dy = n, dy return _norm(best.get("text")) if best else None
# ── depth-backing navigation helpers (named and_enter_* so depth>=1 is audited) ──
def _open_drawer(): db = find_node(ui(), content_desc="Open navigation drawer") return bool(db) and tap_node(db)
def and_enter_game(): """Main -> START NEW GAME -> GameActivity. Confirms the game surface (points + the game 'Record' label appeared) and counts one crossed surface. Backs depth>=1.""" ng = node_by_id(ui(), "button_newGame") if not ng or not tap_node(ng): return False settle("tap") fresh = ui() if node_by_id(fresh, "points") is None: return False and_enter("game") return True
def and_enter_drawer_dest(item, confirm_text): """Main -> (open drawer) -> tap `item`, then CONFIRM the destination by its own text `confirm_text` appearing while Main's START NEW GAME vanished. Counts one surface. The and_enter_* NAME is what the depth audit reads.""" if not _open_drawer(): return False settle("tap") if not tap_text(ui(), item): return False settle("tap") now = ui() reached = (find_node_ci(now, confirm_text) is not None and find_node_ci(now, SRC_MAIN) is None) if reached: and_enter(item) return reached
def and_enter_settings(): return and_enter_drawer_dest("Settings", "Select theme")
def and_enter_stats(): return and_enter_drawer_dest("Statistics", "Highest Number")
def and_enter_help(): return and_enter_drawer_dest("Help", "What is the goal of this game?")
def and_enter_about(): return and_enter_drawer_dest("About", "Version:")
def and_enter_tutorial(): return and_enter_drawer_dest("Tutorial", "Welcome!")
# ══════════════════════════════════════════════════════════════════════════════# (A) DYNAMIC score strings — the app COMPUTES these; the STRING must change# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("text_points_updates_on_merge",))def test_points_updates_on_merge(): """points TextView starts as the exact string '0'; a merge move changes the RENDERED string to a specific non-'0' numeric value. Text owns the string flip (absent '<observed>' before, present after); computation owns the numeric delta.""" _boot_clean() _goto_first_mode() if not and_enter_game(): record("text_points_updates_on_merge", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="transition", expect="points text '0' -> a non-'0' numeric string after a merge") return start = _points_str() reached = None for i in range(16): press_key("KEYCODE_DPAD_LEFT" if i % 2 == 0 else "KEYCODE_DPAD_UP") cur = _points_str() if cur and cur.isdigit() and int(cur) > 0: reached = cur break ok = (start == "0" and reached is not None and reached != "0" and reached.isdigit()) record("text_points_updates_on_merge", ok, "" if ok else f"behavior_wrong: points string did not update from '0' " f"to a non-'0' value (start={start!r}, after={reached!r})", depth=1, jump_kind="transition", expect=f"points text '0' -> '{reached}' after a scoring move")
@and_test(expects=("text_record_reflects_best",))def test_record_reflects_best(): """On a clean DB the record TextView starts '0' and, as points climb past it, the RENDERED record string becomes exactly the points string (record = best).""" _boot_clean() _goto_first_mode() if not and_enter_game(): record("text_record_reflects_best", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="transition", expect="record text '0' -> equals the points string after play") return start_rec = _record_str() pts_after = None for i in range(16): press_key("KEYCODE_DPAD_LEFT" if i % 2 == 0 else "KEYCODE_DPAD_UP") p = _points_str() if p and p.isdigit() and int(p) > 0: pts_after = p break rec_after = _record_str() ok = (start_rec == "0" and pts_after is not None and rec_after == pts_after and rec_after != "0") record("text_record_reflects_best", ok, "" if ok else f"behavior_wrong: record string did not reflect the best " f"score (start_record={start_rec!r}, points={pts_after!r}, " f"record={rec_after!r})", depth=1, jump_kind="transition", expect=f"record text '0' -> '{pts_after}' (== points) after play")
@and_test(expects=("text_points_resets_to_zero",))def test_points_resets_to_zero(): """After a scoring move the points string is non-'0'; tapping restartButton puts the RENDERED string back to exactly '0' (the string consequence of a re-seed).""" _boot_clean() _goto_first_mode() if not and_enter_game(): record("text_points_resets_to_zero", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="transition", expect="points text non-'0' -> '0' after restart") return raised = None for i in range(16): press_key("KEYCODE_DPAD_LEFT" if i % 2 == 0 else "KEYCODE_DPAD_UP") p = _points_str() if p and p.isdigit() and int(p) > 0: raised = p break r = node_by_id(ui(), "restartButton") tapped = tap_node(r) if r else False settle("tap") after = _points_str() ok = raised is not None and raised != "0" and tapped and after == "0" record("text_points_resets_to_zero", ok, "" if ok else f"behavior_wrong: points string did not reset to '0' after " f"restart (raised={raised!r}, after={after!r}, " f"restart_tapped={tapped})", depth=1, jump_kind="transition", expect=f"points text '{raised}' -> '0' after tapping restart")
@and_test(expects=("text_game_header_labels",))def test_game_header_labels(): """Entering the game BRINGS UP the exact static header labels 'Points' and 'Record' (the section headers a recreation of the score bar must render).""" _boot() _goto_first_mode() if not and_enter_game(): record("text_game_header_labels", False, "setup_failed: could not start a new 4x4 game", depth=1, jump_kind="none", expect="GameActivity shows 'Points' and 'Record' header labels") return n = ui() ok = (find_node(n, text="Points") is not None and find_node(n, text="Record") is not None) record("text_game_header_labels", ok, "" if ok else "behavior_wrong: game header labels 'Points'/'Record' " "not both present", depth=1, jump_kind="none", expect="exact labels 'Points' and 'Record' shown on GameActivity")
# ══════════════════════════════════════════════════════════════════════════════# (B) DYNAMIC MainActivity mode label — changes with the ViewPager# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("text_mode_label_pages_4to5",))def test_mode_label_pages_4to5(): """The mode label TextView reads exactly '4x4' on page 0; tapping btn_next swaps the RENDERED string to exactly '5x5'. In-page string flip (depth 0).""" _boot() _goto_first_mode() start = _mode_label(ui()) absent_5 = "5x5" not in all_text(ui()) nx = node_by_id(ui(), "btn_next") tapped = tap_node(nx) if nx else False settle("tap") end = _mode_label(ui()) ok = start == "4x4" and absent_5 and tapped and end == "5x5" record("text_mode_label_pages_4to5", ok, "" if ok else f"behavior_wrong: mode label did not change '4x4'->'5x5' " f"(start={start!r}, end={end!r}, next_tapped={tapped})", depth=0, jump_kind="transition", expect="mode label text '4x4' -> '5x5' after btn_next")
# ══════════════════════════════════════════════════════════════════════════════# (C) Settings — preference titles + summaries reflect the current selection# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("text_settings_titles",))def test_settings_titles(): """SettingsActivity renders the exact title 'Settings' and the four preference TITLE strings a recreation must match.""" _boot() if not and_enter_settings(): record("text_settings_titles", False, "setup_failed: could not reach Settings", depth=1, jump_kind="none", expect="Settings preference titles shown exactly") return n = ui() want = ["Settings", "Select theme", "Activate Animation", "Activate Screen Lock", "Select Color Scheme"] missing = [w for w in want if find_node(n, text=w) is None] ok = not missing record("text_settings_titles", ok, "" if ok else f"behavior_wrong: Settings missing exact title strings " f"{missing}", depth=1, jump_kind="none", expect="titles 'Settings','Select theme','Activate Animation'," "'Activate Screen Lock','Select Color Scheme' all present")
@and_test(expects=("text_theme_summary",))def test_theme_summary(): """The 'Select theme' row's summary renders the current value; on the default DB it is exactly 'System'. Asserted by exact-equality to the observed value.""" _boot() if not and_enter_settings(): record("text_theme_summary", False, "setup_failed: could not reach Settings", depth=1, jump_kind="none", expect="theme summary reads 'System'") return summ = _summary_for("Select theme") ok = summ == "System" record("text_theme_summary", ok, "" if ok else f"behavior_wrong: 'Select theme' summary is {summ!r}, " f"expected exactly 'System'", depth=1, jump_kind="none", expect="'Select theme' summary text == 'System'")
@and_test(expects=("text_color_scheme_summary",))def test_color_scheme_summary(): """The 'Select Color Scheme' row's summary renders the current value; on the default DB it is exactly 'Default'.""" _boot() if not and_enter_settings(): record("text_color_scheme_summary", False, "setup_failed: could not reach Settings", depth=1, jump_kind="none", expect="colour-scheme summary reads 'Default'") return summ = _summary_for("Select Color Scheme") ok = summ == "Default" record("text_color_scheme_summary", ok, "" if ok else f"behavior_wrong: 'Select Color Scheme' summary is " f"{summ!r}, expected exactly 'Default'", depth=1, jump_kind="none", expect="'Select Color Scheme' summary text == 'Default'")
# ══════════════════════════════════════════════════════════════════════════════# (D) Statistics — labels, a formatted value, and the tab TEXT casing# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("text_stats_labels",))def test_stats_labels(): """StatsActivity renders the exact row-label strings the recreation must match on the default 4x4 tab.""" _boot() if not and_enter_stats(): record("text_stats_labels", False, "setup_failed: could not reach Statistics", depth=1, jump_kind="none", expect="Stats row labels shown exactly") return n = ui() want = ["Highest Number", "Highest Score", "Playing Time", "Used Undo-Button", "Total Amount of Swipes", "Time per Swipe", "Up", "Down", "Left", "Right"] missing = [w for w in want if find_node(n, text=w) is None] ok = not missing record("text_stats_labels", ok, "" if ok else f"behavior_wrong: Statistics missing exact label strings " f"{missing}", depth=1, jump_kind="none", expect="all 10 stat labels ('Highest Number'..'Right') present exactly")
@and_test(expects=("text_stats_playing_time_format",))def test_stats_playing_time_format(): """The Playing-Time value (id time_played1) renders in the hours format ending ' h' — observed 'X.XX h' (e.g. '0.00 h'). Asserts the rendered format string.""" _boot() if not and_enter_stats(): record("text_stats_playing_time_format", False, "setup_failed: could not reach Statistics", depth=1, jump_kind="none", expect="Playing Time value formatted as 'N.NN h'") return node = node_by_id(ui(), "time_played1") val = _norm(node.get("text")) if node else None ok = bool(val) and val.endswith(" h") and val[:-2].strip().count(".") == 1 \ and val[:-2].strip().replace(".", "").isdigit() record("text_stats_playing_time_format", ok, "" if ok else f"behavior_wrong: Playing Time value {val!r} is not the " f"'N.NN h' hours format", depth=1, jump_kind="none", expect="time_played1 renders like '0.00 h' (a decimal followed by ' h')")
@and_test(expects=("text_stats_tab_labels",))def test_stats_tab_labels(): """The stat tab TEXT is UPPERCASE — exactly '4X4'/'5X5'/'6X6'/'7X7' (distinct from the lowercase content-desc). Asserts the rendered tab strings.""" _boot() if not and_enter_stats(): record("text_stats_tab_labels", False, "setup_failed: could not reach Statistics", depth=1, jump_kind="none", expect="tab texts '4X4'/'5X5'/'6X6'/'7X7' shown") return n = ui() want = ["4X4", "5X5", "6X6", "7X7"] missing = [w for w in want if find_node(n, text=w) is None] ok = not missing record("text_stats_tab_labels", ok, "" if ok else f"behavior_wrong: Statistics tab texts missing/wrong casing " f"{missing} (expected uppercase '4X4'..'7X7')", depth=1, jump_kind="none", expect="tab texts exactly '4X4','5X5','6X6','7X7' (uppercase)")
# ══════════════════════════════════════════════════════════════════════════════# (E) Help — FAQ group titles, and an EXPANSION that PRODUCES a body paragraph# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("text_help_faq_titles",))def test_help_faq_titles(): """HelpActivity renders the exact FAQ group-title strings (id listTitle).""" _boot() if not and_enter_help(): record("text_help_faq_titles", False, "setup_failed: could not reach Help", depth=1, jump_kind="none", expect="FAQ group titles shown exactly") return n = ui() want = ["What is Privacy Friendly App 2048?", "How do I move the numbers?", "Is it possible to undo steps?", "How can I change the color spectre of the game?"] missing = [w for w in want if find_node(n, text=w) is None] ok = not missing record("text_help_faq_titles", ok, "" if ok else f"behavior_wrong: Help missing exact FAQ title strings " f"{missing}", depth=1, jump_kind="none", expect="FAQ titles incl. 'What is Privacy Friendly App 2048?' present")
@and_test(expects=("text_help_expansion_reveals_body",))def test_help_expansion_reveals_body(): """Tapping the first FAQ row EXPANDS it and PRODUCES a body TextView (id expandedListItem). The body string is ABSENT before the tap and PRESENT after — the discriminating half. depth 2: entered Help, then expanded within it.""" _boot() if not and_enter_help(): record("text_help_expansion_reveals_body", False, "setup_failed: could not reach Help", depth=2, jump_kind="transition", expect="FAQ body paragraph appears after expanding the first row") return body_frag = "privacy friendly version of the well-known original game 2048" absent = body_frag.lower() not in all_text(ui()).lower() row = find_node(ui(), text="What is Privacy Friendly App 2048?") tapped = tap_node(row) if row else False settle("tap") settle("tap") and_enter("help-expanded") after = all_text(ui()).lower() present = body_frag.lower() in after ok = absent and tapped and present record("text_help_expansion_reveals_body", ok, "" if ok else f"behavior_wrong: expanding the first FAQ row did not " f"reveal its body text (absent_before={absent}, " f"tapped={tapped}, present_after={present})", depth=2, jump_kind="transition", expect="body '...privacy friendly version of the well-known original " "game 2048' appears only after the row is expanded")
# ══════════════════════════════════════════════════════════════════════════════# (F) Tutorial — slide 1 title/body, and NEXT advancing the title# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("text_tutorial_slide1", "text_tutorial_illustration_vlm"))def test_tutorial_slide1(): """TutorialActivity slide 1 renders the exact title 'Welcome!' and body 'In the following slides you will learn how to play the Game 2048.'. VLM: the slide's drawn '2048' grid illustration is a Canvas/vector image, NOT in the view tree.""" _boot() if not and_enter_tutorial(): record("text_tutorial_slide1", False, "setup_failed: could not reach Tutorial", depth=1, jump_kind="none", expect="slide 1 title 'Welcome!' and its body shown") vlm_assert("text_tutorial_illustration", "Is a large white '2048' shown drawn inside a grid/hash pattern " "in the centre of the screen?", RESULTS_DIR, depth=1, jump_kind="none", tag="shape") return n = ui() title_ok = find_node(n, text="Welcome!") is not None body_ok = find_node( n, text="In the following slides you will learn how to play the Game 2048." ) is not None ok = title_ok and body_ok record("text_tutorial_slide1", ok, "" if ok else f"behavior_wrong: slide 1 strings wrong " f"(title_ok={title_ok}, body_ok={body_ok})", depth=1, jump_kind="none", expect="slide 1 title 'Welcome!' and body 'In the following slides you " "will learn how to play the Game 2048.'") # VLM: the illustration glyphs are drawn (vector), not TextViews in the tree. vlm_assert("text_tutorial_illustration", "Is a large white '2048' shown drawn inside a grid/hash pattern in " "the centre of the screen?", RESULTS_DIR, depth=1, jump_kind="none", tag="shape") # leave tidy: SKIP back to Main if tap_text(ui(), "SKIP"): settle("tap")
@and_test(expects=("text_tutorial_next_advances_title",))def test_tutorial_next_advances_title(): """Tapping NEXT swaps the slide TITLE from 'Welcome!' to the exact slide-2 title 'Learn how to move the numbers!'. The new title is ABSENT before, PRESENT after. depth 2: entered Tutorial, then advanced within it. SKIPs back to Main after.""" _boot() if not and_enter_tutorial(): record("text_tutorial_next_advances_title", False, "setup_failed: could not reach Tutorial", depth=2, jump_kind="transition", expect="title advances 'Welcome!' -> 'Learn how to move the numbers!'") return slide2 = "Learn how to move the numbers!" on_slide1 = find_node(ui(), text="Welcome!") is not None absent = slide2.lower() not in all_text(ui()).lower() nx = node_by_id(ui(), "btn_next") tapped = tap_node(nx) if nx else False settle("tap") and_enter("tutorial-slide2") present = find_node(ui(), text=slide2) is not None ok = on_slide1 and absent and tapped and present record("text_tutorial_next_advances_title", ok, "" if ok else f"behavior_wrong: NEXT did not advance the slide title to " f"{slide2!r} (on_slide1={on_slide1}, absent_before={absent}, " f"tapped={tapped}, present_after={present})", depth=2, jump_kind="transition", expect=f"slide title 'Welcome!' -> '{slide2}' after tapping NEXT") # leave tidy: SKIP back to Main if tap_text(ui(), "SKIP"): settle("tap")
# ══════════════════════════════════════════════════════════════════════════════# (G) About — labels + link texts (never the source-derived version VALUE)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("text_about_labels",))def test_about_labels(): """AboutActivity renders the exact label strings 'Version:' and 'Authors:', the author names, and both link texts. The version NUMBER value is deliberately NOT asserted (it is source-derived and a recreation cannot know it).""" _boot() if not and_enter_about(): record("text_about_labels", False, "setup_failed: could not reach About", depth=1, jump_kind="none", expect="About labels + link texts shown exactly") return n = ui() want = ["Version:", "Authors:", "Saskia Jacob and Julian Wadephul", "SECUSO-Website", "Github-Repo"] missing = [w for w in want if find_node(n, text=w) is None] ok = not missing record("text_about_labels", ok, "" if ok else f"behavior_wrong: About missing exact strings {missing}", depth=1, jump_kind="none", expect="labels 'Version:'/'Authors:', authors 'Saskia Jacob and Julian " "Wadephul', links 'SECUSO-Website'/'Github-Repo' all present")
# ══════════════════════════════════════════════════════════════════════════════# (H) VLM — icon-only controls whose meaning is rendered, not in the tree# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("text_game_icon_controls_vlm",))def test_game_icon_controls(): """The undo (curved ↶) and restart (circular ⟳) controls on the game toolbar are icon-only — empty text AND empty content-desc — so their MEANING reaches the screen only as a rendered glyph, never the view tree. That is this lane's one legitimate opaque-core case. A move is made first so the undo icon is visible.""" _boot() _goto_first_mode() if not and_enter_game(): vlm_assert("text_game_icon_controls", "Are there two dark rounded-square icon buttons below the " "'Points' and 'Record' labels — a curved undo arrow on the left " "and a circular refresh/restart arrow on the right?", RESULTS_DIR, depth=1, jump_kind="none", tag="shape") return press_key("KEYCODE_DPAD_LEFT") press_key("KEYCODE_DPAD_UP") settle("tap") vlm_assert("text_game_icon_controls", "Are there two dark rounded-square icon buttons below the 'Points' " "and 'Record' labels — a curved undo arrow on the left and a " "circular refresh/restart arrow on the right?", RESULTS_DIR, depth=1, jump_kind="none", tag="shape")
TESTS = [ # (A) dynamic score strings test_points_updates_on_merge, test_record_reflects_best, test_points_resets_to_zero, test_game_header_labels, # (B) dynamic mode label test_mode_label_pages_4to5, # (C) settings titles + summaries test_settings_titles, test_theme_summary, test_color_scheme_summary, # (D) stats labels + value + tabs test_stats_labels, test_stats_playing_time_format, test_stats_tab_labels, # (E) help titles + expansion body test_help_faq_titles, test_help_expansion_reveals_body, # (F) tutorial slide title/body + NEXT test_tutorial_slide1, test_tutorial_next_advances_title, # (G) about labels test_about_labels, # (H) VLM icon-only controls test_game_icon_controls,]
if __name__ == "__main__": run_suite(TESTS, "text")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857{ "manifest_version": 1, "kit_api_version": 1, "task_id": "privacy-friendly-2048", "baseline_model": "claude-opus-4-8", "baseline_package": "", "total": 132, "manifest_sha": "0ff7282d13b8", "tests": [ { "name": "computation::computation_5x5_grid_vlm", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_5x5_larger_grid", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_blocked_move_no_change", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_blocked_move_no_new_tile", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_effective_move_sum_delta", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_fresh_seed_two_tiles", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_merge_collapses_pair", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_merge_pair_value", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_merge_scores_points", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_points_accumulate", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_record_is_max", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_record_monotonic", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_restart_resets", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_restart_then_move", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_restart_two_tiles_vlm", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_slide_adds_one_tile", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_sum_growth_bounded", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_two_slides_add_two", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_undo_once", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_undo_restores_points", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_undo_restores_tile_count", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_undo_then_replay", "module": "computation", "baseline_status": "passed" }, { "name": "interaction::interaction_5x5_larger_grid_vlm", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_accumulated_score_persists", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_continue_enable_after_play_back", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_continue_mode_correct", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_continue_repeatable", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_kill_without_back_not_saved", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_merged_tiles_colored_vlm", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_persist_after_kill", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_persist_board_restored_vlm", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_restart_icon_visible_vlm", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_restart_reseeds_board", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_restart_then_persist", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_restart_then_playable", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_restart_two_tiles_vlm", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_stats_highest_number", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_stats_highest_score", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_stats_mode_isolation", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_stats_moves_increment", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_stats_nonzero_vlm", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_stats_overflow_menu", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_stats_undo_counter", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_two_saved_games", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_undo_board_reverted_vlm", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_undo_icon_visible_vlm", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_undo_once_per_move", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_undo_reverts_points", "module": "interaction", "baseline_status": "passed" }, { "name": "navigation::nav_back_about_to_main", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_back_game_to_main", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_back_settings_to_main", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_back_stats_to_main", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_deep_color_dialog", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_deep_game_roundtrip", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_deep_stats_tab_content", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_deep_theme_dialog", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_deep_theme_dialog_vlm", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_pager_last_arrow_vlm", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_pager_next_4to5", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_pager_prev_5to4", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_pager_to_last_7x7", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_reach_about", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_reach_about_vlm", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_reach_continue_game", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_reach_game_new", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_reach_game_new_vlm", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_reach_help", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_reach_help_vlm", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_reach_settings", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_reach_settings_vlm", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_reach_statistics", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_reach_statistics_vlm", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_reach_tutorial", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_reach_tutorial_vlm", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_stats_tab_4to5", "module": "navigation", "baseline_status": "passed" }, { "name": "states::states_animation_persists_revisit", "module": "states", "baseline_status": "passed" }, { "name": "states::states_animation_switch_on_off_vlm", "module": "states", "baseline_status": "passed" }, { "name": "states::states_animation_toggle", "module": "states", "baseline_status": "passed" }, { "name": "states::states_color_default_tiles_vlm", "module": "states", "baseline_status": "passed" }, { "name": "states::states_color_original_tiles_vlm", "module": "states", "baseline_status": "passed" }, { "name": "states::states_color_persists_revisit", "module": "states", "baseline_status": "passed" }, { "name": "states::states_color_preview_changed_vlm", "module": "states", "baseline_status": "passed" }, { "name": "states::states_color_summary_changes", "module": "states", "baseline_status": "passed" }, { "name": "states::states_continue_enable_transition", "module": "states", "baseline_status": "passed" }, { "name": "states::states_drawer_checked_follows_surface", "module": "states", "baseline_status": "passed" }, { "name": "states::states_drawer_selected_highlight_vlm", "module": "states", "baseline_status": "passed" }, { "name": "states::states_restart_zeros_points", "module": "states", "baseline_status": "passed" }, { "name": "states::states_screenlock_persists_revisit", "module": "states", "baseline_status": "passed" }, { "name": "states::states_screenlock_toggle", "module": "states", "baseline_status": "passed" }, { "name": "states::states_stats_tab_highlight_vlm", "module": "states", "baseline_status": "passed" }, { "name": "states::states_stats_tab_selected", "module": "states", "baseline_status": "passed" }, { "name": "states::states_theme_dark_applied_vlm", "module": "states", "baseline_status": "passed" }, { "name": "states::states_theme_persists_revisit", "module": "states", "baseline_status": "passed" }, { "name": "states::states_theme_summary_changes", "module": "states", "baseline_status": "passed" }, { "name": "states::states_theme_system_restored_vlm", "module": "states", "baseline_status": "passed" }, { "name": "states::states_undo_button_appears", "module": "states", "baseline_status": "passed" }, { "name": "structure::structure_about_scroll", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_board_size_grows", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_board_size_grows_vlm", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_drawer_opens", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_drawer_opens_vlm", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_game_board_appears", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_game_board_appears_vlm", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_game_tile_color_vlm", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_gate_launch", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_gate_main_vlm", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_help_expand", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_help_expand_vlm", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_main_dots_vlm", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_restart_reseeds", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_settings_list", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_stats_tabs", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_stats_tabs_vlm", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_tutorial_slider", "module": "structure", "baseline_status": "passed" }, { "name": "text::text_about_labels", "module": "text", "baseline_status": "passed" }, { "name": "text::text_color_scheme_summary", "module": "text", "baseline_status": "passed" }, { "name": "text::text_game_header_labels", "module": "text", "baseline_status": "passed" }, { "name": "text::text_game_icon_controls_vlm", "module": "text", "baseline_status": "passed" }, { "name": "text::text_help_expansion_reveals_body", "module": "text", "baseline_status": "passed" }, { "name": "text::text_help_faq_titles", "module": "text", "baseline_status": "passed" }, { "name": "text::text_mode_label_pages_4to5", "module": "text", "baseline_status": "passed" }, { "name": "text::text_points_resets_to_zero", "module": "text", "baseline_status": "passed" }, { "name": "text::text_points_updates_on_merge", "module": "text", "baseline_status": "passed" }, { "name": "text::text_record_reflects_best", "module": "text", "baseline_status": "passed" }, { "name": "text::text_settings_titles", "module": "text", "baseline_status": "passed" }, { "name": "text::text_stats_labels", "module": "text", "baseline_status": "passed" }, { "name": "text::text_stats_playing_time_format", "module": "text", "baseline_status": "passed" }, { "name": "text::text_stats_tab_labels", "module": "text", "baseline_status": "passed" }, { "name": "text::text_theme_summary", "module": "text", "baseline_status": "passed" }, { "name": "text::text_tutorial_illustration_vlm", "module": "text", "baseline_status": "passed" }, { "name": "text::text_tutorial_next_advances_title", "module": "text", "baseline_status": "passed" }, { "name": "text::text_tutorial_slide1", "module": "text", "baseline_status": "passed" } ], "ignored": [], "vlm_assertions": [ { "name": "computation::computation_restart_two_tiles_vlm", "module": "computation", "tag": "position" }, { "name": "computation::computation_5x5_grid_vlm", "module": "computation", "tag": "size" }, { "name": "interaction::interaction_persist_board_restored_vlm", "module": "interaction", "tag": "content" }, { "name": "interaction::interaction_undo_board_reverted_vlm", "module": "interaction", "tag": "content" }, { "name": "interaction::interaction_undo_icon_visible_vlm", "module": "interaction", "tag": "shape" }, { "name": "interaction::interaction_restart_two_tiles_vlm", "module": "interaction", "tag": "position" }, { "name": "interaction::interaction_merged_tiles_colored_vlm", "module": "interaction", "tag": "color" }, { "name": "interaction::interaction_stats_nonzero_vlm", "module": "interaction", "tag": "content" }, { "name": "interaction::interaction_5x5_larger_grid_vlm", "module": "interaction", "tag": "size" }, { "name": "interaction::interaction_restart_icon_visible_vlm", "module": "interaction", "tag": "shape" }, { "name": "navigation::nav_reach_statistics_vlm", "module": "navigation", "tag": "position" }, { "name": "navigation::nav_reach_settings_vlm", "module": "navigation", "tag": "position" }, { "name": "navigation::nav_reach_help_vlm", "module": "navigation", "tag": "layout" }, { "name": "navigation::nav_reach_about_vlm", "module": "navigation", "tag": "content" }, { "name": "navigation::nav_reach_tutorial_vlm", "module": "navigation", "tag": "position" }, { "name": "navigation::nav_reach_game_new_vlm", "module": "navigation", "tag": "position" }, { "name": "navigation::nav_pager_last_arrow_vlm", "module": "navigation", "tag": "position" }, { "name": "navigation::nav_deep_theme_dialog_vlm", "module": "navigation", "tag": "shape" }, { "name": "states::states_animation_switch_on_off_vlm", "module": "states", "tag": "position" }, { "name": "states::states_theme_dark_applied_vlm", "module": "states", "tag": "color" }, { "name": "states::states_theme_system_restored_vlm", "module": "states", "tag": "color" }, { "name": "states::states_color_original_tiles_vlm", "module": "states", "tag": "color" }, { "name": "states::states_color_default_tiles_vlm", "module": "states", "tag": "color" }, { "name": "states::states_color_preview_changed_vlm", "module": "states", "tag": "color" }, { "name": "states::states_drawer_selected_highlight_vlm", "module": "states", "tag": "color" }, { "name": "states::states_stats_tab_highlight_vlm", "module": "states", "tag": "color" }, { "name": "structure::structure_gate_main_vlm", "module": "structure", "tag": "layout" }, { "name": "structure::structure_main_dots_vlm", "module": "structure", "tag": "shape" }, { "name": "structure::structure_drawer_opens_vlm", "module": "structure", "tag": "position" }, { "name": "structure::structure_game_board_appears_vlm", "module": "structure", "tag": "shape" }, { "name": "structure::structure_board_size_grows_vlm", "module": "structure", "tag": "shape" }, { "name": "structure::structure_game_tile_color_vlm", "module": "structure", "tag": "color" }, { "name": "structure::structure_stats_tabs_vlm", "module": "structure", "tag": "position" }, { "name": "structure::structure_help_expand_vlm", "module": "structure", "tag": "layout" }, { "name": "text::text_tutorial_illustration_vlm", "module": "text", "tag": "shape" }, { "name": "text::text_game_icon_controls_vlm", "module": "text", "tag": "shape" } ], "vlm_total": 36, "n_vlm_unverified": 0, "vlm_log_found": true}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743{ "schema_version": 2, "instance_id": "android/secuso-privacy-friendly-2048", "grading": { "mode": "inline", "model": null, "scored_separately": true }, "totals": { "assertions": 36, "with_verdict": 36, "calibrated": 0, "usable": null, "scored_records": 36, "unbacked_records": 0 }, "assertions": [ { "id": "computation_restart_two_tiles_vlm", "screenshot": "computation_restart_two_tiles_vlm.png", "assertion": "Does the game grid show exactly two numbered tiles, with every other cell empty?", "form": "question", "expected": true, "aspect": "position", "modality": null, "links_to": "computation_restart_two_tiles", "rigor": { "jump_kind": "value", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "computation_5x5_grid_vlm", "screenshot": "computation_5x5_grid_vlm.png", "assertion": "Is the game board a square grid with five columns and five rows of cells (a 5 by 5 grid)?", "form": "question", "expected": true, "aspect": "size", "modality": null, "links_to": "computation_5x5_grid", "rigor": { "jump_kind": "value", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "states_animation_switch_on_off_vlm", "screenshot": "states_animation_switch_on_off_vlm.png", "assertion": "In this settings list, is the ON/OFF toggle switch next to 'Activate Animation' in its ON state, with the thumb slid to the RIGHT end of its track?", "form": "question", "expected": true, "aspect": "position", "modality": null, "links_to": "states_animation_switch_on_off", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "states_theme_dark_applied_vlm", "screenshot": "states_theme_dark_applied_vlm.png", "assertion": "Is this settings screen drawn with a DARK theme, i.e. a near-black or dark-grey background behind light-coloured text?", "form": "question", "expected": true, "aspect": "color", "modality": null, "links_to": "states_theme_dark_applied", "rigor": { "jump_kind": "transition", "depth": 2 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "states_theme_system_restored_vlm", "screenshot": "states_theme_system_restored_vlm.png", "assertion": "Is this settings screen drawn with a LIGHT theme, i.e. a white or light background behind dark-coloured text?", "form": "question", "expected": true, "aspect": "color", "modality": null, "links_to": "states_theme_system_restored", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "states_color_original_tiles_vlm", "screenshot": "states_color_original_tiles_vlm.png", "assertion": "On this 2048 game board, are the numbered tiles coloured in the classic warm ORANGE / TAN / beige palette (NOT blue)?", "form": "question", "expected": true, "aspect": "color", "modality": null, "links_to": "states_color_original_tiles", "rigor": { "jump_kind": "transition", "depth": 2 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "states_color_default_tiles_vlm", "screenshot": "states_color_default_tiles_vlm.png", "assertion": "On this 2048 game board, are the numbered tiles coloured in a BLUE / blue-gradient palette (NOT orange or tan)?", "form": "question", "expected": true, "aspect": "color", "modality": null, "links_to": "states_color_default_tiles", "rigor": { "jump_kind": "transition", "depth": 2 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "states_color_preview_changed_vlm", "screenshot": "states_color_preview_changed_vlm.png", "assertion": "On this home screen, is the small 2048 board preview image drawn in warm ORANGE / TAN colours rather than blue?", "form": "question", "expected": true, "aspect": "color", "modality": null, "links_to": "states_color_preview_changed", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "states_drawer_selected_highlight_vlm", "screenshot": "states_drawer_selected_highlight_vlm.png", "assertion": "In this open navigation drawer, is the 'Settings' menu row visually highlighted (a coloured/tinted background or coloured text) that sets it apart from the other menu rows?", "form": "question", "expected": true, "aspect": "color", "modality": null, "links_to": "states_drawer_selected_highlight", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "states_stats_tab_highlight_vlm", "screenshot": "states_stats_tab_highlight_vlm.png", "assertion": "In this row of tabs (4x4 / 5x5 / 6x6 / 7x7), is the '5x5' tab visually highlighted as the active tab, e.g. by a coloured underline indicator or a differently-coloured label, compared with the other tabs?", "form": "question", "expected": true, "aspect": "color", "modality": null, "links_to": "states_stats_tab_highlight", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "text_tutorial_illustration_vlm", "screenshot": "text_tutorial_illustration_vlm.png", "assertion": "Is a large white '2048' shown drawn inside a grid/hash pattern in the centre of the screen?", "form": "question", "expected": true, "aspect": "shape", "modality": null, "links_to": "text_tutorial_illustration", "rigor": { "jump_kind": "none", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "text_game_icon_controls_vlm", "screenshot": "text_game_icon_controls_vlm.png", "assertion": "Are there two dark rounded-square icon buttons below the 'Points' and 'Record' labels — a curved undo arrow on the left and a circular refresh/restart arrow on the right?", "form": "question", "expected": true, "aspect": "shape", "modality": null, "links_to": "text_game_icon_controls", "rigor": { "jump_kind": "none", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "structure_gate_main_vlm", "screenshot": "structure_gate_main_vlm.png", "assertion": "Is there a game mode preview card in the upper area and two wide buttons stacked near the bottom of the screen?", "form": "question", "expected": true, "aspect": "layout", "modality": null, "links_to": "structure_gate_main", "rigor": { "jump_kind": "none", "depth": 0 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "structure_main_dots_vlm", "screenshot": "structure_main_dots_vlm.png", "assertion": "Is there a horizontal row of exactly 4 small round page-indicator dots below the preview image?", "form": "question", "expected": true, "aspect": "shape", "modality": null, "links_to": "structure_main_dots", "rigor": { "jump_kind": "none", "depth": 0 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "structure_drawer_opens_vlm", "screenshot": "structure_drawer_opens_vlm.png", "assertion": "Is a vertical navigation menu panel of about six labeled rows shown on the left side of the screen?", "form": "question", "expected": true, "aspect": "position", "modality": null, "links_to": "structure_drawer_opens", "rigor": { "jump_kind": "transition", "depth": 0 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "structure_game_board_appears_vlm", "screenshot": "structure_game_board_appears_vlm.png", "assertion": "Is a 4 by 4 grid of equally sized square cells shown in the middle of the screen?", "form": "question", "expected": true, "aspect": "shape", "modality": null, "links_to": "structure_game_board_appears", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "structure_board_size_grows_vlm", "screenshot": "structure_board_size_grows_vlm.png", "assertion": "Is the grid of tiles 5 columns wide and 5 rows tall?", "form": "question", "expected": true, "aspect": "shape", "modality": null, "links_to": "structure_board_size_grows", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "structure_game_tile_color_vlm", "screenshot": "structure_game_tile_color_vlm.png", "assertion": "Do the tiles that contain numbers have a solid fill color that clearly differs from the empty background cells?", "form": "question", "expected": true, "aspect": "color", "modality": null, "links_to": "structure_game_tile_color", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "structure_stats_tabs_vlm", "screenshot": "structure_stats_tabs_vlm.png", "assertion": "Is a horizontal row of tab labels positioned across the top of the screen, with rows of statistics below it?", "form": "question", "expected": true, "aspect": "position", "modality": null, "links_to": "structure_stats_tabs", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "structure_help_expand_vlm", "screenshot": "structure_help_expand_vlm.png", "assertion": "Is the screen a vertical list of question rows, one per line, like an FAQ or expandable help list?", "form": "question", "expected": true, "aspect": "layout", "modality": null, "links_to": "structure_help_expand", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "nav_reach_statistics_vlm", "screenshot": "nav_reach_statistics_vlm.png", "assertion": "Is a horizontal row of tab labels shown across the top of the screen, with rows of statistics listed below it?", "form": "question", "expected": true, "aspect": "position", "modality": null, "links_to": "nav_reach_statistics", "rigor": { "jump_kind": "reach", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "nav_reach_settings_vlm", "screenshot": "nav_reach_settings_vlm.png", "assertion": "Is this a settings screen showing a vertical list of preference rows, each with a title line?", "form": "question", "expected": true, "aspect": "position", "modality": null, "links_to": "nav_reach_settings", "rigor": { "jump_kind": "reach", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "nav_reach_help_vlm", "screenshot": "nav_reach_help_vlm.png", "assertion": "Is the screen a vertical list of question rows, one per line, like an FAQ / help list?", "form": "question", "expected": true, "aspect": "layout", "modality": null, "links_to": "nav_reach_help", "rigor": { "jump_kind": "reach", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "nav_reach_about_vlm", "screenshot": "nav_reach_about_vlm.png", "assertion": "Does this screen show app information text such as a version number, author names, and a license paragraph?", "form": "question", "expected": true, "aspect": "content", "modality": null, "links_to": "nav_reach_about", "rigor": { "jump_kind": "reach", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "nav_reach_tutorial_vlm", "screenshot": "nav_reach_tutorial_vlm.png", "assertion": "Are there SKIP and NEXT buttons at the bottom of the screen below an introduction slide?", "form": "question", "expected": true, "aspect": "position", "modality": null, "links_to": "nav_reach_tutorial", "rigor": { "jump_kind": "reach", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "nav_reach_game_new_vlm", "screenshot": "nav_reach_game_new_vlm.png", "assertion": "Is there a left-pointing back/up arrow at the top-left of the screen, above a grid of square game tiles?", "form": "question", "expected": true, "aspect": "position", "modality": null, "links_to": "nav_reach_game_new", "rigor": { "jump_kind": "reach", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "nav_pager_last_arrow_vlm", "screenshot": "nav_pager_last_arrow_vlm.png", "assertion": "Is there a right-pointing next arrow on the RIGHT edge next to the mode preview? Answer NO if only a left-pointing arrow is present.", "form": "question", "expected": false, "aspect": "position", "modality": null, "links_to": "nav_pager_last_arrow", "rigor": { "jump_kind": "transition", "depth": 0 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "nav_deep_theme_dialog_vlm", "screenshot": "nav_deep_theme_dialog_vlm.png", "assertion": "Is a pop-up dialog titled 'Select theme' shown with radio options (System / Light / Dark) stacked vertically?", "form": "question", "expected": true, "aspect": "shape", "modality": null, "links_to": "nav_deep_theme_dialog", "rigor": { "jump_kind": "reach", "depth": 2 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "interaction_persist_board_restored_vlm", "screenshot": "interaction_persist_board_restored_vlm.png", "assertion": "Does the game board show multiple numbered tiles (a populated grid), i.e. it is NOT an empty grid?", "form": "question", "expected": true, "aspect": "content", "modality": null, "links_to": "interaction_persist_board_restored", "rigor": { "jump_kind": "transition", "depth": 2 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "interaction_undo_board_reverted_vlm", "screenshot": "interaction_undo_board_reverted_vlm.png", "assertion": "Does the game board still show numbered tiles on the grid after the undo (a non-empty board)?", "form": "question", "expected": true, "aspect": "content", "modality": null, "links_to": "interaction_undo_board_reverted", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "interaction_undo_icon_visible_vlm", "screenshot": "interaction_undo_icon_visible_vlm.png", "assertion": "Is there a curved counter-clockwise undo arrow icon visible near the top of the screen?", "form": "question", "expected": true, "aspect": "shape", "modality": null, "links_to": "interaction_undo_icon_visible", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "interaction_restart_two_tiles_vlm", "screenshot": "interaction_restart_two_tiles_vlm.png", "assertion": "Does the game board show exactly two numbered tiles, with all the other grid cells empty?", "form": "question", "expected": true, "aspect": "position", "modality": null, "links_to": "interaction_restart_two_tiles", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "interaction_merged_tiles_colored_vlm", "screenshot": "interaction_merged_tiles_colored_vlm.png", "assertion": "Do the numbered tiles on the board have colored (non-white) backgrounds?", "form": "question", "expected": true, "aspect": "color", "modality": null, "links_to": "interaction_merged_tiles_colored", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "interaction_stats_nonzero_vlm", "screenshot": "interaction_stats_nonzero_vlm.png", "assertion": "Does this statistics screen display numeric values in its rows (numbers other than only zeros)?", "form": "question", "expected": true, "aspect": "content", "modality": null, "links_to": "interaction_stats_nonzero", "rigor": { "jump_kind": "transition", "depth": 2 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "interaction_5x5_larger_grid_vlm", "screenshot": "interaction_5x5_larger_grid_vlm.png", "assertion": "Is the game board a large square grid with five columns and five rows of cells?", "form": "question", "expected": true, "aspect": "size", "modality": null, "links_to": "interaction_5x5_larger_grid", "rigor": { "jump_kind": "transition", "depth": 2 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "interaction_restart_icon_visible_vlm", "screenshot": "interaction_restart_icon_visible_vlm.png", "assertion": "Is there a circular refresh / restart arrow icon visible near the top-right of the game screen?", "form": "question", "expected": true, "aspect": "shape", "modality": null, "links_to": "interaction_restart_icon_visible", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null } ], "merged_from_files": 1, "source_shapes": { "list": 1 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license forsoftware and other kinds of works.
The licenses for most software and other practical works are designedto take away your freedom to share and change the works. By contrast,the GNU General Public License is intended to guarantee your freedom toshare and change all versions of a program--to make sure it remains freesoftware for all its users. We, the Free Software Foundation, use theGNU General Public License for most of our software; it applies also toany other work released this way by its authors. You can apply it toyour programs, too.
When we speak of free software, we are referring to freedom, notprice. Our General Public Licenses are designed to make sure that youhave the freedom to distribute copies of free software (and charge forthem if you wish), that you receive source code or can get it if youwant it, that you can change the software or use pieces of it in newfree programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying youthese rights or asking you to surrender the rights. Therefore, you havecertain responsibilities if you distribute copies of the software, or ifyou modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whethergratis or for a fee, you must pass on to the recipients the samefreedoms that you received. You must make sure that they, too, receiveor can get the source code. And you must show them these terms so theyknow their rights.
Developers that use the GNU GPL protect your rights with two steps:(1) assert copyright on the software, and (2) offer you this Licensegiving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explainsthat there is no warranty for this free software. For both users' andauthors' sake, the GPL requires that modified versions be marked aschanged, so that their problems will not be attributed erroneously toauthors of previous versions.
Some devices are designed to deny users access to install or runmodified versions of the software inside them, although the manufacturercan do so. This is fundamentally incompatible with the aim ofprotecting users' freedom to change the software. The systematicpattern of such abuse occurs in the area of products for individuals touse, which is precisely where it is most unacceptable. Therefore, wehave designed this version of the GPL to prohibit the practice for thoseproducts. If such problems arise substantially in other domains, westand ready to extend this provision to those domains in future versionsof the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.States should not allow patents to restrict development and use ofsoftware on general-purpose computers, but in those that do, we wish toavoid the special danger that patents applied to a free program couldmake it effectively proprietary. To prevent this, the GPL assures thatpatents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution andmodification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds ofworks, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under thisLicense. Each licensee is addressed as "you". "Licensees" and"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the workin a fashion requiring copyright permission, other than the making of anexact copy. The resulting work is called a "modified version" of theearlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work basedon the Program.
To "propagate" a work means to do anything with it that, withoutpermission, would make you directly or secondarily liable forinfringement under applicable copyright law, except executing it on acomputer or modifying a private copy. Propagation includes copying,distribution (with or without modification), making available to thepublic, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables otherparties to make or receive copies. Mere interaction with a user througha computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"to the extent that it includes a convenient and prominently visiblefeature that (1) displays an appropriate copyright notice, and (2)tells the user that there is no warranty for the work (except to theextent that warranties are provided), that licensees may convey thework under this License, and how to view a copy of this License. Ifthe interface presents a list of user commands or options, such as amenu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the workfor making modifications to it. "Object code" means any non-sourceform of a work.
A "Standard Interface" means an interface that either is an officialstandard defined by a recognized standards body, or, in the case ofinterfaces specified for a particular programming language, one thatis widely used among developers working in that language.
The "System Libraries" of an executable work include anything, otherthan the work as a whole, that (a) is included in the normal form ofpackaging a Major Component, but which is not part of that MajorComponent, and (b) serves only to enable use of the work with thatMajor Component, or to implement a Standard Interface for which animplementation is available to the public in source code form. A"Major Component", in this context, means a major essential component(kernel, window system, and so on) of the specific operating system(if any) on which the executable work runs, or a compiler used toproduce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means allthe source code needed to generate, install, and (for an executablework) run the object code and to modify the work, including scripts tocontrol those activities. However, it does not include the work'sSystem Libraries, or general-purpose tools or generally available freeprograms which are used unmodified in performing those activities butwhich are not part of the work. For example, Corresponding Sourceincludes interface definition files associated with source files forthe work, and the source code for shared libraries and dynamicallylinked subprograms that the work is specifically designed to require,such as by intimate data communication or control flow between thosesubprograms and other parts of the work.
The Corresponding Source need not include anything that userscan regenerate automatically from other parts of the CorrespondingSource.
The Corresponding Source for a work in source code form is thatsame work.
2. Basic Permissions.
All rights granted under this License are granted for the term ofcopyright on the Program, and are irrevocable provided the statedconditions are met. This License explicitly affirms your unlimitedpermission to run the unmodified Program. The output from running acovered work is covered by this License only if the output, given itscontent, constitutes a covered work. This License acknowledges yourrights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do notconvey, without conditions so long as your license otherwise remainsin force. You may convey covered works to others for the sole purposeof having them make modifications exclusively for you, or provide youwith facilities for running those works, provided that you comply withthe terms of this License in conveying all material for which you donot control copyright. Those thus making or running the covered worksfor you must do so exclusively on your behalf, under your directionand control, on terms that prohibit them from making any copies ofyour copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely underthe conditions stated below. Sublicensing is not allowed; section 10makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technologicalmeasure under any applicable law fulfilling obligations under article11 of the WIPO copyright treaty adopted on 20 December 1996, orsimilar laws prohibiting or restricting circumvention of suchmeasures.
When you convey a covered work, you waive any legal power to forbidcircumvention of technological measures to the extent such circumventionis effected by exercising rights under this License with respect tothe covered work, and you disclaim any intention to limit operation ormodification of the work as a means of enforcing, against the work'susers, your or third parties' legal rights to forbid circumvention oftechnological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as youreceive it, in any medium, provided that you conspicuously andappropriately publish on each copy an appropriate copyright notice;keep intact all notices stating that this License and anynon-permissive terms added in accord with section 7 apply to the code;keep intact all notices of the absence of any warranty; and give allrecipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications toproduce it from the Program, in the form of source code under theterms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independentworks, which are not by their nature extensions of the covered work,and which are not combined with it such as to form a larger program,in or on a volume of a storage or distribution medium, is called an"aggregate" if the compilation and its resulting copyright are notused to limit the access or legal rights of the compilation's usersbeyond what the individual works permit. Inclusion of a covered workin an aggregate does not cause this License to apply to the otherparts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the termsof sections 4 and 5, provided that you also convey themachine-readable Corresponding Source under the terms of this License,in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excludedfrom the Corresponding Source as a System Library, need not beincluded in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means anytangible personal property which is normally used for personal, family,or household purposes, or (2) anything designed or sold for incorporationinto a dwelling. In determining whether a product is a consumer product,doubtful cases shall be resolved in favor of coverage. For a particularproduct received by a particular user, "normally used" refers to atypical or common use of that class of product, regardless of the statusof the particular user or of the way in which the particular useractually uses, or expects or is expected to use, the product. A productis a consumer product regardless of whether the product has substantialcommercial, industrial or non-consumer uses, unless such uses representthe only significant mode of use of the product.
"Installation Information" for a User Product means any methods,procedures, authorization keys, or other information required to installand execute modified versions of a covered work in that User Product froma modified version of its Corresponding Source. The information mustsuffice to ensure that the continued functioning of the modified objectcode is in no case prevented or interfered with solely becausemodification has been made.
If you convey an object code work under this section in, or with, orspecifically for use in, a User Product, and the conveying occurs aspart of a transaction in which the right of possession and use of theUser Product is transferred to the recipient in perpetuity or for afixed term (regardless of how the transaction is characterized), theCorresponding Source conveyed under this section must be accompaniedby the Installation Information. But this requirement does not applyif neither you nor any third party retains the ability to installmodified object code on the User Product (for example, the work hasbeen installed in ROM).
The requirement to provide Installation Information does not include arequirement to continue to provide support service, warranty, or updatesfor a work that has been modified or installed by the recipient, or forthe User Product in which it has been modified or installed. Access to anetwork may be denied when the modification itself materially andadversely affects the operation of the network or violates the rules andprotocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,in accord with this section must be in a format that is publiclydocumented (and with an implementation available to the public insource code form), and must require no special password or key forunpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of thisLicense by making exceptions from one or more of its conditions.Additional permissions that are applicable to the entire Program shallbe treated as though they were included in this License, to the extentthat they are valid under applicable law. If additional permissionsapply only to part of the Program, that part may be used separatelyunder those permissions, but the entire Program remains governed bythis License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your optionremove any additional permissions from that copy, or from any part ofit. (Additional permissions may be written to require their ownremoval in certain cases when you modify the work.) You may placeadditional permissions on material, added by you to a covered work,for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material youadd to a covered work, you may (if authorized by the copyright holders ofthat material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "furtherrestrictions" within the meaning of section 10. If the Program as youreceived it, or any part of it, contains a notice stating that it isgoverned by this License along with a term that is a furtherrestriction, you may remove that term. If a license document containsa further restriction but permits relicensing or conveying under thisLicense, you may add to a covered work material governed by the termsof that license document, provided that the further restriction doesnot survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, youmust place, in the relevant source files, a statement of theadditional terms that apply to those files, or a notice indicatingwhere to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in theform of a separately written license, or stated as exceptions;the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expresslyprovided under this License. Any attempt otherwise to propagate ormodify it is void, and will automatically terminate your rights underthis License (including any patent licenses granted under the thirdparagraph of section 11).
However, if you cease all violation of this License, then yourlicense from a particular copyright holder is reinstated (a)provisionally, unless and until the copyright holder explicitly andfinally terminates your license, and (b) permanently, if the copyrightholder fails to notify you of the violation by some reasonable meansprior to 60 days after the cessation.
Moreover, your license from a particular copyright holder isreinstated permanently if the copyright holder notifies you of theviolation by some reasonable means, this is the first time you havereceived notice of violation of this License (for any work) from thatcopyright holder, and you cure the violation prior to 30 days afteryour receipt of the notice.
Termination of your rights under this section does not terminate thelicenses of parties who have received copies or rights from you underthis License. If your rights have been terminated and not permanentlyreinstated, you do not qualify to receive new licenses for the samematerial under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive orrun a copy of the Program. Ancillary propagation of a covered workoccurring solely as a consequence of using peer-to-peer transmissionto receive a copy likewise does not require acceptance. However,nothing other than this License grants you permission to propagate ormodify any covered work. These actions infringe copyright if you donot accept this License. Therefore, by modifying or propagating acovered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automaticallyreceives a license from the original licensors, to run, modify andpropagate that work, subject to this License. You are not responsiblefor enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of anorganization, or substantially all assets of one, or subdividing anorganization, or merging organizations. If propagation of a coveredwork results from an entity transaction, each party to thattransaction who receives a copy of the work also receives whateverlicenses to the work the party's predecessor in interest had or couldgive under the previous paragraph, plus a right to possession of theCorresponding Source of the work from the predecessor in interest, ifthe predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of therights granted or affirmed under this License. For example, you maynot impose a license fee, royalty, or other charge for exercise ofrights granted under this License, and you may not initiate litigation(including a cross-claim or counterclaim in a lawsuit) alleging thatany patent claim is infringed by making, using, selling, offering forsale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under thisLicense of the Program or a work on which the Program is based. Thework thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claimsowned or controlled by the contributor, whether already acquired orhereafter acquired, that would be infringed by some manner, permittedby this License, of making, using, or selling its contributor version,but do not include claims that would be infringed only as aconsequence of further modification of the contributor version. Forpurposes of this definition, "control" includes the right to grantpatent sublicenses in a manner consistent with the requirements ofthis License.
Each contributor grants you a non-exclusive, worldwide, royalty-freepatent license under the contributor's essential patent claims, tomake, use, sell, offer for sale, import and otherwise run, modify andpropagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any expressagreement or commitment, however denominated, not to enforce a patent(such as an express permission to practice a patent or covenant not tosue for patent infringement). To "grant" such a patent license to aparty means to make such an agreement or commitment not to enforce apatent against the party.
If you convey a covered work, knowingly relying on a patent license,and the Corresponding Source of the work is not available for anyoneto copy, free of charge and under the terms of this License, through apublicly available network server or other readily accessible means,then you must either (1) cause the Corresponding Source to be soavailable, or (2) arrange to deprive yourself of the benefit of thepatent license for this particular work, or (3) arrange, in a mannerconsistent with the requirements of this License, to extend the patentlicense to downstream recipients. "Knowingly relying" means you haveactual knowledge that, but for the patent license, your conveying thecovered work in a country, or your recipient's use of the covered workin a country, would infringe one or more identifiable patents in thatcountry that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction orarrangement, you convey, or propagate by procuring conveyance of, acovered work, and grant a patent license to some of the partiesreceiving the covered work authorizing them to use, propagate, modifyor convey a specific copy of the covered work, then the patent licenseyou grant is automatically extended to all recipients of the coveredwork and works based on it.
A patent license is "discriminatory" if it does not include withinthe scope of its coverage, prohibits the exercise of, or isconditioned on the non-exercise of one or more of the rights that arespecifically granted under this License. You may not convey a coveredwork if you are a party to an arrangement with a third party that isin the business of distributing software, under which you make paymentto the third party based on the extent of your activity of conveyingthe work, and under which the third party grants, to any of theparties who would receive the covered work from you, a discriminatorypatent license (a) in connection with copies of the covered workconveyed by you (or copies made from those copies), or (b) primarilyfor and in connection with specific products or compilations thatcontain the covered work, unless you entered into that arrangement,or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limitingany implied license or other defenses to infringement that mayotherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement orotherwise) that contradict the conditions of this License, they do notexcuse you from the conditions of this License. If you cannot convey acovered work so as to satisfy simultaneously your obligations under thisLicense and any other pertinent obligations, then as a consequence you maynot convey it at all. For example, if you agree to terms that obligate youto collect a royalty for further conveying from those to whom you conveythe Program, the only way you could satisfy both those terms and thisLicense would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you havepermission to link or combine any covered work with a work licensedunder version 3 of the GNU Affero General Public License into a singlecombined work, and to convey the resulting work. The terms of thisLicense will continue to apply to the part which is the covered work,but the special requirements of the GNU Affero General Public License,section 13, concerning interaction through a network will apply to thecombination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions ofthe GNU General Public License from time to time. Such new versions willbe similar in spirit to the present version, but may differ in detail toaddress new problems or concerns.
Each version is given a distinguishing version number. If theProgram specifies that a certain numbered version of the GNU GeneralPublic License "or any later version" applies to it, you have theoption of following the terms and conditions either of that numberedversion or of any later version published by the Free SoftwareFoundation. If the Program does not specify a version number of theGNU General Public License, you may choose any version ever publishedby the Free Software Foundation.
If the Program specifies that a proxy can decide which futureversions of the GNU General Public License can be used, that proxy'spublic statement of acceptance of a version permanently authorizes youto choose that version for the Program.
Later license versions may give you additional or differentpermissions. However, no additional obligations are imposed on anyauthor or copyright holder as a result of your choosing to follow alater version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BYAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHTHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTYOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULARPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAMIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OFALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITINGWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYSTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANYGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THEUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OFDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRDPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OFSUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability providedabove cannot be given local legal effect according to their terms,reviewing courts shall apply local law that most closely approximatesan absolute waiver of all civil liability in connection with theProgram, unless a warranty or assumption of liability accompanies acopy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatestpossible use to the public, the best way to achieve this is to make itfree software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safestto attach them to the start of each source file to most effectivelystate the exclusion of warranty; and each file should have at leastthe "copyright" line and a pointer to where the full notice is found.
Privacy Friendly Pedometer is an Android app that can count steps. Copyright (C) 2016 Tobias Neidig
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a shortnotice like this when it starts in an interactive mode:
Privacy Friendly Apps Copyright (C) 2016 Tobias Neidig This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriateparts of the General Public License. Of course, your program's commandsmight be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,if any, to sign a "copyright disclaimer" for the program, if necessary.For more information on this, and how to apply and follow the GNU GPL, see<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your programinto proprietary programs. If your program is a subroutine library, youmay consider it more useful to permit linking proprietary applications withthe library. If this is what you want to do, use the GNU Lesser GeneralPublic License instead of this License. But first, please read<http://www.gnu.org/philosophy/why-not-lgpl.html>.
12345678910{ "schema_version": 1, "instance_id": "android/secuso-privacy-friendly-pedometer", "platform": "android", "repo": "https://github.com/SecUSo/privacy-friendly-pedometer", "commit": "c38c60a31691b07fbda7efdd9b4cd9d6b85fddd8", "patches": [], "package": "org.secuso.privacyfriendlyactivitytracker", "license": null}123456789#!/usr/bin/env bash# TEMPLATE (rb_unify) — review before use.set -euo pipefail: "${RB_PACKAGE:?must be exported by the runner from instance.json}"D="$(cd "$(dirname "$0")" && pwd)"; SER="${DEVICE_SERIAL:-emulator-5554}"APK="$(find "$D" -name '*.apk' | head -1)"[ -n "$APK" ] || { echo "ERROR: no apk found; extract reference.tar.gz first" >&2; exit 1; }adb -s "$SER" install -r -g "$APK"adb -s "$SER" shell monkey -p "$RB_PACKAGE" -c android.intent.category.LAUNCHER 1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215{ "module": "computation", "total": 20, "passed": 20, "failed": 0, "pass_rate": 1.0, "rule": { "total": 17, "passed": 17, "failed": 0, "pass_rate": 1.0 }, "vlm": { "total": 3, "passed": 3, "failed": 0, "pass_rate": 1.0 }, "vlm_ratio": 0.1765, "audit": { "kit_api_version": 1, "existence": 0, "liveness": 0, "interactive": 20, "depth_ge1": 16, "depth_ge2": 0, "value": 20, "vlm_fine": 1 }, "results": [ { "test": "computation_steps_50", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "stepCount displays 50" }, { "test": "computation_steps_100", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "stepCount displays 100" }, { "test": "computation_steps_199", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "stepCount displays 199" }, { "test": "computation_steps_200", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "stepCount displays 200" }, { "test": "computation_steps_1000", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "stepCount displays 1000" }, { "test": "computation_steps_2000", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "stepCount displays 2000" }, { "test": "computation_steps_zero", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "stepCount displays 0" }, { "test": "computation_steps_large", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "stepCount displays 12345" }, { "test": "computation_steps_arbitrary", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "stepCount displays 777" }, { "test": "computation_distance_two_decimals", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "distanceCount is a 2-decimal number e.g. '0.50'" }, { "test": "computation_distance_unit_km_when_ge_100m", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "distanceTitle=='km' iff distance>=100 m, else 'm'" }, { "test": "computation_distance_unit_meters_small", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "distance renders as '<value> m' for a sub-100 m distance" }, { "test": "computation_calorie_number_with_unit", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "calorieCount is a 2-decimal number labelled 'cal'" }, { "test": "computation_period_day", "passed": true, "message": "", "depth": 0, "jump_kind": "value", "tier": 3, "expect": "Day period label is a single day '05. August'" }, { "test": "computation_period_week_is_range", "passed": true, "message": "", "depth": 0, "jump_kind": "value", "tier": 3, "expect": "Week period is a range like '02. - 08. August'" }, { "test": "computation_period_month_pattern", "passed": true, "message": "", "depth": 0, "jump_kind": "value", "tier": 3, "expect": "Month period matches 'Month YY' e.g. 'August 26'" }, { "test": "computation_period_changes_day_to_week", "passed": true, "message": "", "depth": 0, "jump_kind": "value", "tier": 3, "expect": "period value changes from a single day to a Week range" }, { "test": "computation_chart_plotted_vlm", "passed": true, "message": "VLM: Q='Does the lower card show a line chart with a plotted line and round data points across a grid (not an empty or blank graph)?' A=YES expect=YES", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "VLM YES: Does the lower card show a line chart with a plotted line and round data points across a grid (not an empty or blank graph)?", "tag": "shape" }, { "test": "computation_summary_numbers_vlm", "passed": true, "message": "VLM: Q='In the upper summary card, is a numeric step count shown as a large number next to the word 'Steps', with a distance value and a unit (m or km) below it?' A=YES expect=YES", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "VLM YES: In the upper summary card, is a numeric step count shown as a large number next to the word 'Steps', with a distance value and a unit (m or km) below it?", "tag": "content" }, { "test": "computation_chart_distance_type_vlm", "passed": true, "message": "VLM: Q='Does the lower card display a chart (a graph area with axes/grid and plotted data), consistent with showing distance data?' A=YES expect=YES", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "VLM YES: Does the lower card display a chart (a graph area with axes/grid and plotted data), consistent with showing distance data?", "tag": "content" } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192{ "module": "interaction", "total": 17, "passed": 17, "failed": 0, "pass_rate": 1.0, "rule": { "total": 10, "passed": 10, "failed": 0, "pass_rate": 1.0 }, "vlm": { "total": 7, "passed": 7, "failed": 0, "pass_rate": 1.0 }, "vlm_ratio": 0.7, "audit": { "kit_api_version": 1, "existence": 0, "liveness": 0, "interactive": 17, "depth_ge1": 17, "depth_ge2": 9, "value": 6, "vlm_fine": 5 }, "results": [ { "test": "interaction_correct_steps_save_persists", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "stepCount 300 after SAVE" }, { "test": "interaction_correct_steps_survives_death", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "stepCount 321 after force-stop + relaunch" }, { "test": "interaction_correct_steps_cancel_noop", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "stepCount stays 250 after typing 999 then CANCEL" }, { "test": "interaction_add_walking_mode", "passed": true, "message": "", "depth": 3, "jump_kind": "value", "tier": 3, "expect": "card 'ZTestMode' appears in walking_modes_list" }, { "test": "interaction_walking_mode_survives_death", "passed": true, "message": "", "depth": 2, "jump_kind": "value", "tier": 3, "expect": "card 'ZTestMode' still present after force-stop + relaunch" }, { "test": "interaction_multi_record_integrity", "passed": true, "message": "", "depth": 2, "jump_kind": "value", "tier": 3, "expect": "Walking(active) before Running, both intact, ZTestMode also present" }, { "test": "interaction_card_context_menu", "passed": true, "message": "", "depth": 3, "jump_kind": "transition", "tier": 2, "expect": "'Set as active' and 'Learn' appear after tapping the card overflow" }, { "test": "interaction_switch_active_mode", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "after selecting Running and reopening: Running checked, Walking unchecked" }, { "test": "interaction_help_expand_collapse", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "'This app can count your steps...' child appears on expand, gone on collapse" }, { "test": "interaction_training_creates_session", "passed": true, "message": "", "depth": 2, "jump_kind": "value", "tier": 3, "expect": ">=1 card_training_session row on the overview after END TRAINING NOW" }, { "test": "interaction_vlm_walking_modes_list_vlm", "passed": true, "message": "VLM: Q='Are there three or more walking-mode rows stacked vertically one below another, filling the list from the top of the screen downward?' A=YES expect=YES", "depth": 2, "jump_kind": "reach", "tier": 2, "expect": "VLM YES: Are there three or more walking-mode rows stacked vertically one below another, filling the list from the top of the screen downward?", "tag": "position" }, { "test": "interaction_vlm_walking_mode_card_vlm", "passed": true, "message": "VLM: Q='On every walking-mode row, is there a vertical three-dot overflow menu icon aligned to the far RIGHT edge, with the mode name and its 'Step length' text on the LEFT side of the same row?' A=YES expect=YES", "depth": 2, "jump_kind": "reach", "tier": 2, "expect": "VLM YES: On every walking-mode row, is there a vertical three-dot overflow menu icon aligned to the far RIGHT edge, with the mode name and its 'Step length' text on the LEFT side of the same row?", "tag": "position" }, { "test": "interaction_vlm_context_menu_vlm", "passed": true, "message": "VLM: Q='Is a small pop-up context menu shown listing text options including 'Set as active' and 'Learn'?' A=YES expect=YES", "depth": 3, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Is a small pop-up context menu shown listing text options including 'Set as active' and 'Learn'?", "tag": "content" }, { "test": "interaction_vlm_correct_steps_dialog_vlm", "passed": true, "message": "VLM: Q='In the 'Correct steps' dialog, are the 'CANCEL' and 'SAVE' text buttons positioned side by side in the bottom-right corner, with 'SAVE' to the right of 'CANCEL'?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: In the 'Correct steps' dialog, are the 'CANCEL' and 'SAVE' text buttons positioned side by side in the bottom-right corner, with 'SAVE' to the right of 'CANCEL'?", "tag": "position" }, { "test": "interaction_vlm_summary_popup_vlm", "passed": true, "message": "VLM: Q='Is a small pop-up menu shown listing 'Walking' and 'Running' each with a round radio button on the right, plus a 'Correct steps' option, and is exactly one radio button filled in (selected)?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Is a small pop-up menu shown listing 'Walking' and 'Running' each with a round radio button on the right, plus a 'Correct steps' option, and is exactly one radio button filled in (selected)?", "tag": "shape" }, { "test": "interaction_vlm_help_expanded_vlm", "passed": true, "message": "VLM: Q='Under the 'Overview' heading of this help list, is a paragraph of descriptive body text now shown (the 'Overview' topic is expanded)?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Under the 'Overview' heading of this help list, is a paragraph of descriptive body text now shown (the 'Overview' topic is expanded)?", "tag": "content" }, { "test": "interaction_vlm_training_live_vlm", "passed": true, "message": "VLM: Q='Is a large duration timer centred near the TOP of this screen, with four workout stats arranged in a 2-by-2 grid in the middle, and a full-width 'END TRAINING NOW' button pinned at the BOTTOM?' A=YES expect=YES", "depth": 2, "jump_kind": "reach", "tier": 2, "expect": "VLM YES: Is a large duration timer centred near the TOP of this screen, with four workout stats arranged in a 2-by-2 grid in the middle, and a full-width 'END TRAINING NOW' button pinned at the BOTTOM?", "tag": "position" } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209{ "module": "navigation", "total": 19, "passed": 19, "failed": 0, "pass_rate": 1.0, "rule": { "total": 13, "passed": 13, "failed": 0, "pass_rate": 1.0 }, "vlm": { "total": 6, "passed": 6, "failed": 0, "pass_rate": 1.0 }, "vlm_ratio": 0.4615, "audit": { "kit_api_version": 1, "existence": 0, "liveness": 0, "interactive": 19, "depth_ge1": 19, "depth_ge2": 7, "value": 0, "vlm_fine": 4 }, "results": [ { "test": "nav_reach_training", "passed": true, "message": "", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "TrainingOverview 'Start training' FAB visible; home 'Day' tab gone" }, { "test": "nav_reach_distance", "passed": true, "message": "", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "'START DISTANCE MEASUREMENT' button visible; home 'Day' tab gone" }, { "test": "nav_reach_settings", "passed": true, "message": "", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "Settings 'General' header visible; home 'Day' tab gone" }, { "test": "nav_reach_help", "passed": true, "message": "", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "Help 'Overview' group header visible; home 'Day' tab gone" }, { "test": "nav_reach_about", "passed": true, "message": "", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "About appName 'Privacy Friendly Pedometer' visible; home 'Day' tab gone" }, { "test": "nav_chain_settings_general", "passed": true, "message": "", "depth": 2, "jump_kind": "reach", "tier": 2, "expect": "General 'Permanent step counter' title visible; Settings 'Notifications' header gone" }, { "test": "nav_chain_settings_notifications", "passed": true, "message": "", "depth": 2, "jump_kind": "reach", "tier": 2, "expect": "Notifications 'Enable motivation alert' title visible; Settings 'General' header gone" }, { "test": "nav_chain_settings_walkingmodes", "passed": true, "message": "", "depth": 2, "jump_kind": "reach", "tier": 2, "expect": "WalkingModes card 'Walking(active)' visible; Settings 'Notifications' header gone" }, { "test": "nav_chain_training_live", "passed": true, "message": "", "depth": 2, "jump_kind": "reach", "tier": 2, "expect": "TrainingActivity 'END TRAINING NOW' button visible; overview 'Start training' FAB gone" }, { "test": "nav_backstack_about_home", "passed": true, "message": "", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "home 'Day' tab restored after one BACK; About appName gone" }, { "test": "nav_backstack_general_settings", "passed": true, "message": "", "depth": 2, "jump_kind": "reach", "tier": 2, "expect": "Settings 'Notifications' header restored after one BACK; General 'Permanent step counter' gone" }, { "test": "nav_backstack_walkingmodes_deep", "passed": true, "message": "", "depth": 2, "jump_kind": "reach", "tier": 2, "expect": "1st BACK restores Settings 'Notifications'; 2nd BACK restores home 'Day'" }, { "test": "nav_backstack_distance_home", "passed": true, "message": "", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "home 'Day' tab restored after one BACK; 'START DISTANCE MEASUREMENT' gone" }, { "test": "nav_vlm_training_overview_vlm", "passed": true, "message": "VLM: Q='Is there a round blue floating action button with a white plus sign in the bottom-right corner of this screen?' A=YES expect=YES", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "VLM YES: Is there a round blue floating action button with a white plus sign in the bottom-right corner of this screen?", "tag": "position" }, { "test": "nav_vlm_distance_vlm", "passed": true, "message": "VLM: Q='Is there a full-width dark-blue button labelled 'START DISTANCE MEASUREMENT' pinned to the bottom of this screen?' A=YES expect=YES", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "VLM YES: Is there a full-width dark-blue button labelled 'START DISTANCE MEASUREMENT' pinned to the bottom of this screen?", "tag": "position" }, { "test": "nav_vlm_settings_headers_vlm", "passed": true, "message": "VLM: Q='Does this screen show a vertical settings list with three rows labelled 'General', 'Notifications' and 'Walking modes', each with an icon on the left?' A=YES expect=YES", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "VLM YES: Does this screen show a vertical settings list with three rows labelled 'General', 'Notifications' and 'Walking modes', each with an icon on the left?", "tag": "layout" }, { "test": "nav_vlm_about_vlm", "passed": true, "message": "VLM: Q='Does this About screen show the SECUSO logo (a round emblem to the left of the word 'SECUSO') in its middle area?' A=YES expect=YES", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "VLM YES: Does this About screen show the SECUSO logo (a round emblem to the left of the word 'SECUSO') in its middle area?", "tag": "shape" }, { "test": "nav_vlm_help_vlm", "passed": true, "message": "VLM: Q='Does this screen show a top app bar titled 'Help' and, below it, a vertical list of help topics starting with 'Overview'?' A=YES expect=YES", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "VLM YES: Does this screen show a top app bar titled 'Help' and, below it, a vertical list of help topics starting with 'Overview'?", "tag": "layout" }, { "test": "nav_vlm_training_live_vlm", "passed": true, "message": "VLM: Q='Is there a prominent full-width button labelled 'END TRAINING NOW' at the bottom of this screen?' A=YES expect=YES", "depth": 2, "jump_kind": "reach", "tier": 2, "expect": "VLM YES: Is there a prominent full-width button labelled 'END TRAINING NOW' at the bottom of this screen?", "tag": "position" } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266{ "module": "states", "total": 25, "passed": 25, "failed": 0, "pass_rate": 1.0, "rule": { "total": 16, "passed": 16, "failed": 0, "pass_rate": 1.0 }, "vlm": { "total": 9, "passed": 9, "failed": 0, "pass_rate": 1.0 }, "vlm_ratio": 0.5625, "audit": { "kit_api_version": 1, "existence": 0, "liveness": 0, "interactive": 25, "depth_ge1": 16, "depth_ge2": 5, "value": 1, "vlm_fine": 7 }, "results": [ { "test": "states_pause_to_continue", "passed": true, "message": "", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "Pause step detection -> Continue step detection; pause node gone" }, { "test": "states_pause_icon_vlm", "passed": true, "message": "VLM: Q='Look at the icon button in the top-right of the blue toolbar. Is it now a single right-pointing 'play' / triangle style icon (indicating detection is paused and can be continued) rather than two pause bars?' A=YES expect=YES", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Look at the icon button in the top-right of the blue toolbar. Is it now a single right-pointing 'play' / triangle style icon (indicating detection is paused and can be continued) rather than two pause bars?", "tag": "shape" }, { "test": "states_continue_back_to_pause", "passed": true, "message": "", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "Continue step detection -> Pause step detection; continue node gone" }, { "test": "states_tab_day_selected_on_launch", "passed": true, "message": "", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "Day selected=true; Week=false; Month=false on launch" }, { "test": "states_tab_day_highlight_vlm", "passed": true, "message": "VLM: Q='Among the three tabs DAY, WEEK, MONTH at the top, is 'DAY' the highlighted/selected one (its label a different, brighter colour such as yellow AND with a coloured underline indicator beneath it) while WEEK and MONTH are plain white with no underline?' A=YES expect=YES", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Among the three tabs DAY, WEEK, MONTH at the top, is 'DAY' the highlighted/selected one (its label a different, brighter colour such as yellow AND with a coloured underline indicator beneath it) while WEEK and MONTH are plain white with no underline?", "tag": "color" }, { "test": "states_tab_switch_day_to_week", "passed": true, "message": "", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "Week selected=true, Day selected=false; period label a range containing ' - '" }, { "test": "states_tab_week_highlight_vlm", "passed": true, "message": "VLM: Q='Among the three tabs DAY, WEEK, MONTH at the top, is 'WEEK' now the highlighted/selected one (brighter/different colour label AND a coloured underline indicator beneath WEEK) instead of DAY?' A=YES expect=YES", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Among the three tabs DAY, WEEK, MONTH at the top, is 'WEEK' now the highlighted/selected one (brighter/different colour label AND a coloured underline indicator beneath WEEK) instead of DAY?", "tag": "color" }, { "test": "states_tab_switch_week_to_month", "passed": true, "message": "", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "Month selected=true, Week selected=false; period '<Month> <YY>'" }, { "test": "states_tab_back_to_day", "passed": true, "message": "", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "Day selected=true, Week selected=false; period 'DD. Month'" }, { "test": "states_walking_radio_default", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "Walking radio checked=true, Running checked=false on open" }, { "test": "states_walking_radio_default_vlm", "passed": true, "message": "VLM: Q='In this popup listing walking modes, is the round radio button next to 'Walking' filled in (a solid coloured/blue dot = selected) while the radio next to 'Running' is an empty hollow circle?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: In this popup listing walking modes, is the round radio button next to 'Walking' filled in (a solid coloured/blue dot = selected) while the radio next to 'Running' is an empty hollow circle?", "tag": "shape" }, { "test": "states_walking_select_running", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "Running radio checked=true, Walking checked=false on reopen" }, { "test": "states_running_radio_vlm", "passed": true, "message": "VLM: Q='In this walking-modes popup, is the round radio button next to 'Running' now filled in (solid coloured/blue dot = selected)?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: In this walking-modes popup, is the round radio button next to 'Running' now filled in (solid coloured/blue dot = selected)?", "tag": "shape" }, { "test": "states_chart_radio_default", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "Steps radio checked=true, Distance checked=false on open" }, { "test": "states_chart_steps_radio_vlm", "passed": true, "message": "VLM: Q='In this popup listing chart data types, is the round radio button next to 'Steps' filled in (solid coloured/blue dot = selected) while 'Distance' and 'Calories' show empty hollow circles?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: In this popup listing chart data types, is the round radio button next to 'Steps' filled in (solid coloured/blue dot = selected) while 'Distance' and 'Calories' show empty hollow circles?", "tag": "shape" }, { "test": "states_chart_select_distance", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "Distance radio checked=true, Steps checked=false on reopen" }, { "test": "states_distance_start_to_stop", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "start_button hidden, stop_button ('STOP DISTANCE MEASUREMENT') shown on the same DistanceMeasurementActivity" }, { "test": "states_distance_measuring_vlm", "passed": true, "message": "VLM: Q='Does the large button at the bottom of the screen read 'STOP DISTANCE MEASUREMENT' (a measurement is in progress) rather than 'START DISTANCE MEASUREMENT'?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Does the large button at the bottom of the screen read 'STOP DISTANCE MEASUREMENT' (a measurement is in progress) rather than 'START DISTANCE MEASUREMENT'?", "tag": "layout" }, { "test": "states_distance_stop_to_start", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "stop_button hidden, start_button ('START DISTANCE MEASUREMENT') shown again on the same Activity" }, { "test": "states_drawer_home_checked", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "'Pedometer' menu item checked=true (current section), 'Settings' checked=false" }, { "test": "states_settings_velocity_toggle", "passed": true, "message": "", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "'Show current velocity' switch checked false->true" }, { "test": "states_settings_switches_vlm", "passed": true, "message": "VLM: Q='In this settings list, are there several ON/OFF toggle SWITCHES aligned down the RIGHT-hand edge of the rows (rounded pill toggles), one per switch preference?' A=YES expect=YES", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: In this settings list, are there several ON/OFF toggle SWITCHES aligned down the RIGHT-hand edge of the rows (rounded pill toggles), one per switch preference?", "tag": "layout" }, { "test": "states_settings_hardware_toggle", "passed": true, "message": "", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "'Use phone's step counting hardware' switch checked false->true" }, { "test": "states_settings_permanent_on_vlm", "passed": true, "message": "VLM: Q='Look at the row 'Permanent step counter'. Is its toggle switch in the ON position — the thumb pushed to the RIGHT and the track filled with the app's accent colour (not grey/left = off)?' A=YES expect=YES", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Look at the row 'Permanent step counter'. Is its toggle switch in the ON position — the thumb pushed to the RIGHT and the track filled with the app's accent colour (not grey/left = off)?", "tag": "position" }, { "test": "states_settings_velocity_persists", "passed": true, "message": "", "depth": 2, "jump_kind": "value", "tier": 3, "expect": "'Show current velocity' switch still checked=true after force_stop_and_relaunch()" } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229{ "module": "structure", "total": 21, "passed": 21, "failed": 0, "pass_rate": 1.0, "rule": { "total": 13, "passed": 13, "failed": 0, "pass_rate": 1.0 }, "vlm": { "total": 8, "passed": 8, "failed": 0, "pass_rate": 1.0 }, "vlm_ratio": 0.6154, "audit": { "kit_api_version": 1, "existence": 7, "liveness": 0, "interactive": 14, "depth_ge1": 13, "depth_ge2": 3, "value": 0, "vlm_fine": 7 }, "results": [ { "test": "structure_gate_launch", "passed": true, "message": "", "depth": 0, "jump_kind": "none", "tier": 0, "expect": "" }, { "test": "structure_gate_toolbar", "passed": true, "message": "", "depth": 0, "jump_kind": "none", "tier": 0, "expect": "" }, { "test": "structure_gate_tabs_pager", "passed": true, "message": "", "depth": 0, "jump_kind": "none", "tier": 0, "expect": "" }, { "test": "structure_gate_two_cards", "passed": true, "message": "", "depth": 0, "jump_kind": "none", "tier": 0, "expect": "" }, { "test": "structure_drawer_subtree", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "hamburger adds nav_view subtree (node count grows, menu rows appear)" }, { "test": "structure_drawer_subtree_vlm", "passed": true, "message": "VLM: Q='Is a navigation drawer panel anchored to the LEFT edge of the screen (covering roughly the left three-quarters), listing menu items stacked vertically top-to-bottom: Pedometer, Training, Distance Measurement, Settings, Help, About?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Is a navigation drawer panel anchored to the LEFT edge of the screen (covering roughly the left three-quarters), listing menu items stacked vertically top-to-bottom: Pedometer, Training, Distance Measurement, Settings, Help, About?", "tag": "position" }, { "test": "structure_correct_steps_dialog", "passed": true, "message": "", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "summary popup -> Correct steps adds a dialog (alertTitle + steps EditText)" }, { "test": "structure_summary_popup_vlm", "passed": true, "message": "VLM: Q='Is a small popup menu or dialog shown listing selectable options including 'Walking', 'Running' and 'Correct steps'?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Is a small popup menu or dialog shown listing selectable options including 'Walking', 'Running' and 'Correct steps'?", "tag": "layout" }, { "test": "structure_summary_popup", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "summary periodMoreButton adds a popup window (Running + Correct steps rows appear), removed on BACK" }, { "test": "structure_chart_popup", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "chart periodMoreButton adds a popup window (Distance + Calories rows appear), removed on BACK" }, { "test": "structure_pause_button_flip", "passed": true, "message": "", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "pause button becomes continue (pause gone), reverts on second tap" }, { "test": "structure_distance_start_stop_vlm", "passed": true, "message": "VLM: Q='Is a large distance value like '0.00 m' positioned near the TOP of the content area, with a single full-width button labelled 'START DISTANCE MEASUREMENT' pinned at the BOTTOM of the screen?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Is a large distance value like '0.00 m' positioned near the TOP of the content area, with a single full-width button labelled 'START DISTANCE MEASUREMENT' pinned at the BOTTOM of the screen?", "tag": "position" }, { "test": "structure_distance_start_stop", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "start_button replaced by stop_button on tap, restored on stop" }, { "test": "structure_walkmodes_layout_vlm", "passed": true, "message": "VLM: Q='Are there exactly two list rows stacked vertically at the TOP (each with a mode name and a 'Step length:' value), and a round blue circular '+' floating button in the LOWER-RIGHT corner?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Are there exactly two list rows stacked vertically at the TOP (each with a mode name and a 'Step length:' value), and a round blue circular '+' floating button in the LOWER-RIGHT corner?", "tag": "position" }, { "test": "structure_walkmodes_add_dialog", "passed": true, "message": "", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "FAB add adds a dialog (alertTitle + input_name + step_length_edit)" }, { "test": "structure_help_expand_grows", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "tap Overview grows the expandable list (child row appears), collapses back" }, { "test": "structure_training_grid_vlm", "passed": true, "message": "VLM: Q='Is a large timer (like 00:00:05) centered near the TOP, with the stats laid out BELOW it in a two-column grid: distance in 'm' and velocity in 'km/h' on one row, calories in 'cal' and a step count on the next row?' A=YES expect=YES", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Is a large timer (like 00:00:05) centered near the TOP, with the stats laid out BELOW it in a two-column grid: distance in 'm' and velocity in 'km/h' on one row, calories in 'cal' and a step count on the next row?", "tag": "position" }, { "test": "structure_training_reach", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "start_training FAB flips the surface: END TRAINING NOW appears, the Start-training FAB disappears (proven via and_reach_surface)" }, { "test": "structure_home_two_cards_vlm", "passed": true, "message": "VLM: Q='Are there two white card panels stacked VERTICALLY: the UPPER card titled with 'Summary of activities' and the LOWER card titled with 'Detailed summary of your activities'?' A=YES expect=YES", "depth": 0, "jump_kind": "none", "tier": 0, "expect": "VLM YES: Are there two white card panels stacked VERTICALLY: the UPPER card titled with 'Summary of activities' and the LOWER card titled with 'Detailed summary of your activities'?", "tag": "position" }, { "test": "structure_tabs_row_vlm", "passed": true, "message": "VLM: Q='Is there a horizontal row of exactly three tabs labelled DAY, WEEK and MONTH directly below the top toolbar?' A=YES expect=YES", "depth": 0, "jump_kind": "none", "tier": 0, "expect": "VLM YES: Is there a horizontal row of exactly three tabs labelled DAY, WEEK and MONTH directly below the top toolbar?", "tag": "position" }, { "test": "structure_chart_canvas_vlm", "passed": true, "message": "VLM: Q='In the lower card, is a line/area chart rendered with a horizontal time axis (labels like 00:00, 08:00, 16:00, 23:00) and a vertical axis with numeric gridlines (0 up to 10,000)?' A=YES expect=YES", "depth": 0, "jump_kind": "none", "tier": 0, "expect": "VLM YES: In the lower card, is a line/area chart rendered with a horizontal time axis (labels like 00:00, 08:00, 16:00, 23:00) and a vertical axis with numeric gridlines (0 up to 10,000)?", "tag": "shape" } ]}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910#!/usr/bin/env python3"""Android TestGen Kit — the single source of every test helper, so a test'sNAVIGATION DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded,and self-auditable.
LOCATION AT RUNTIME: alongside the generated test files (testgen: $TESTGEN_DIR/eval/,eval: the restored eval dir). READ-ONLY — never edit, copy, or reimplement it.`import` it from every test file:
import os, sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from android_testgen_kit import * # noqa: F403
WHY THIS EXISTS Helpers used to be re-emitted verbatim into every generated test file (~370 lines x 6 files). That blew the output-token ceiling, forced a "write the script in pieces" protocol, let each copy drift, and duplicated one API key into every file. Everything mechanical now lives here; prompts carry only judgement.
Two orthogonal properties decide whether a suite really exercises an app: * navigation DEPTH — how many SURFACES you cross before the assertion (0 = first screen, 1 = one page/dialog/sheet, 2+ = deeper) * jump RIGOR — what the assertion after the trigger actually checks Prose alone let these drift, so every behavioral test DECLARES both:
@and_test(expects=("interaction_create_note", "interaction_create_note_vlm")) def test_create_note(): ... record("interaction_create_note", ok, "behavior_wrong: ...", depth=1, jump_kind="value", expect="list shows 'Milk'")
jump_kind (verbatim strings — audit/stats key off them): "none" no trigger; existence/gate only -> tier 0 "liveness" only "did not crash / still foreground" -> tier 1 (weak; never ship) "reach" a real surface jump: the TARGET surface's element APPEARED *and* the SOURCE surface's DISAPPEARED -> tier 2 "transition" a state flip (checked/enabled/selected/mode) with before->after -> tier 2 "value" a specific expected value/content was asserted -> tier 3
WHAT A "SURFACE" IS ON ANDROID NOT the Activity — single-Activity Compose/Fragment apps never change it, so get_current_activity() cannot discriminate. A surface is the SET of visible discriminating element keys: and_showing() -> {"Button|Save", "TextView|Total"}. and_reach(before, after, target, source) therefore proves a real jump; reading a flat tree for an always-present element cannot fake it.
DETERMINISTIC DENOMINATOR Scoring is eval_pass_case / origin_total_case, so a test function MUST contribute the same number of records on every code path. @and_test(expects=(...)) owns the try/except and back-fills any declared-but-unrecorded name as a failure, and record() refuses duplicates. N is a literal in the decorator.
PORTABILITY (the same file scores the ORIGINAL and the RECREATION, whose packagename differs): always use the module-level PACKAGE (argv[1]). Never write a packagename, an .apk path, a /data/data path, or a pixel coordinate as a literal. python3 android_testgen_kit.py lint_sources <dir> # flags all of those
SELF-AUDIT (report-only — these are GOALS, never a gate that blocks delivery): python3 android_testgen_kit.py audit <results_dir> python3 android_testgen_kit.py lint <results_dir> python3 android_testgen_kit.py lint_sources <testgen_dir> python3 android_testgen_kit.py audit_depth <testgen_dir> [results_dir]"""from __future__ import annotations
import astimport base64import functoolsimport globimport hashlibimport jsonimport mathimport osimport reimport shleximport subprocessimport sysimport timeimport urllib.errorimport urllib.request
KIT_API_VERSION = 1
# ── Runtime context ────────────────────────────────────────────────────────────# argv[1] = package under test (ORIGINAL during testgen, RECREATION during eval).# argv[2] / $RESULTS_DIR = where the eval JSON + screenshots go.PACKAGE = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("PACKAGE", "")RESULTS_DIR = ( sys.argv[2] if len(sys.argv) > 2 else os.environ.get("RESULTS_DIR", "/workspace/testgen/eval"))ADB = os.environ.get("ADB_PATH", "adb")DEVICE = os.environ.get("DEVICE_SERIAL", "emulator-5554")
# Known emulator packages (from adb-tips). Used by type_text, never by tests.CLIPPER_PKG = "ca.zgrs.clipper"ADB_KEYBOARD_IME = "com.android.adbkeyboard/.AdbIME"
# ── Settling table (adb-tips §5). ANDROID_REMOTE=1 doubles it for tunnelled adb. ─_REMOTE = os.environ.get("ANDROID_REMOTE", "") in ("1", "true", "yes")_SETTLE_MULT = 2.0 if _REMOTE else 1.0SETTLE = { "launch": 3.0, "tap": 1.0, "key": 0.5, "keyboard": 0.5, "dump": 1.0, "ime": 0.5, "text": 0.5, "swipe": 1.0, "dump_retry": 2.0,}
JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3}
# Double-axis quota TARGETS (fractions). rb_audit REPORTS these; they are NOT a# gate. Tune here only — never restate them in a prompt.QUOTAS = { "existence_max": 0.30, # jump_kind=="none" share of ALL tests "interactive_min": 0.60, # reach|transition|value share of ALL tests "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests "depth_ge2_min": 0.15, # depth>=2 share of INTERACTIVE tests "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests # Suite-wide VLM budget, measured as vlm records / ALL records. The right # share is app-dependent (a chart/canvas app earns more than a list app) and # individual modules may legitimately contribute zero, so this is a BAND on # the whole suite, never a per-module requirement. "vlm_share_min": 0.30, "vlm_share_max": 0.50, "vlm_fine_min": 0.66, # fine-grained share of VLM records}
# Depth family (naming convention — see and_audit_depth). A test "crosses a# surface" iff it calls a member of this family; and_back* pops one. Semantic# aliases (and_enter_settings, and_reach_detail) match BY PREFIX, so the kit stays# small and the authored tests stay diverse.DEPTH_FWD_RE = re.compile(r"^and_(enter|reach)[a-z0-9_]*$")DEPTH_BACK_RE = re.compile(r"^and_back[a-z0-9_]*$")DEPTH_RESET_RE = re.compile(r"^and_reset_depth$")
# VLM tags. The fine-grained ones test an exact rendered property; and_audit# computes the >=2/3 fine share from these instead of trusting self-report.VLM_FINE_TAGS = {"color", "shape", "position", "size"}VLM_TAGS = VLM_FINE_TAGS | {"layout", "content"}
# Failure-message taxonomy. and_lint flags a failed record that uses none of them.FAIL_PREFIXES = ("setup_failed:", "feature_missing:", "behavior_wrong:", "exception:")
# Never tap these (tests mutate real device state).DANGEROUS_TEXTS = [ "delete", "remove", "clear", "reset", "erase", "discard", "uninstall", "sign out", "log out", "logout", "format", "wipe", "revoke", "deactivate", "删除", "移除", "清空", "清除", "重置", "退出登录", "注销", "格式化",]
_MODULE_ALIAS = { "states": "states", "state": "states", "structure": "structure", "structures": "structure", "navigation": "navigation", "nav": "navigation", "interaction": "interaction", "interactions": "interaction", "computation": "computation", "computations": "computation", "text": "text", "texts": "text",}
_DEPTH = 0 # surface counter for and_enter/and_back_results: list[dict] = []_seen: set[str] = set()_module: str = ""_screen_info: dict | None = None
def require_kit(min_version: int) -> None: """Fail loudly at import time if the kit is older than the test expects.""" if KIT_API_VERSION < min_version: raise RuntimeError( f"android_testgen_kit v{KIT_API_VERSION} is older than the required " f"v{min_version}; the restored testcase bundle and the kit disagree" )
def _infer_module() -> str: stem = os.path.splitext(os.path.basename(sys.argv[0] or ""))[0] if stem.startswith("test_android_"): return _MODULE_ALIAS.get(stem[len("test_android_"):], stem[len("test_android_"):]) return ""
def init(module: str = "", package: str = "", results_dir: str = "") -> None: """Optional. Overrides the values inferred from argv/env.""" global _module, PACKAGE, RESULTS_DIR if module: _module = _MODULE_ALIAS.get(module, module) if package: PACKAGE = package if results_dir: RESULTS_DIR = results_dir
_module = _infer_module()
def tier_of(jump_kind: str) -> int: return JUMP_KINDS.get(jump_kind, 2)
def settle(kind: str = "tap") -> None: """Sleep the calibrated settling time for `kind` (see SETTLE).""" time.sleep(SETTLE.get(kind, 1.0) * _SETTLE_MULT)
# ══════════════════════════════════════════════════════════════════════════════# (1) Results / recording# ══════════════════════════════════════════════════════════════════════════════
def record(test_name, passed, message="", *, depth=None, jump_kind="none", expect="", tag=None, backfilled=False) -> bool: """Record ONE test result. Returns bool(passed).
The three positional parameters are unchanged from the legacy inline helper. Everything new is keyword-only with a default, so old call sites still work.
depth surfaces this test crossed before asserting (see and_enter/and_reach) jump_kind none | liveness | reach | transition | value expect MANDATORY for reach/transition/value — the exact target you OBSERVED on the original app (and_lint flags an empty one) tag for VLM records: color|shape|position|size|layout|content message on failure, start it with setup_failed: / feature_missing: / behavior_wrong: / exception: """ if test_name in _seen: print(f" [DUP ] {_module}:{test_name} refused (already recorded) — " f"a duplicate would drift the denominator") return bool(passed) if jump_kind not in JUMP_KINDS: jump_kind = "none" d = _DEPTH if depth is None else int(depth) p = bool(passed) rec = { "test": test_name, "passed": p, "message": str(message), "depth": max(0, d), "jump_kind": jump_kind, "tier": tier_of(jump_kind), "expect": str(expect), } if tag: rec["tag"] = str(tag) if backfilled: rec["backfilled"] = True _results.append(rec) _seen.add(test_name) print(f" [{'PASS' if p else 'FAIL'}] {_module}:{test_name} " f"(depth={rec['depth']}, {jump_kind})" + (f" {message}" if message and not p else "")) _flush() return p
def _payload(module_name: str) -> dict: """The eval JSON. Shape is byte-compatible with the legacy helper: the aggregator reads module/total/passed/pass_rate, and the results extraction reads the rule/vlm sub-objects. New keys ride inside results[] + `audit`.""" rule = [r for r in _results if not r["test"].endswith("_vlm")] vlm = [r for r in _results if r["test"].endswith("_vlm")] rt, rp = len(rule), sum(1 for r in rule if r["passed"]) vt, vp = len(vlm), sum(1 for r in vlm if r["passed"]) total, passed = len(_results), sum(1 for r in _results if r["passed"]) fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS) inter = [r for r in _results if r["jump_kind"] in ("reach", "transition", "value")] return { "module": module_name, "total": total, "passed": passed, "failed": total - passed, "pass_rate": round(passed / total, 4) if total else 0, "rule": {"total": rt, "passed": rp, "failed": rt - rp, "pass_rate": round(rp / rt, 4) if rt else 0}, "vlm": {"total": vt, "passed": vp, "failed": vt - vp, "pass_rate": round(vp / vt, 4) if vt else 0}, "vlm_ratio": round(vt / rt, 4) if rt else 0, "audit": { "kit_api_version": KIT_API_VERSION, "existence": sum(1 for r in _results if r["jump_kind"] == "none"), "liveness": sum(1 for r in _results if r["jump_kind"] == "liveness"), "interactive": len(inter), "depth_ge1": sum(1 for r in inter if r["depth"] >= 1), "depth_ge2": sum(1 for r in inter if r["depth"] >= 2), "value": sum(1 for r in inter if r["jump_kind"] == "value"), "vlm_fine": fine, }, "results": _results, }
def _write_json(path: str, data: dict) -> None: """Atomic write, so a mid-run SIGKILL never leaves a truncated JSON.""" os.makedirs(os.path.dirname(path) or ".", exist_ok=True) tmp = path + ".tmp" with open(tmp, "w") as f: json.dump(data, f, indent=2, ensure_ascii=False) os.replace(tmp, path)
def _flush() -> None: """Persist after EVERY record, so a timeout/emulator hang leaves N results instead of zero. save_results() stays the documented finalizer.""" if not _module: return try: _write_json(os.path.join(RESULTS_DIR, f"android_{_module}_eval.json"), _payload(_module)) except Exception: pass
def save_results(module_name: str) -> dict: """MANDATORY finalizer. Authoritatively rewrites the eval JSON under the confirmed module name, prints the summary, and runs the in-process audit. Idempotent.""" global _module _module = _MODULE_ALIAS.get(module_name, module_name) out = _payload(_module) path = os.path.join(RESULTS_DIR, f"android_{_module}_eval.json") _write_json(path, out) print(f"Results: {out['passed']}/{out['total']} passed " f"(rule: {out['rule']['passed']}/{out['rule']['total']}, " f"vlm: {out['vlm']['passed']}/{out['vlm']['total']}) -> {path}") try: and_audit(RESULTS_DIR) and_lint(RESULTS_DIR) except Exception as exc: print(f"[audit] skipped: {exc}") return out
def declared_names() -> list[str]: """Every record name produced so far. The eval run MUST produce this same set against the recreation — a missing feature FAILS, it never vanishes from the denominator.""" return [r["test"] for r in _results]
def and_test(*, expects, module: str = ""): """Wrap a test function so it contributes EXACTLY len(expects) records on every code path — the deterministic-denominator guarantee.
Any name in `expects` still unrecorded when the function returns or raises is back-filled as a failure. The literal also lets and_audit_depth attribute records to this function exactly.
@and_test(expects=("states_toggle_dark", "states_toggle_dark_vlm")) def test_toggle_dark(): ... """ names = tuple(expects)
def deco(fn): @functools.wraps(fn) def wrapper(*a, **kw): if module: init(module=module) err = "" try: return fn(*a, **kw) except Exception as exc: err = f"{type(exc).__name__}: {exc}" print(f" [EXC ] {fn.__name__}: {err}") return None finally: for n in names: if n not in _seen: record(n, False, f"exception: not_reached ({err})" if err else "setup_failed: not_reached (no exception raised)", backfilled=True) wrapper._and_expects = names return wrapper return deco
def run_suite(tests, module: str) -> dict: """Run every test, then finalize. Each test owns its own entry point, so one failure never cascades.""" init(module=module) n_fix = len(fixture_names()) print(f"=== {module}: {len(tests)} tests | package={PACKAGE}" + (f" | fixtures={n_fix}" if n_fix else "") + " ===") if n_fix and not push_fixtures(): print(" [fixtures] WARNING: not all fixtures reached the device — every " "test that opens one will record setup_failed") for t in tests: and_reset_depth() try: t() except Exception as exc: print(f" [EXC ] {getattr(t, '__name__', t)}: {exc}") return save_results(module)
# ══════════════════════════════════════════════════════════════════════════════# (2) Device & adb primitives# ══════════════════════════════════════════════════════════════════════════════
def adb_shell(*args, timeout: int = 30) -> str: """`adb -s $DEVICE shell ...` -> stdout. The -s serial is ALWAYS injected, so a multi-device host can never dispatch to the wrong emulator.""" try: r = subprocess.run([ADB, "-s", DEVICE, "shell", *[str(a) for a in args]], capture_output=True, text=True, timeout=timeout) return r.stdout.strip() except subprocess.TimeoutExpired: return "" except Exception: return ""
def adb_raw(*args, timeout: int = 30) -> str: """`adb -s $DEVICE ...` (no `shell`) — for install/pull/exec-out.""" try: r = subprocess.run([ADB, "-s", DEVICE, *[str(a) for a in args]], capture_output=True, text=True, timeout=timeout) return r.stdout.strip() except Exception: return ""
def device_online() -> bool: try: out = subprocess.run([ADB, "devices"], capture_output=True, text=True, timeout=15).stdout except Exception: return False return any(ln.startswith(DEVICE) and ln.rstrip().endswith("device") for ln in out.splitlines()[1:])
def get_screen_info() -> dict: """Cached screen geometry. EVERY coordinate must be derived from this, never written as a literal — density and font scale differ across devices.""" global _screen_info if _screen_info: return _screen_info m = re.search(r"(\d+)x(\d+)", adb_shell("wm", "size")) w, h = (int(m.group(1)), int(m.group(2))) if m else (1080, 2400) md = re.search(r"(\d+)", adb_shell("wm", "density")) _screen_info = {"width": w, "height": h, "density": int(md.group(1)) if md else 440, "center_x": w // 2, "center_y": h // 2} return _screen_info
def screencap(path: str) -> bool: """Screenshot to a local path. exec-out first; falls back to on-device screencap + pull, which is what survives a tunnelled adb connection.""" os.makedirs(os.path.dirname(path) or ".", exist_ok=True) try: with open(path, "wb") as f: subprocess.run([ADB, "-s", DEVICE, "exec-out", "screencap", "-p"], stdout=f, timeout=20) if os.path.getsize(path) > 0: return True except Exception: pass remote = "/sdcard/_kit_shot.png" adb_shell("screencap", "-p", remote) adb_raw("pull", remote, path, timeout=40) adb_shell("rm", "-f", remote) return os.path.exists(path) and os.path.getsize(path) > 0
# ── Fixtures: sample files a file/image/document app needs to have anything to# open. These MUST be a pipeline artifact, not something you push by hand while# exploring: testgen and eval run in DIFFERENT jobs on DIFFERENT emulators, so a# hand-pushed file is gone by eval and every test that opens it records# setup_failed — blaming the recreation for a harness gap.## authoring (once, during recon): write the files into <EVAL_OUT>/fixtures/# consuming (every test run): run_suite() pushes them before the first test## The directory rides along with the test files into the testcases bank, so the# bytes are restored on every later eval. Sub-directories are preserved, so# fixtures/docs/a.pdf lands at /sdcard/Download/docs/a.pdf.FIXTURES_DEVICE_DIR = "/sdcard/Download"_fixtures_pushed = False
def fixtures_dir() -> str: """The host fixtures directory, or "" when this app needs none.
The script's own directory comes FIRST: at eval, RESULTS_DIR is a separate eval_results/ dir, while the fixtures were restored next to the test files. """ for cand in (os.environ.get("FIXTURES_DIR", ""), os.path.join(os.path.dirname(os.path.abspath(sys.argv[0] or ".")), "fixtures"), os.path.join(RESULTS_DIR, "fixtures")): if cand and os.path.isdir(cand): return cand return ""
def fixture_names() -> list[str]: """Fixture paths relative to fixtures_dir(), e.g. ["doc.pdf", "docs/b.epub"].""" src = fixtures_dir() if not src: return [] out = [] for root, _dirs, files in os.walk(src): for fn in sorted(files): if fn.startswith("."): continue out.append(os.path.relpath(os.path.join(root, fn), src)) return sorted(out)
def fixture_on_device(name: str, dest: str = FIXTURES_DEVICE_DIR) -> str: """Where `name` lives on the device after push_fixtures().""" return f"{dest.rstrip('/')}/{name}"
def push_fixtures(dest: str = FIXTURES_DEVICE_DIR, *, force: bool = False) -> bool: """Mirror the host fixtures onto the device. Idempotent and safe to call from every test — a file already there with the same size is not re-pushed, so the six module processes cost one real push between them.
Returns True when the device holds every fixture (including the vacuous case of an app that needs none). """ global _fixtures_pushed if _fixtures_pushed and not force: return True src = fixtures_dir() names = fixture_names() if not src or not names: _fixtures_pushed = True return True ok = True pushed = 0 for rel in names: local = os.path.join(src, rel) remote = fixture_on_device(rel, dest) try: want = os.path.getsize(local) except OSError: ok = False continue got = adb_shell("stat", "-c", "%s", remote) if not force and got.isdigit() and int(got) == want: continue parent = remote.rsplit("/", 1)[0] if parent: adb_shell("mkdir", "-p", parent) adb_raw("push", local, remote, timeout=120) check = adb_shell("stat", "-c", "%s", remote) if check.isdigit() and int(check) == want: pushed += 1 else: ok = False print(f" [fixtures] FAILED to push {rel} -> {remote}") if pushed: # Make the files visible to gallery/media-backed pickers. Both forms are # API-level dependent and neither is required for plain SAF browsing, so # failures here are not fatal. adb_shell("content", "call", "--uri", "content://media/external/file", "--method", "scan_volume", "--arg", "external_primary") adb_shell("am", "broadcast", "-a", "android.intent.action.MEDIA_SCANNER_SCAN_FILE", "-d", f"file://{dest}") print(f" [fixtures] pushed {pushed}/{len(names)} fixture(s) to {dest}") _fixtures_pushed = ok return ok
# ══════════════════════════════════════════════════════════════════════════════# (3) UI tree query & element matching# ══════════════════════════════════════════════════════════════════════════════
def dump_xml(retries: int = 3, settle_first: bool = True) -> str: """uiautomator dump -> XML text. Retries because the dump fails outright while an animation is in flight.""" if settle_first: settle("dump") remote = "/sdcard/_kit_ui.xml" for attempt in range(retries): adb_shell("uiautomator", "dump", remote) xml = adb_shell("cat", remote, timeout=60) if "<node" in xml: return xml settle("dump_retry") return ""
def parse_nodes(xml_str: str) -> list[dict]: """XML -> list of attribute dicts, each with _bounds and _center.""" nodes = [] for m in re.finditer(r"<node\s+([^>]+?)/?>", xml_str): attrs_str = m.group(1) attrs = {am.group(1): am.group(2) for am in re.finditer(r'([\w-]+)="([^"]*)"', attrs_str)} b = re.search(r'bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"', attrs_str) if b: x1, y1, x2, y2 = (int(v) for v in b.groups()) attrs["_bounds"] = (x1, y1, x2, y2) attrs["_center"] = ((x1 + x2) // 2, (y1 + y2) // 2) nodes.append(attrs) return nodes
def ui(retries: int = 3) -> list[dict]: """THE entry point for a fresh tree. Call it again after ANY state change — a scroll, navigation, dialog, or keyboard invalidates every prior coordinate.""" return parse_nodes(dump_xml(retries=retries))
def find_nodes(nodes, **criteria) -> list[dict]: """Nodes matching ALL criteria, EXACT string match. `True`/`False` match the "true"/"false" attribute strings. Underscores in keys become dashes (content_desc -> content-desc).""" out = [] for n in nodes: ok = True for k, v in criteria.items(): key = k.replace("_", "-") if "_" in k and k != "class" else k if key not in n: ok = False break if v is True and n[key] != "true": ok = False break if v is False and n[key] != "false": ok = False break if v is not True and v is not False and n[key] != v: ok = False break if ok: out.append(n) return out
def find_node(nodes, **criteria) -> dict | None: f = find_nodes(nodes, **criteria) return f[0] if f else None
def find_by_class(nodes, widget_class: str) -> list[dict]: """Partial class-name match, e.g. "Switch", "EditText", "RecyclerView".""" return [n for n in nodes if widget_class in n.get("class", "")]
def find_node_ci(nodes, text: str) -> dict | None: """Case-insensitive text or content-desc match. Use for user-visible labels whose casing a faithful recreation may legitimately differ on.""" t = text.strip().lower() for n in nodes: if (n.get("text", "").strip().lower() == t or n.get("content-desc", "").strip().lower() == t): return n return None
def node_by_id(nodes, rid_suffix: str) -> dict | None: """Match the LAST segment of resource-id, so the package prefix (which differs between original and recreation) is never compared.""" for n in nodes: rid = n.get("resource-id", "") if rid and rid.rsplit("/", 1)[-1] == rid_suffix: return n return None
def find_closest_match(nodes, original_node) -> dict | None: """Re-locate a node in a fresh dump by similarity (class/text/desc/position).""" best, best_score = None, 0 for n in nodes: score = 0 if n.get("class") == original_node.get("class"): score += 3 if n.get("text") and n.get("text") == original_node.get("text"): score += 5 if (n.get("content-desc") and n.get("content-desc") == original_node.get("content-desc")): score += 4 if "_center" in n and "_center" in original_node: if (abs(n["_center"][0] - original_node["_center"][0]) < 100 and abs(n["_center"][1] - original_node["_center"][1]) < 100): score += 2 if score > best_score: best, best_score = n, score return best if best_score >= 3 else None
def node_key(n: dict) -> str: """"{shortClass}|{identity}" — the surface-membership key. Identity priority: text -> content-desc -> resource-id suffix. Returns "" for anonymous nodes (pure layout containers), which are excluded from a surface.""" cls = n.get("class", "").rsplit(".", 1)[-1] ident = (n.get("text", "").strip() or n.get("content-desc", "").strip() or n.get("resource-id", "").rsplit("/", 1)[-1]) return f"{cls}|{ident}" if ident else ""
def and_showing(nodes=None) -> set[str]: """Snapshot the current SURFACE as a set of discriminating element keys. Only on-screen, non-degenerate, identity-bearing nodes count. Take one before and one after a trigger and feed them to and_reach().""" nodes = ui() if nodes is None else nodes s = get_screen_info() out = set() for n in nodes: b = n.get("_bounds") if not b: continue x1, y1, x2, y2 = b if (x2 - x1) < 5 or (y2 - y1) < 5: continue if x2 <= 0 or y2 <= 0 or x1 >= s["width"] or y1 >= s["height"]: continue k = node_key(n) if k: out.add(k) return out
def and_reach(before, after, target: str, source: str | None = None) -> bool: """TRUE-JUMP verdict: the TARGET surface's element newly APPEARED and (if given) the SOURCE surface's element DISAPPEARED. This is what separates a real surface jump from reading an element that was in the tree all along.""" before, after = set(before or []), set(after or []) t = target.strip().lower() appeared = any(t in k.lower() for k in (after - before)) if source is None: return appeared s = source.strip().lower() return (appeared and any(s in k.lower() for k in before) and not any(s in k.lower() for k in after))
def surface_changed(before, after, min_delta: int = 2) -> bool: """Weaker than and_reach: the surface changed materially but you are not naming the target. Use for shape deltas, never to claim a `reach`.""" return len(set(before or []) ^ set(after or [])) >= min_delta
def and_surface_id(nodes=None) -> str: """A stable-ish fingerprint of the current surface, for "did this change?".""" keys = sorted(and_showing(nodes)) return f"{len(keys)}:{hash(tuple(keys)) & 0xFFFFFF:06x}"
# ══════════════════════════════════════════════════════════════════════════════# (4) Interaction# ══════════════════════════════════════════════════════════════════════════════
def tap(x, y) -> None: adb_shell("input", "tap", int(x), int(y)) settle("tap")
def tap_node(node) -> bool: """Tap a node's centre, validating bounds against the real screen first.""" if not node or "_center" not in node: return False x, y = node["_center"] s = get_screen_info() if x < 0 or x > s["width"] or y < 0 or y > s["height"]: return False if "_bounds" in node: x1, y1, x2, y2 = node["_bounds"] if (x2 - x1) < 5 or (y2 - y1) < 5: return False tap(x, y) return True
def tap_text(nodes, text: str) -> bool: n = find_node(nodes, text=text) or find_node_ci(nodes, text) return tap_node(n) if n else False
def is_safe(node) -> bool: """False for destructive controls. Tests mutate real device state, so every exploratory tap must go through this.""" blob = " ".join([node.get("text", ""), node.get("content-desc", ""), node.get("resource-id", "")]).lower() return not any(d in blob for d in DANGEROUS_TEXTS)
def safe_tap(node) -> bool: return tap_node(node) if node and is_safe(node) else False
def long_press(node, ms: int = 800) -> bool: """Long-press = a zero-distance swipe with a duration.""" if not node or "_center" not in node: return False x, y = node["_center"] adb_shell("input", "swipe", x, y, x, y, int(ms)) settle("tap") return True
def swipe(x1, y1, x2, y2, ms: int = 300) -> None: adb_shell("input", "swipe", int(x1), int(y1), int(x2), int(y2), int(ms)) settle("swipe")
def scroll_down(frac: float = 0.5) -> None: s = get_screen_info() swipe(s["center_x"], int(s["height"] * 0.7), s["center_x"], int(s["height"] * (0.7 - frac)))
def scroll_up(frac: float = 0.5) -> None: s = get_screen_info() swipe(s["center_x"], int(s["height"] * 0.3), s["center_x"], int(s["height"] * (0.3 + frac)))
def open_drawer() -> None: s = get_screen_info() swipe(5, s["center_y"], int(s["width"] * 0.8), s["center_y"], ms=400)
def scroll_into_view(text: str, max_swipes: int = 4) -> dict | None: """Scroll until `text` is on screen, RE-DUMPING between swipes. This encodes "after a scroll every previous coordinate is invalid" as code.""" for _ in range(max_swipes + 1): nodes = ui() n = find_node(nodes, text=text) or find_node_ci(nodes, text) if n: return n scroll_down(0.4) return None
def press_key(keycode) -> None: adb_shell("input", "keyevent", keycode) settle("key")
def back() -> None: """Raw BACK. Use and_back() when you are leaving a surface you entered.""" press_key("KEYCODE_BACK")
def home() -> None: press_key("KEYCODE_HOME")
def enter() -> None: press_key("KEYCODE_ENTER")
def keyboard_visible() -> bool: return "mInputShown=true" in adb_shell("dumpsys", "input_method")
def hide_keyboard() -> bool: """Dismiss the soft keyboard without navigating away. Tries, in order: the collapse affordance, an empty region, then BACK — and BACK is only accepted if the surface did NOT change, because BACK can navigate instead.""" if not keyboard_visible(): return True nodes = ui() for n in nodes: blob = (n.get("content-desc", "") + n.get("resource-id", "")).lower() if any(w in blob for w in ("hide", "collapse", "close_keyboard", "back")): if tap_node(n): settle("keyboard") if not keyboard_visible(): return True s = get_screen_info() tap(s["center_x"], int(s["height"] * 0.12)) # top strip is rarely interactive settle("keyboard") if not keyboard_visible(): return True sid = and_surface_id() back() settle("keyboard") if keyboard_visible(): return False if and_surface_id() != sid: print(" [warn] hide_keyboard: BACK also changed the surface") return True
def _quote_for_device(text: str) -> str: """Quote a string for the on-device shell (adb joins argv with spaces).""" return shlex.quote(text)
def type_text(node, text: str, *, method: str = "auto", verify_focus: bool = True) -> bool: """Type into an EditText, safely.
An unfocused EditText silently swallows ALL input (including paste and the ADB-Keyboard broadcast), so this taps the field, re-dumps, and asserts focused="true" before typing — retrying the tap once.
Routing: pure ASCII -> `input text`. Non-ASCII -> Clipper broadcast + paste. method="ime" -> ADB Keyboard, which needs a re-tap after the IME switch (the switch drops focus) and ALWAYS restores the original IME in a finally. """ if not node: return False target = node if verify_focus: ok = False for _ in range(2): if not tap_node(target): return False settle("keyboard") fresh = find_closest_match(ui(), target) or target if fresh.get("focused") == "true": target, ok = fresh, True break target = fresh if not ok: print(" [warn] type_text: field never reported focused=true") else: tap_node(target) settle("keyboard")
is_ascii = all(ord(c) < 128 for c in text) use = method if use == "auto": use = "input" if is_ascii else "clipper"
if use == "input": adb_shell("input", "text", _quote_for_device(text.replace(" ", "%s"))) settle("text") return True
if use == "clipper": adb_shell("am", "broadcast", "-a", "clipper.set", "-e", "text", _quote_for_device(text)) settle("text") press_key(279) # KEYCODE_PASTE settle("text") return True
# method="ime": ADB Keyboard. Some custom views ignore paste, this is the fallback. original = adb_shell("settings", "get", "secure", "default_input_method") try: adb_shell("ime", "set", ADB_KEYBOARD_IME) settle("ime") tap_node(target) # IME switch dropped focus settle("keyboard") adb_shell("am", "broadcast", "-a", "ADB_INPUT_TEXT", "--es", "msg", _quote_for_device(text)) settle("text") return True finally: if original and "null" not in original.lower(): adb_shell("ime", "set", original) # NEVER leave it switched settle("ime")
# ══════════════════════════════════════════════════════════════════════════════# (5) Navigation & the depth family# ══════════════════════════════════════════════════════════════════════════════
def and_reset_depth() -> None: global _DEPTH _DEPTH = 0
def and_enter(surface: str = "") -> int: """Call right AFTER your test navigates into a new surface. This is what backs a declared depth>=1 — and_audit_depth looks for a call from the and_enter*/and_reach* family.""" global _DEPTH _DEPTH += 1 return _DEPTH
def and_back() -> int: """Press BACK and pop one surface.""" global _DEPTH back() _DEPTH = max(0, _DEPTH - 1) return _DEPTH
def and_enter_surface(nodes, target_text: str = "", content_desc: str = "", rid: str = "") -> tuple[bool, str]: """Tap a named trigger, then confirm the surface changed. Counts one surface on success. Returns (ok, note). Prefer and_reach_surface when you can name the destination — that yields jump_kind="reach".""" n = None if target_text: n = find_node(nodes, text=target_text) or find_node_ci(nodes, target_text) if n is None and content_desc: n = find_node(nodes, content_desc=content_desc) if n is None and rid: n = node_by_id(nodes, rid) if n is None: return False, f"setup_failed: trigger not found ({target_text or content_desc or rid})" before = and_showing(nodes) if not tap_node(n): return False, "setup_failed: trigger not tappable" after = and_showing() if not surface_changed(before, after): return False, "behavior_wrong: surface did not change after tapping the trigger" and_enter(target_text or content_desc or rid) return True, ""
def and_reach_surface(node, target: str, source: str | None = None) -> bool: """Tap `node`, then PROVE the jump: `target` appeared and `source` vanished. Counts one surface. This is the only honest way to claim jump_kind="reach".""" before = and_showing() if not tap_node(node): return False after = and_showing() ok = and_reach(before, after, target, source) if ok: and_enter(target) return ok
# ══════════════════════════════════════════════════════════════════════════════# (6) App lifecycle — always keyed on PACKAGE (argv[1]), never a literal# ══════════════════════════════════════════════════════════════════════════════
def launch_app() -> None: adb_shell("monkey", "-p", PACKAGE, "-c", "android.intent.category.LAUNCHER", "1") settle("launch")
def force_stop() -> None: adb_shell("am", "force-stop", PACKAGE) settle("key")
def clear_data() -> None: """Wipe app data. Use to guarantee a clean entry point, never mid-assertion.""" adb_shell("pm", "clear", PACKAGE) settle("key")
def restart_app() -> None: force_stop() launch_app()
def force_stop_and_relaunch() -> None: """The persistence probe: kill the process, relaunch, then assert the state survived. An in-memory-only recreation fails this.""" force_stop() settle("key") launch_app()
def get_current_activity() -> str: out = adb_shell("dumpsys", "activity", "activities") m = re.search(r"mResumedActivity.*?\{[^}]*?([\w.]+/[\w.$]+)", out) if m: return m.group(1) m = re.search(r"mCurrentFocus=.*?\{[^}]*?([\w.]+/[\w.$]+)", adb_shell("dumpsys", "window")) return m.group(1) if m else ""
def is_app_foreground() -> bool: return PACKAGE in get_current_activity() or PACKAGE in adb_shell("dumpsys", "window")
def wait_for_foreground(timeout: int = 10) -> bool: deadline = time.time() + timeout while time.time() < deadline: if is_app_foreground(): return True time.sleep(0.5) return False
# ══════════════════════════════════════════════════════════════════════════════# (7) VLM# ══════════════════════════════════════════════════════════════════════════════
# OpenAI-compatible endpoint. Hardcoded on purpose: the public DashScope native# endpoint rejected the key that pods are provisioned with, so every generated# suite either lost its whole VLM track or shipped a hand-rolled `dashscope.py`# shim to reroute it. This speaks plain chat/completions over the standard library# only — no `pip install`, and the stale shims in the testcases bank can no longer# shadow the transport because nothing imports `dashscope` any more.VLM_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"_VLM_DEFAULT_KEY = "sk-bd0c3f375649439bba62b5b0e8c13057"# Attempts per key. 3 covers the blips seen in practice (empty body, gateway 5xx,# rate-limit bursts) without turning a genuine outage into a 10-minute stall.VLM_RETRIES = int(os.environ.get("VLM_RETRIES", "3"))# Repeating these cannot help: the request itself is wrong (malformed, missing,# too large, or semantically rejected). Everything else 4xx/5xx is worth a retry._VLM_TERMINAL_CODES = {400, 404, 413, 422}
def _vlm_key() -> str: """The judge model's API key: first non-empty of DASHSCOPE_API_KEY, VLM_API_KEY, JUDGE_API_KEY. Empty when none is set.""" for name in ("DASHSCOPE_API_KEY", "VLM_API_KEY", "JUDGE_API_KEY"): v = os.environ.get(name, "").strip() if v: return v return ""
def call_vlm(image_path: str, prompt: str, *, retries: int = 0) -> str | None: """Ask the VLM one question about a local screenshot. Returns the answer text.
Retries transient API failures (empty body, 429, 408/409/425, any 5xx) up to `retries` times — default VLM_RETRIES (3), overridable via the VLM_RETRIES env var. Terminal errors (bad key, malformed/oversized request) are not retried. """ retries = retries or VLM_RETRIES key = _vlm_key() or _VLM_DEFAULT_KEY try: with open(image_path, "rb") as f: b64 = base64.b64encode(f.read()).decode() except Exception as exc: print(f"[VLM] cannot read screenshot {image_path}: {exc}") return None mime = "image/jpeg" if image_path.lower().endswith((".jpg", ".jpeg")) else "image/png" body = json.dumps({ "model": os.environ.get("JUDGE_MODEL", "qwen3.7-plus"), "temperature": 0, "messages": [{"role": "user", "content": [ {"type": "image_url", "image_url": {"url": f"data:{mime};base64,{b64}"}}, {"type": "text", "text": prompt}, ]}], }).encode()
for attempt in range(retries): backoff = 2 * (attempt + 1) req = urllib.request.Request( f"{VLM_BASE_URL}/chat/completions", data=body, headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"}) try: with urllib.request.urlopen(req, timeout=120) as resp: data = json.loads(resp.read().decode()) text = (data["choices"][0]["message"]["content"] or "").strip() if text: return text print(f"[VLM] empty response (attempt {attempt + 1}/{retries})") except urllib.error.HTTPError as exc: detail = exc.read().decode(errors="replace")[:200] print(f"[VLM] HTTP {exc.code} (attempt {attempt + 1}/{retries}): {detail}") if exc.code in (401, 403) or exc.code in _VLM_TERMINAL_CODES: return None # repeating cannot help if exc.code == 429: backoff = 10 * (attempt + 1) # rate limit, not a blip except Exception as exc: # timeout, DNS, reset, bad JSON print(f"[VLM] call failed (attempt {attempt + 1}/{retries}): {exc}") if attempt < retries - 1: time.sleep(backoff) print(f"[VLM] giving up after {retries} attempt(s)") return None
def _vlm_log(results_dir: str, entry: dict) -> None: """Append one attempt to vlm_assertions.json. Called on EVERY vlm_assert exit path, including failures — a `_vlm` case with no entry here then provably never invoked the VLM, which is what build_manifest keys off.""" af = os.path.join(results_dir, "vlm_assertions.json") try: existing = json.load(open(af)) if os.path.exists(af) else [] if not isinstance(existing, list): existing = [] except Exception: existing = [] existing.append(entry) try: _write_json(af, existing) # type: ignore[arg-type] except Exception: try: with open(af, "w") as f: json.dump(existing, f, indent=2, ensure_ascii=False) except Exception as exc: print(f" [warn] vlm_assert: cannot write {af}: {exc}")
def vlm_assert(test_name, question, results_dir=None, expect="YES", *, depth=None, jump_kind="none", tag=None) -> bool: """Screenshot the current screen, ask the VLM one YES/NO question, record it.
`test_name` is auto-suffixed with `_vlm`, which is what routes it to the VLM track in save_results(). `tag` (color|shape|position|size|layout|content) lets and_audit compute the fine-grained share mechanically — always set it.
Ask about a SPECIFIC observable rendered property. A question that a blank screen or any app would pass is worthless. """ if not test_name.endswith("_vlm"): test_name += "_vlm" rd = results_dir or RESULTS_DIR if tag and tag not in VLM_TAGS: print(f" [warn] vlm_assert: unknown tag {tag!r}") ss_path = os.path.join(rd, "screenshots", f"{test_name}.png")
def _fail(msg: str, resp=None, answer="") -> bool: _vlm_log(rd, {"test_name": test_name, "question": question, "screenshot": ss_path, "vlm_response": resp, "vlm_answer": answer, "expected": expect, "passed": False, "tag": tag or "", "error": msg}) return record(test_name, False, msg, depth=depth, jump_kind=jump_kind, tag=tag)
if not screencap(ss_path): return _fail("setup_failed: screenshot capture failed")
prompt = ("Look at this Android app screenshot and answer the following question " "with ONLY 'YES' or 'NO'. Do not explain.\n\n" f"Question: {question}\n\nAnswer (YES or NO):") # An unparseable answer is the same class of flakiness as an empty body, so # re-ask rather than scoring harness noise against the VLM track. answer, resp = "", None for ask in range(VLM_RETRIES): resp = call_vlm(ss_path, prompt) if resp is None: return _fail("setup_failed: VLM API call failed") a = resp.strip().upper() # Whole-word match only: a bare `"NO" in a` also fires on CANNOT / NOT / # NONE / KNOW, turning "Maybe? I cannot tell." into a confident NO and # failing the test on harness noise instead of re-asking. has_yes = re.search(r"\bYES\b", a) is not None has_no = re.search(r"\bNO\b", a) is not None if a.startswith("YES"): answer = "YES" elif a.startswith("NO"): answer = "NO" elif has_yes and not has_no: answer = "YES" elif has_no and not has_yes: answer = "NO" if answer: break print(f"[VLM] unparseable answer {resp!r} (ask {ask + 1}/{VLM_RETRIES})") if not answer: return _fail(f"setup_failed: ambiguous VLM response after {VLM_RETRIES} " f"asks {resp!r}", resp=resp)
passed = answer == expect.upper() record(test_name, passed, (f"VLM: Q='{question}' A={answer} expect={expect}" if passed else f"behavior_wrong: VLM Q='{question}' A={answer} expect={expect}"), depth=depth, jump_kind=jump_kind, expect=f"VLM {expect}: {question}", tag=tag) _vlm_log(rd, {"test_name": test_name, "question": question, "screenshot": ss_path, "vlm_response": resp, "vlm_answer": answer, "expected": expect, "passed": passed, "tag": tag or ""}) return passed
# ══════════════════════════════════════════════════════════════════════════════# (8) Audit / lint — ALL report-only. None of these ever blocks delivery.# ══════════════════════════════════════════════════════════════════════════════
def _load_all(results_dir: str) -> list[dict]: recs, seen_files = [], set() for pat in (os.path.join(results_dir, "android_*_eval.json"), os.path.join(results_dir, "eval_results", "android_*_eval.json")): for path in glob.glob(pat): base = os.path.basename(path) if base in seen_files: continue seen_files.add(base) try: data = json.load(open(path)) except Exception: continue for t in data.get("results", []): if isinstance(t, dict) and "test" in t: recs.append(t) return recs
def and_audit(results_dir: str = "", quotas: dict | None = None) -> dict: """Aggregate declared depth/jump_kind/vlm-tag across the suite and report the quota TARGETS with the concrete gap. GOALS, not a gate.""" results_dir = results_dir or RESULTS_DIR q = quotas or QUOTAS recs = _load_all(results_dir) backfilled = [r for r in recs if r.get("backfilled")] recs = [r for r in recs if not r.get("backfilled")] n = len(recs) if not n: print(f"[and_audit] no records under {results_dir}") return {"total": 0} kinds = [r.get("jump_kind", "none") for r in recs] none_n = sum(1 for k in kinds if k == "none") live_n = sum(1 for k in kinds if k == "liveness") inter = [r for r in recs if r.get("jump_kind") in ("reach", "transition", "value")] ni = len(inter) or 1 d1 = sum(1 for r in inter if int(r.get("depth", 0)) >= 1) d2 = sum(1 for r in inter if int(r.get("depth", 0)) >= 2) val = sum(1 for r in inter if r.get("jump_kind") == "value") vlm = [r for r in recs if r["test"].endswith("_vlm")] fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS) vlm_share = len(vlm) / n
def line(label, got, need, kind): ok = got >= need if kind == "min" else got <= need return ok, (f" [{'ok ' if ok else 'GAP'}] {label}: {got:.0%} " f"({'>=' if kind == 'min' else '<='} {need:.0%})")
lo, hi = q["vlm_share_min"], q["vlm_share_max"] vlm_ok = lo <= vlm_share <= hi if vlm_share < lo: # each added vlm record also grows the denominator: (v+x)/(n+x) >= lo need_more = math.ceil((lo * n - len(vlm)) / (1 - lo)) vlm_hint = (f"under budget by ~{max(1, need_more)} record(s) — allocate more " f"per lane NEXT run; do not re-run to chase it") elif vlm_share > hi: vlm_hint = "over budget — allocate fewer per lane next run" else: vlm_hint = "in budget" vlm_msg = (f" [{'ok ' if vlm_ok else 'GAP'}] VLM BUDGET vlm/total: " f"{len(vlm)}/{n} = {vlm_share:.0%} (target {lo:.0%}-{hi:.0%}) " f"— {vlm_hint}")
checks = [ line("existence(none)/all", none_n / n, q["existence_max"], "max"), line("interactive/all", len(inter) / n, q["interactive_min"], "min"), line("depth>=1 /interactive", d1 / ni, q["depth_ge1_min"], "min"), line("depth>=2 /interactive", d2 / ni, q["depth_ge2_min"], "min"), line("value(tier3)/interactive", val / ni, q["value_min"], "min"), (vlm_ok, vlm_msg), line("vlm fine-grained/vlm", fine / (len(vlm) or 1), q["vlm_fine_min"], "min"), ] print(f"[and_audit] {results_dir} total={n} interactive={len(inter)} " f"none={none_n} liveness={live_n} depth>=1={d1} depth>=2={d2} " f"value={val} vlm={len(vlm)} vlm_fine={fine}") if backfilled: print(f" [!!!] {len(backfilled)} record(s) never reached their assertion " f"(back-filled as failures) — excluded from the ratios above; the " f"100%-pass gate on the original app must catch these") for _ok, msg in checks: print(msg) passed = all(ok for ok, _ in checks) print("[and_audit] " + ("ALL TARGETS MET" if passed else "some targets below — this is a REPORT, not a task: finalize now and fix " "the shortfall in the NEXT run's plan. Re-running the suite to move these " "numbers costs hours and changes nothing about the app under test")) return {"total": n, "interactive": len(inter), "none": none_n, "liveness": live_n, "depth_ge1": d1, "depth_ge2": d2, "value": val, "vlm": len(vlm), "vlm_fine": fine, "vlm_share": round(vlm_share, 4), "backfilled": len(backfilled), "passed": passed, "checks": [m for _o, m in checks]}
def and_lint(results_dir: str = "") -> list[str]: """Flag weak or inconsistent DECLARATIONS.""" results_dir = results_dir or RESULTS_DIR issues, names = [], set() for r in _load_all(results_dir): jk, nm = r.get("jump_kind", "none"), r.get("test", "?") if nm in names: issues.append(f"{nm}: duplicate record name (drifts the denominator)") names.add(nm) if jk not in JUMP_KINDS: issues.append(f"{nm}: unknown jump_kind {jk!r}") if jk in ("reach", "transition", "value") and not str(r.get("expect", "")).strip(): issues.append(f"{nm}: jump_kind={jk} but empty expect " f"(name the specific observed target)") if jk == "liveness": issues.append(f"{nm}: liveness is tier1 — assert the app-authored effect instead") if int(r.get("depth", 0)) < 0: issues.append(f"{nm}: negative depth") msg = str(r.get("message", "")) if not r.get("passed") and not msg.startswith(FAIL_PREFIXES): issues.append(f"{nm}: failure message must start with one of " f"{'/'.join(FAIL_PREFIXES)} (got {msg[:40]!r})") if nm.endswith("_vlm") and not r.get("tag") and not r.get("backfilled"): issues.append(f"{nm}: VLM record has no tag " f"(color|shape|position|size|layout|content)") if issues: print(f"[and_lint] {len(issues)} issue(s):") for i in issues: print(" - " + i) else: print("[and_lint] no issues") return issues
# Non-portable source patterns: they pass on the ORIGINAL app and break on the# RECREATION (different package, different install path). Each is a hard defect._BAD_SOURCE_PATTERNS = [ (r"""["'][a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*){2,}["']""", "hardcodes a package name; use the module-level PACKAGE (argv[1]) — the " "recreation's package differs", ("android.", "androidx.", "java.", "javax.", "com.android.adbkeyboard", "ca.zgrs.clipper", "android.intent.", "com.google.android.inputmethod")), (r"""["'][^"']*\.apk["']|clean\.apk""", "names an APK path; the test must never install or locate the app", ()), (r"/data/data/|/sdcard/Android/data/", "uses a per-package data path, which breaks when the recreation's package " "differs; drive state through the GUI", ()), (r"\btap\(\s*\d{2,}\s*,\s*\d{2,}", "taps a hardcoded pixel coordinate; derive it from a node's _center or " "get_screen_info()", ()), (r"\bpm\s+grant\b|\bappops\s+set\b|\bsettings\s+put\b|\bcontent\s+insert\b", "seeds state outside the GUI; the recreation may not honor it — drive the " "same state through the UI", ()), (r"am\s+start\s+-n\s", "deep-links straight to a component: not portable, and not navigation " "(it cannot back a depth claim)", ()), (r"emulator-\d{4}|127\.0\.0\.1:\d{4}", "hardcodes a device serial; use the module-level DEVICE", ()),]
def and_lint_sources(testgen_dir: str = "") -> list[str]: """Scan authored test/helper .py for NON-PORTABLE patterns and for kit API drift. A clean result means the suite will actually drive the recreation, not just the original.""" testgen_dir = testgen_dir or RESULTS_DIR kit_base = os.path.basename(__file__) py = [p for p in (glob.glob(os.path.join(testgen_dir, "*.py")) + glob.glob(os.path.join(testgen_dir, "tests", "*.py"))) if os.path.basename(p) != kit_base] kit_names = set(globals().keys()) # A sample file the app is supposed to OPEN. Testgen and eval run on DIFFERENT # emulators, so naming one without pushing it means it only ever existed # because someone put it there by hand while exploring. _DEV_PATH_RE = re.compile(r"/sdcard/|/storage/emulated/|\bDCIM\b", re.I) _DOC_RE = re.compile( r"""["'][^"']*\.(?:pdf|epub|mobi|djvu|zim|mp3|mp4|mkv|wav|ogg)["']""", re.I) _fix_files = [f for f in glob.glob(os.path.join(testgen_dir, "fixtures", "**"), recursive=True) if os.path.isfile(f)] issues = [] srcs = {} for p in py: try: srcs[p] = open(p, errors="replace").read() except Exception: continue suite_pushes = any(re.search(r"\b(push_fixtures|fixture_on_device)\b", s) for s in srcs.values()) if _fix_files and not suite_pushes: issues.append( f"fixtures/: {len(_fix_files)} fixture file(s) are authored but NO test " f"calls push_fixtures() — they never reach the device, so every test " f"that opens one records setup_failed. Call it once via run_suite(), " f"or drop the directory.") for p, src in srcs.items(): base = os.path.basename(p) # Strip comments AND docstrings: prose describing the app under test names # files it opens, which is not the same as the code depending on one. scan = re.sub(r'"""[\s\S]*?"""|\'\'\'[\s\S]*?\'\'\'', '""', src) scan = re.sub(r"#[^\n]*", "", scan) # adb is called argv-style — adb_shell("am", "start", "-n", x) — so collapse # the quote-comma-quote separators to read those calls as command lines. flat = re.sub(r"""["']\s*,\s*["']""", " ", scan) if not suite_pushes: for ln in scan.splitlines(): m = _DEV_PATH_RE.search(ln) or _DOC_RE.search(ln) if m: issues.append( f"{base}: needs a sample file on the device " f"[{ln.strip()[:60]}] but the suite never calls " f"push_fixtures() — testgen and eval run on DIFFERENT " f"emulators, so at eval the file is absent. Author the bytes " f"into {os.path.join(testgen_dir, 'fixtures')}/ and let " f"run_suite() push them.") break for pat, why, allow in _BAD_SOURCE_PATTERNS: hit = None for form in (scan, flat): for m in re.finditer(pat, form): cand = m.group(0) if allow and any(a in cand for a in allow): continue hit = cand break if hit: break if hit: issues.append(f"{base}: {why} [{hit[:48]}]") # kit API drift — an import/attr the kit does not define imported: list[str] = [] for m in re.finditer( r"from\s+android_testgen_kit\s+import\s+\(([^)]*)\)", scan, re.S): imported += m.group(1).split(",") for m in re.finditer( r"from\s+android_testgen_kit\s+import\s+([^\n(]+)", scan): imported += m.group(1).split(",") for raw in imported: nm = raw.strip().split(" as ")[0].strip() if nm and nm != "*" and nm not in kit_names: issues.append(f"{base}: imports android_testgen_kit.{nm} which the " f"kit does not define (would ImportError at eval)") for m in re.finditer(r"\bkit\.(\w+)\s*\(", scan): if m.group(1) not in kit_names: issues.append(f"{base}: calls kit.{m.group(1)}() which the kit does " f"not define (would AttributeError at eval)") if issues: print(f"[and_lint_sources] {len(issues)} portability issue(s):") for i in issues: print(" - " + i) else: print("[and_lint_sources] no portability issues") return issues
# ── MEASURED depth cross-check (report-only): does the SOURCE back the DECLARE? ─def _ast_call_name(node) -> str: f = node.func if isinstance(f, ast.Attribute): return f.attr if isinstance(f, ast.Name): return f.id return ""
def _string_locals(fn_node) -> dict[str, str]: """`name = "states_toggle"` inside a test — so record(name, ...) resolves.""" out = {} for n in ast.walk(fn_node): if isinstance(n, ast.Assign) and isinstance(n.value, ast.Constant) \ and isinstance(n.value.value, str): for t in n.targets: if isinstance(t, ast.Name): out[t.id] = n.value.value return out
def _record_names(fn_node) -> list[str]: """Literal record()/vlm_assert() names in this function, preferring the @and_test(expects=(...)) literal when present.""" for dec in getattr(fn_node, "decorator_list", []): if isinstance(dec, ast.Call) and _ast_call_name(dec) == "and_test": for kw in dec.keywords: if kw.arg == "expects" and isinstance(kw.value, (ast.Tuple, ast.List)): return [e.value for e in kw.value.elts if isinstance(e, ast.Constant) and isinstance(e.value, str)] slocals = _string_locals(fn_node) names = [] for n in ast.walk(fn_node): if not (isinstance(n, ast.Call) and _ast_call_name(n) in ("record", "vlm_assert")): continue if not n.args: continue a0 = n.args[0] if isinstance(a0, ast.Constant) and isinstance(a0.value, str): names.append(a0.value) elif isinstance(a0, ast.Name) and a0.id in slocals: names.append(slocals[a0.id]) return names
def _depth_calls(fn_node, local_funcs, budget: int = 2, seen=None): """(fwd, back, reach) depth-family calls, descending `budget` levels into file-local helpers. Cycle-guarded. A LOWER BOUND — never an over-claim.""" seen = seen if seen is not None else set() fwd = bk = rch = 0 relaunch = False for node in ast.walk(fn_node): if not isinstance(node, ast.Call): continue cn = _ast_call_name(node) if DEPTH_FWD_RE.match(cn): fwd += 1 if cn.startswith("and_reach"): rch += 1 elif DEPTH_BACK_RE.match(cn): bk += 1 elif cn in ("launch_app", "restart_app", "force_stop_and_relaunch"): relaunch = True elif budget > 0 and cn in local_funcs and cn not in seen: seen.add(cn) f, b, r = _depth_calls(local_funcs[cn], local_funcs, budget - 1, seen)[:3] fwd, bk, rch = fwd + f, bk + b, rch + r return fwd, bk, rch, relaunch
def and_audit_depth(testgen_dir: str = "", results_dir: str = "") -> list[str]: """MEASURE navigation depth from the test SOURCE (AST) and cross-check the DECLARED depth/jump_kind — so a test cannot just TYPE depth=2. REPORT-ONLY.
Flags a declared depth>=1 or jump_kind="reach" with NO backing call from the depth family and_enter*/and_reach* (directly, in a file-local helper it calls, or anywhere in the module for variable-named records), plus a "reach" that was achieved by relaunching the app rather than navigating. """ testgen_dir = testgen_dir or RESULTS_DIR results_dir = results_dir or testgen_dir files = [p for p in (glob.glob(os.path.join(testgen_dir, "test_android_*.py")) + glob.glob(os.path.join(testgen_dir, "tests", "test_android_*.py")))] per_record, per_module = {}, {} for p in files: try: tree = ast.parse(open(p, errors="replace").read()) except Exception: continue stem = os.path.basename(p)[len("test_android_"):-len(".py")] mod = _MODULE_ALIAS.get(stem, stem) local_funcs = {n.name: n for n in ast.walk(tree) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))} module_backing = any( isinstance(n, ast.Call) and DEPTH_FWD_RE.match(_ast_call_name(n)) for n in ast.walk(tree)) per_module[mod] = {"module_backing": module_backing} for fn in local_funcs.values(): if not fn.name.startswith("test_"): continue fwd, bk, rch, relaunch = _depth_calls(fn, local_funcs) measured = max(0, max((fwd - rch) - bk, 1 if rch >= 1 else 0)) for nm in _record_names(fn): per_record[(mod, nm)] = {"measured_depth": measured, "backing": fwd >= 1, "n_reach": rch, "relaunch": relaunch, "fn": fn.name} issues = [] for r in _load_all(results_dir): nm, jk = r.get("test", "?"), r.get("jump_kind", "none") depth = int(r.get("depth", 0) or 0) strong = depth >= 1 or jk == "reach" hit = None for (mod, rname), v in per_record.items(): if rname == nm: hit = v break if hit is not None: if strong and not hit["backing"]: issues.append(f"{nm} ({hit['fn']}): declared depth={depth}/" f"jump_kind={jk} but NO backing and_enter*/and_reach* " f"call (fake depth)") elif jk == "reach" and hit["n_reach"] == 0: issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but no " f"and_reach* call in its code") elif jk == "reach" and hit["relaunch"]: issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but the function " f"relaunches the app — that is not navigation") elif strong and not any(v.get("module_backing", True) for v in per_module.values()): issues.append(f"{nm}: declared depth={depth}/jump_kind={jk} but no " f"and_enter*/and_reach* call anywhere (fake depth)") if issues: print(f"[and_audit_depth] {len(issues)} fake-depth issue(s) (REPORT-ONLY — " f"fix by adding the and_reach/and_enter you navigated with, or lower " f"the declared depth):") for i in issues: print(" - " + i) else: print("[and_audit_depth] no fake-depth issues " "(declared depth/reach backed by nav calls)") return issues
# ══════════════════════════════════════════════════════════════════════════════# (9) Frozen manifest — the FIXED denominator (ported from RecreationBench v7.2)## Without this, the eval denominator is whatever the candidate happened to emit:# a recreation that crashes a module SHRINKS its own denominator instead of# counting the missing behaviour as failures. The manifest is frozen ONCE per# task from the ORIGINAL app's run and is the denominator authority for every# candidate. Missing tests are injected as `not_run`; extra tests are ignored.# ══════════════════════════════════════════════════════════════════════════════
MANIFEST_NAME = "test_manifest.json"MANIFEST_VERSION = 1
def qualify_name(module: str, test: str) -> str: """`module::test` — two modules may legitimately reuse a short test name.""" return test if "::" in test else f"{module}::{test}"
def _record_status(rec: dict) -> str: if rec.get("status") in ("passed", "failed", "error", "skipped", "not_run"): return rec["status"] return "passed" if rec.get("passed") else "failed"
def _load_by_module(results_dir: str) -> list[tuple[str, dict]]: """Like _load_all but keeps the owning module, so names can be qualified.""" out, seen_files = [], set() for pat in (os.path.join(results_dir, "android_*_eval.json"), os.path.join(results_dir, "eval_results", "android_*_eval.json")): for path in sorted(glob.glob(pat)): base = os.path.basename(path) if base in seen_files: continue seen_files.add(base) try: data = json.load(open(path)) except Exception: continue mod = data.get("module") or base[len("android_"):-len("_eval.json")] for t in data.get("results", []): if isinstance(t, dict) and "test" in t: out.append((str(mod), t)) return out
def _vlm_logged_names(results_dir: str) -> tuple[set[str], bool]: """(names with >=1 logged VLM attempt, whether any log file was found).
Checks the root AND eval_results/ — the agent's self-validation run drives test_verify.sh with --output-dir, which puts the log one level down. """ names, found = set(), False for sub in ("", "eval_results"): p = os.path.join(results_dir, sub, "vlm_assertions.json") if not os.path.isfile(p): continue found = True try: for x in json.load(open(p)): if isinstance(x, dict) and x.get("test_name"): names.add(str(x["test_name"])) except Exception: pass return names, found
def build_manifest(results_dir: str = "", *, task_id: str = "", baseline_model: str = "", out_path: str = "") -> dict: """Freeze the ORIGINAL app's PASSING tests as the denominator.
A test that fails on the original is not a signal about any recreation, so it is moved to `ignored[reason=baseline_fail]` instead of counting against every candidate. This is the only denominator-shrinking mechanism, and it is applied identically to all candidates. """ results_dir = results_dir or RESULTS_DIR logged, log_found = _vlm_logged_names(results_dir) tests, ignored, vlm_assertions = [], [], [] n_unverified = 0 for mod, rec in _load_by_module(results_dir): name = qualify_name(mod, str(rec.get("test", ""))) status = _record_status(rec) entry = {"name": name, "module": mod, "baseline_status": status} is_vlm = name.endswith("_vlm") # A passing _vlm case with no logged attempt never provably reached the # judge on the original app — it must not sit in the VLM denominator that # every recreation is scored against. if is_vlm and status == "passed" and str(rec.get("test", "")) not in logged: n_unverified += 1 ignored.append({"name": name, "module": mod, "reason": "vlm_unverified", "baseline_status": status, "message": "no attempt in vlm_assertions.json — the VLM " "was never provably invoked for this case"}) continue if status == "passed": tests.append(entry) if is_vlm: vlm_assertions.append({"name": name, "module": mod, "tag": rec.get("tag", "")}) else: ignored.append({"name": name, "module": mod, "reason": "baseline_fail", "baseline_status": status, "message": str(rec.get("message", ""))[:300]}) tests.sort(key=lambda t: t["name"]) ignored.sort(key=lambda t: t["name"]) payload = "\n".join(t["name"] for t in tests) pkg = (os.environ.get("ORIG_PACKAGE") or os.environ.get("PACKAGE") or (PACKAGE if "." in PACKAGE else "")) manifest = { "manifest_version": MANIFEST_VERSION, "kit_api_version": KIT_API_VERSION, "task_id": task_id or os.environ.get("INSTANCE_ID", ""), "baseline_model": baseline_model or os.environ.get("MODEL", ""), "baseline_package": pkg, "total": len(tests), "manifest_sha": hashlib.sha256(payload.encode()).hexdigest()[:12], "tests": tests, "ignored": ignored, "vlm_assertions": vlm_assertions, "vlm_total": len(vlm_assertions), "n_vlm_unverified": n_unverified, "vlm_log_found": log_found, } dest = out_path or os.path.join(results_dir, MANIFEST_NAME) tmp = dest + ".tmp" with open(tmp, "w") as f: json.dump(manifest, f, indent=2, ensure_ascii=False) os.replace(tmp, dest) print(f"[build_manifest] {dest} total={manifest['total']} " f"vlm={manifest['vlm_total']} ignored={len(ignored)} " f"sha={manifest['manifest_sha']}") if n_unverified: print(f" [!!!] {n_unverified} passing _vlm case(s) EXCLUDED as " f"vlm_unverified — no attempt logged in vlm_assertions.json" + ("" if log_found else " (no log file found at all — the suite may " "have bypassed the kit's vlm_assert)") + ". They are out of the VLM denominator; fix the VLM path rather " "than accepting the smaller denominator.") base_fail = [i for i in ignored if i["reason"] == "baseline_fail"] if base_fail: print(f" {len(base_fail)} baseline failure(s) excluded from the denominator " f"(they say nothing about a recreation):") for i in base_fail[:20]: print(f" - {i['name']}: {i['message'][:120]}") return manifest
def load_manifest(d: str = "") -> dict | None: """Return the frozen manifest from `d` (or its eval_results/), else None.""" d = d or RESULTS_DIR for p in (os.path.join(d, MANIFEST_NAME), os.path.join(d, "eval_results", MANIFEST_NAME)): if os.path.isfile(p): try: m = json.load(open(p)) except Exception: continue if isinstance(m, dict) and m.get("tests"): return m return None
def score_against_manifest(results_dir: str = "", manifest: dict | None = None) -> dict: """Score a candidate run against the frozen denominator.
denominator = len(manifest["tests"]) regardless of what the candidate emitted. A manifest test the candidate never reported is injected as `not_run` (a non-pass); a test the candidate invented is excluded. A module that crashed on import therefore scores 0/full instead of vanishing. """ results_dir = results_dir or RESULTS_DIR manifest = manifest or load_manifest(results_dir) if not manifest: return {} expected = {t["name"]: t for t in manifest["tests"]} got = {} for mod, rec in _load_by_module(results_dir): got[qualify_name(mod, str(rec.get("test", "")))] = rec
per_test, by_module = {}, {} injected = 0 for name, meta in expected.items(): rec = got.get(name) if rec is None: status, msg = "not_run", "not_run: absent from the candidate's output" injected += 1 else: status, msg = _record_status(rec), str(rec.get("message", "")) per_test[name] = {"status": status, "message": msg[:300]} m = by_module.setdefault(meta.get("module", "?"), {"total": 0, "passed": 0, "not_run": 0}) m["total"] += 1 m["passed"] += status == "passed" m["not_run"] += status == "not_run"
unexpected = sorted(set(got) - set(expected)) total = len(expected) passed = sum(1 for v in per_test.values() if v["status"] == "passed") vlm_names = {a["name"] for a in manifest.get("vlm_assertions", [])} vlm_total = len(vlm_names) vlm_passed = sum(1 for n in vlm_names if per_test.get(n, {}).get("status") == "passed") rule_total = total - vlm_total rule_passed = passed - vlm_passed for m in by_module.values(): m["pass_rate"] = round(m["passed"] / m["total"], 4) if m["total"] else 0.0
out = { "scored_against": "manifest", "manifest_sha": manifest.get("manifest_sha", ""), "manifest_total": total, "total": total, "passed": passed, "pass_rate": round(passed / total, 4) if total else 0.0, "n_injected_not_run": injected, "n_unexpected": len(unexpected), "unexpected": unexpected[:50], "rule": {"total": rule_total, "passed": rule_passed, "pass_rate": round(rule_passed / rule_total, 4) if rule_total else 0.0}, "vlm": {"total": vlm_total, "passed": vlm_passed, "pass_rate": round(vlm_passed / vlm_total, 4) if vlm_total else 0.0}, "by_module": by_module, "per_test": per_test, } print(f"[score_against_manifest] sha={out['manifest_sha']} " f"{passed}/{total} = {out['pass_rate']:.4f} " f"(injected_not_run={injected} unexpected={len(unexpected)}) " f"rule={rule_passed}/{rule_total} vlm={vlm_passed}/{vlm_total}") return out
if __name__ == "__main__": _fns = {"audit": and_audit, "lint": and_lint, "lint_sources": and_lint_sources, "build_manifest": build_manifest} _argv = sys.argv[1:] if _argv[:1] == ["audit_depth"] and len(_argv) >= 2: and_audit_depth(_argv[1], _argv[2] if len(_argv) >= 3 else "") elif _argv[:1] == ["score"] and len(_argv) >= 2: _m = load_manifest(_argv[2]) if len(_argv) >= 3 else load_manifest(_argv[1]) _out = score_against_manifest(_argv[1], _m) if not _out: print("no manifest found — cannot score against a fixed denominator", file=sys.stderr) sys.exit(2) print(json.dumps(_out, ensure_ascii=False)) elif len(_argv) >= 2 and _argv[0] in _fns: _fns[_argv[0]](_argv[1]) else: print("usage: android_testgen_kit.py {audit|lint|lint_sources|build_manifest} <dir>\n" " android_testgen_kit.py audit_depth <testgen_dir> [results_dir]\n" " android_testgen_kit.py score <results_dir> [manifest_dir]")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196{ "module": "text", "total": 18, "passed": 18, "failed": 0, "pass_rate": 1.0, "rule": { "total": 16, "passed": 16, "failed": 0, "pass_rate": 1.0 }, "vlm": { "total": 2, "passed": 2, "failed": 0, "pass_rate": 1.0 }, "vlm_ratio": 0.125, "audit": { "kit_api_version": 1, "existence": 15, "liveness": 0, "interactive": 3, "depth_ge1": 0, "depth_ge2": 0, "value": 0, "vlm_fine": 2 }, "results": [ { "test": "text_home_step_title", "passed": true, "message": "", "depth": 0, "jump_kind": "none", "tier": 0, "expect": "home step-count label == 'Steps'" }, { "test": "text_home_period_subtitle", "passed": true, "message": "", "depth": 0, "jump_kind": "none", "tier": 0, "expect": "home summary-card subtitle == 'Summary of activities'" }, { "test": "text_period_week_is_range", "passed": true, "message": "", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "Week period label contains ' - ' (a date range); Day did not" }, { "test": "text_period_month_shape", "passed": true, "message": "", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "Month period label matches '^<Month> YY$' (e.g. 'August 26')" }, { "test": "text_period_day_single", "passed": true, "message": "", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "Day period label matches '^DD. <Month>$' with no ' - ' range" }, { "test": "text_about_appname_version", "passed": true, "message": "", "depth": 1, "jump_kind": "none", "tier": 0, "expect": "appName=='Privacy Friendly Pedometer', label=='Version', name=='3.1.2'" }, { "test": "text_about_authors", "passed": true, "message": "", "depth": 1, "jump_kind": "none", "tier": 0, "expect": "author=='Author:', names=='Noah Schlegel, Tobias Neidig', contributors=='and contributors.'" }, { "test": "text_about_links", "passed": true, "message": "", "depth": 1, "jump_kind": "none", "tier": 0, "expect": "affiliation=='In affiliation with', secuso=='SECUSO-Website', github=='Github-Repo'" }, { "test": "text_about_logo_block_vlm", "passed": true, "message": "VLM: Q='Near the TOP of this screen, is there a small icon made of several coloured squares positioned immediately to the LEFT of a large heading that reads 'Privacy Friendly Apps'?' A=YES expect=YES", "depth": 1, "jump_kind": "none", "tier": 0, "expect": "VLM YES: Near the TOP of this screen, is there a small icon made of several coloured squares positioned immediately to the LEFT of a large heading that reads 'Privacy Friendly Apps'?", "tag": "position" }, { "test": "text_walkingmode_first_card", "passed": true, "message": "", "depth": 2, "jump_kind": "none", "tier": 0, "expect": "first card name=='Walking(active)' with step_length=='0.50'" }, { "test": "text_walkingmode_running_and_labels", "passed": true, "message": "", "depth": 2, "jump_kind": "none", "tier": 0, "expect": "'Running' card step_length=='0.70'; row labels 'Step length:' and 'meters'" }, { "test": "text_help_key_headers", "passed": true, "message": "", "depth": 1, "jump_kind": "none", "tier": 0, "expect": "Help group headers include 'Overview', 'Counting methods', 'Privacy Info'" }, { "test": "text_help_ordered_headers", "passed": true, "message": "", "depth": 1, "jump_kind": "none", "tier": 0, "expect": "listTitle == the 14 ordered headers 'Overview'..'Permission: Write External Storage'" }, { "test": "text_help_list_layout_vlm", "passed": true, "message": "VLM: Q='This is a vertical list of bold section headers, the first being 'Overview'. Does each header row show a small downward-pointing chevron/arrow indicator positioned to the LEFT of its label text (to the left, not on the right edge)?' A=YES expect=YES", "depth": 1, "jump_kind": "none", "tier": 0, "expect": "VLM YES: This is a vertical list of bold section headers, the first being 'Overview'. Does each header row show a small downward-pointing chevron/arrow indicator positioned to the LEFT of its label text (to the left, not on the right edge)?", "tag": "position" }, { "test": "text_settings_headers", "passed": true, "message": "", "depth": 1, "jump_kind": "none", "tier": 0, "expect": "Settings header titles include 'General', 'Notifications', 'Walking modes'" }, { "test": "text_general_switch_titles", "passed": true, "message": "", "depth": 2, "jump_kind": "none", "tier": 0, "expect": "General shows titles 'Permanent step counter' and 'Show current velocity'" }, { "test": "text_general_unit_summaries", "passed": true, "message": "", "depth": 2, "jump_kind": "none", "tier": 0, "expect": "'Unit of length' summary=='kilometers'; 'Unit of energy' summary=='calories'" }, { "test": "text_general_value_summaries", "passed": true, "message": "", "depth": 2, "jump_kind": "none", "tier": 0, "expect": "'Personal daily step goal' summary=='10000'; 'Weight (kg)' summary=='65.0'" } ]}1pytest_plugins = ["rb_unify.pytest_rb", "rb_unify.android_bridge"]12pytestpillow123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498#!/usr/bin/env python3"""COMPUTATION module — the app's core input -> output surface.
The Privacy Friendly Pedometer's core computation is the "Correct steps" dialog:you enter a step count N and the summary card DERIVES and displays the day'sstep total, distance, and calories. This is a genuine value-owning surface, sothis module is the primary owner of jump_kind="value".
GROUND TRUTH (verified live on the running original, which is authoritative): * stepCount is a DETERMINISTIC function of the entered value: set N -> the summary card's stepCount TextView shows exactly str(N), every time, across every value and every restart. This is the rock-solid input->output backbone. * distanceCount is NOT reproducible as an exact point value: this emulator runs a live step sensor whose accumulator drifts the internal distance baseline between operations (the same N=200 produced 0.10 km at one moment and -60.00 m minutes later). So this module NEVER asserts an exact distance number it cannot reproduce. What IS deterministic about distance is its FORMATTING: - distanceCount always renders with exactly two decimals ("-?\\d+\\.\\d{2}"), - distanceTitle is "km" when the value is >= 100 m and "m" otherwise. Those formatting invariants are asserted as values instead. * The active-walking-mode popup radio (Walking/Running) has NO observable effect on the displayed distance on this build, so no mode-multiplier value is claimed (the original does not reproduce it -> asserting it would be a baseline_fail). * The Day/Week/Month tab selects a computed PERIOD label: Day -> "05. August" (single day), Week -> a range containing " - ", Month -> "<Month> <YY>" (regex ^[A-Za-z]+ \\d{2}$). All deterministic.
The "Correct steps" flow crosses a dialog surface, so those tests are depth>=1,backed by and_enter("correct_steps_dialog") inside the shared set_steps_clean()helper. Tab-switch tests are same-surface (depth 0) but still value-tier (theperiod value changed to a specific computed string)."""import osimport reimport sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from android_testgen_kit import * # noqa: F403,E402
TESTS = []
def test(fn): """Register a test function for run_suite().""" TESTS.append(fn) return fn
# ── shared helpers ──────────────────────────────────────────────────────────
def _period_texts(nodes): """Every summary/chart 'period' label currently on screen (there are two — one per card — and both carry the same computed value).""" return [n.get("text", "") for n in nodes if (n.get("resource-id") or "").rsplit("/", 1)[-1] == "period"]
def set_steps_clean(val): """Open the summary-card overflow -> 'Correct steps' dialog, CLEAR the pre-filled field, type `val`, and SAVE. Crosses one surface (the dialog), so it calls and_enter to back the depth>=1 declaration of every test that uses it.
The steps EditText PRE-FILLS with the current count and type_text APPENDS, so the field MUST be cleared first (MOVE_END then repeated DEL) or "50" then "100" becomes "50100". """ nodes = ui() tap_node(find_node(nodes, content_desc="Walking modes")) # summary overflow settle("tap") nodes = ui() tap_node(find_node_ci(nodes, "Correct steps")) settle("tap") and_enter("correct_steps_dialog") # dialog surface crossed nodes = ui() ed = node_by_id(nodes, "steps") if ed is None: return False tap_node(ed) settle("keyboard") press_key(123) # KEYCODE_MOVE_END for _ in range(12): press_key(67) # KEYCODE_DEL settle("keyboard") nodes = ui() ed = node_by_id(nodes, "steps") type_text(ed, str(val)) nodes = ui() save = node_by_id(nodes, "button1") # button1=SAVE, button2=CANCEL if save is None: return False tap_node(save) settle("tap") settle("tap") return True
def _read(rid): n = node_by_id(ui(), rid) return (n.get("text", "") if n else "").strip()
def _step_case(name, n_steps): """One clean input->output case: set N, assert stepCount == str(N).
stepCount is the deterministic core transform of this app — the summary card echoes the corrected step count exactly, so this is the honest value assertion for the input->output surface (distance drifts; steps does not). """ restart_app() if not wait_for_foreground(): record(name, False, "setup_failed: app did not reach foreground", depth=1, jump_kind="value", expect=f"stepCount={n_steps}") return if not set_steps_clean(n_steps): record(name, False, "setup_failed: could not reach/complete Correct-steps dialog", depth=1, jump_kind="value", expect=f"stepCount={n_steps}") return got = _read("stepCount") want = str(n_steps) ok = got == want record(name, ok, "" if ok else f"behavior_wrong: stepCount got {got!r} want {want!r}", depth=1, jump_kind="value", expect=f"stepCount displays {want}")
# ══════════════════════════════════════════════════════════════════════════════# CORE INPUT -> OUTPUT: entered steps -> displayed step count (deterministic)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_steps_50",))@testdef test_steps_50(): _step_case("computation_steps_50", 50)
@and_test(expects=("computation_steps_100",))@testdef test_steps_100(): _step_case("computation_steps_100", 100)
@and_test(expects=("computation_steps_199",))@testdef test_steps_199(): _step_case("computation_steps_199", 199)
@and_test(expects=("computation_steps_200",))@testdef test_steps_200(): _step_case("computation_steps_200", 200)
@and_test(expects=("computation_steps_1000",))@testdef test_steps_1000(): _step_case("computation_steps_1000", 1000)
@and_test(expects=("computation_steps_2000",))@testdef test_steps_2000(): _step_case("computation_steps_2000", 2000)
@and_test(expects=("computation_steps_zero",))@testdef test_steps_zero(): # Edge: empty/zero input -> the card computes a step total of exactly 0. _step_case("computation_steps_zero", 0)
@and_test(expects=("computation_steps_large",))@testdef test_steps_large(): # Edge: a large value still echoes exactly (no truncation/overflow). _step_case("computation_steps_large", 12345)
@and_test(expects=("computation_steps_arbitrary",))@testdef test_steps_arbitrary(): # A non-round value the recreation cannot special-case. _step_case("computation_steps_arbitrary", 777)
# ══════════════════════════════════════════════════════════════════════════════# DERIVED DISTANCE — deterministic FORMATTING invariants (not the drifting value)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_distance_two_decimals",))@testdef test_distance_two_decimals(): """The derived distance always renders with exactly two decimal places. The magnitude drifts with the live sensor, but the 2-decimal FORMAT of the computed value is deterministic — that is the value we assert.""" restart_app() if not wait_for_foreground(): record("computation_distance_two_decimals", False, "setup_failed: app did not reach foreground", depth=1, jump_kind="value", expect="distanceCount matches -?d+.dd") return if not set_steps_clean(1000): record("computation_distance_two_decimals", False, "setup_failed: could not complete Correct-steps dialog", depth=1, jump_kind="value", expect="distanceCount matches -?d+.dd") return d = _read("distanceCount") ok = bool(re.match(r"^-?\d+\.\d{2}$", d)) record("computation_distance_two_decimals", ok, "" if ok else f"behavior_wrong: distanceCount {d!r} not 2-decimal formatted", depth=1, jump_kind="value", expect="distanceCount is a 2-decimal number e.g. '0.50'")
@and_test(expects=("computation_distance_unit_km_when_ge_100m",))@testdef test_distance_unit_km(): """The derived distance switches its UNIT deterministically: distanceTitle is 'km' exactly when the computed distance is >= 100 m, otherwise 'm'. Verified by reading the displayed value and its unit together and checking the rule — robust to the drifting magnitude.""" restart_app() if not wait_for_foreground(): record("computation_distance_unit_km_when_ge_100m", False, "setup_failed: app did not reach foreground", depth=1, jump_kind="value", expect="km iff meters>=100 else m") return if not set_steps_clean(1000): record("computation_distance_unit_km_when_ge_100m", False, "setup_failed: could not complete Correct-steps dialog", depth=1, jump_kind="value", expect="km iff meters>=100 else m") return nodes = ui() dn = node_by_id(nodes, "distanceCount") un = node_by_id(nodes, "distanceTitle") d = (dn.get("text", "") if dn else "").strip() unit = (un.get("text", "") if un else "").strip() ok = False detail = f"distance={d!r} unit={unit!r}" try: meters = float(d) * (1000.0 if unit == "km" else 1.0) expect_km = meters >= 100.0 ok = unit in ("m", "km") and (unit == "km") == expect_km detail = f"distance={d!r} unit={unit!r} meters={meters}" except ValueError: ok = False record("computation_distance_unit_km_when_ge_100m", ok, "" if ok else f"behavior_wrong: unit rule violated ({detail})", depth=1, jump_kind="value", expect="distanceTitle=='km' iff distance>=100 m, else 'm'")
@and_test(expects=("computation_distance_unit_meters_small",))@testdef test_distance_unit_meters_small(): """Complementary edge: with a tiny corrected count (0), the derived distance magnitude is small and the unit label is a bare length unit 'm' (never 'km' for a sub-100 m positive distance). We assert the unit is one of the two valid length labels and consistent with the shown value.""" restart_app() if not wait_for_foreground(): record("computation_distance_unit_meters_small", False, "setup_failed: app did not reach foreground", depth=1, jump_kind="value", expect="distanceTitle in {m,km}") return if not set_steps_clean(0): record("computation_distance_unit_meters_small", False, "setup_failed: could not complete Correct-steps dialog", depth=1, jump_kind="value", expect="distanceTitle in {m,km}") return nodes = ui() dn = node_by_id(nodes, "distanceCount") un = node_by_id(nodes, "distanceTitle") d = (dn.get("text", "") if dn else "").strip() unit = (un.get("text", "") if un else "").strip() ok = False detail = f"distance={d!r} unit={unit!r}" try: meters = float(d) * (1000.0 if unit == "km" else 1.0) ok = unit in ("m", "km") and (unit == "km") == (meters >= 100.0) detail = f"distance={d!r} unit={unit!r} meters={meters}" except ValueError: ok = False record("computation_distance_unit_meters_small", ok, "" if ok else f"behavior_wrong: unit inconsistent with value ({detail})", depth=1, jump_kind="value", expect="distance renders as '<value> m' for a sub-100 m distance")
# ══════════════════════════════════════════════════════════════════════════════# CALORIES — a derived numeric output pairs with its 'cal' unit (deterministic# structure; the magnitude drifts so only its shape/unit are asserted)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_calorie_number_with_unit",))@testdef test_calorie_number_with_unit(): """Entering steps derives a calorie figure shown as a 2-decimal number beside the unit label 'cal'. The value drifts with the sensor, so we assert the derived output's FORMAT and unit pairing, which are deterministic.""" restart_app() if not wait_for_foreground(): record("computation_calorie_number_with_unit", False, "setup_failed: app did not reach foreground", depth=1, jump_kind="value", expect="calorieCount 2-decimal + 'cal'") return if not set_steps_clean(2000): record("computation_calorie_number_with_unit", False, "setup_failed: could not complete Correct-steps dialog", depth=1, jump_kind="value", expect="calorieCount 2-decimal + 'cal'") return c = _read("calorieCount") unit = _read("calorieTitle") ok = bool(re.match(r"^-?\d+\.\d{2}$", c)) and unit == "cal" record("computation_calorie_number_with_unit", ok, "" if ok else f"behavior_wrong: calorieCount {c!r} unit {unit!r}", depth=1, jump_kind="value", expect="calorieCount is a 2-decimal number labelled 'cal'")
# ══════════════════════════════════════════════════════════════════════════════# TAB -> COMPUTED PERIOD LABEL (Day / Week / Month) — same-surface (depth 0)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_period_day",))@testdef test_period_day(): """The Day tab computes a single-day period label 'DD. Month' (observed 05. August on this emulator).""" restart_app() if not wait_for_foreground(): record("computation_period_day", False, "setup_failed: app did not reach foreground", depth=0, jump_kind="value", expect="period '05. August'") return nodes = ui() tap_node(find_node(nodes, content_desc="Day")) # ensure Day selected settle("tap") labels = _period_texts(ui()) # exact observed value; also accept the general single-day shape "DD. Month" ok = ("05. August" in labels) or any( re.match(r"^\d{2}\. [A-Za-z]+$", (p or "")) for p in labels) record("computation_period_day", ok, "" if ok else f"behavior_wrong: Day period labels {labels!r}", depth=0, jump_kind="value", expect="Day period label is a single day '05. August'")
@and_test(expects=("computation_period_week_is_range",))@testdef test_period_week_range(): """Switching to Week recomputes the period into a DATE RANGE containing ' - ' (observed '02. - 08. August').""" restart_app() if not wait_for_foreground(): record("computation_period_week_is_range", False, "setup_failed: app did not reach foreground", depth=0, jump_kind="value", expect="week period contains ' - '") return nodes = ui() tap_node(find_node(nodes, content_desc="Week")) settle("tap") labels = _period_texts(ui()) ok = any(" - " in (p or "") for p in labels) record("computation_period_week_is_range", ok, "" if ok else f"behavior_wrong: Week period labels {labels!r} lack a ' - ' range", depth=0, jump_kind="value", expect="Week period is a range like '02. - 08. August'")
@and_test(expects=("computation_period_month_pattern",))@testdef test_period_month_pattern(): """Switching to Month recomputes the period into '<Month> <YY>' (observed 'August 26', matching ^[A-Za-z]+ \\d{2}$).""" restart_app() if not wait_for_foreground(): record("computation_period_month_pattern", False, "setup_failed: app did not reach foreground", depth=0, jump_kind="value", expect="month period ^[A-Za-z]+ \\d{2}$") return nodes = ui() tap_node(find_node(nodes, content_desc="Month")) settle("tap") labels = _period_texts(ui()) ok = any(re.match(r"^[A-Za-z]+ \d{2}$", (p or "")) for p in labels) record("computation_period_month_pattern", ok, "" if ok else f"behavior_wrong: Month period labels {labels!r} != 'Month YY'", depth=0, jump_kind="value", expect="Month period matches 'Month YY' e.g. 'August 26'")
@and_test(expects=("computation_period_changes_day_to_week",))@testdef test_period_changes_day_to_week(): """The period VALUE genuinely recomputes on tab change: the single-day Day label is replaced by a Week range — a before!=after value transition on the same surface.""" restart_app() if not wait_for_foreground(): record("computation_period_changes_day_to_week", False, "setup_failed: app did not reach foreground", depth=0, jump_kind="value", expect="period value differs Day vs Week") return tap_node(find_node(ui(), content_desc="Day")) settle("tap") day = [p for p in _period_texts(ui()) if p] tap_node(find_node(ui(), content_desc="Week")) settle("tap") week = [p for p in _period_texts(ui()) if p] day0 = day[0] if day else "" week0 = week[0] if week else "" ok = bool(day0) and bool(week0) and day0 != week0 and " - " in week0 record("computation_period_changes_day_to_week", ok, "" if ok else f"behavior_wrong: day={day0!r} week={week0!r} (no recompute)", depth=0, jump_kind="value", expect="period value changes from a single day to a Week range")
# ══════════════════════════════════════════════════════════════════════════════# VLM (exactly 3) — the ONLY genuinely-visual computed output is the LineChart# canvas (numbers are plotted, unreadable from the view tree).# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("computation_chart_plotted_vlm",))@testdef test_chart_plotted_vlm(): """After setting a step count, the lower (chart) card renders a line chart that PLOTS the data — a computed rendering the dump cannot read.""" restart_app() if not wait_for_foreground(): record("computation_chart_plotted_vlm", False, "setup_failed: app did not reach foreground", depth=1, jump_kind="value", tag="shape") return set_steps_clean(2000) ui() # settle the surface before the screenshot vlm_assert("computation_chart_plotted", "Does the lower card show a line chart with a plotted line and " "round data points across a grid (not an empty or blank graph)?", RESULTS_DIR, expect="YES", depth=1, jump_kind="value", tag="shape")
@and_test(expects=("computation_summary_numbers_vlm",))@testdef test_summary_numbers_vlm(): """The summary card renders the computed step count as a large number with a 'Steps' label and a distance value with a unit — a rendered-numbers check.""" restart_app() if not wait_for_foreground(): record("computation_summary_numbers_vlm", False, "setup_failed: app did not reach foreground", depth=1, jump_kind="value", tag="content") return set_steps_clean(2000) ui() vlm_assert("computation_summary_numbers", "In the upper summary card, is a numeric step count shown as a large " "number next to the word 'Steps', with a distance value and a unit " "(m or km) below it?", RESULTS_DIR, expect="YES", depth=1, jump_kind="value", tag="content")
@and_test(expects=("computation_chart_distance_type_vlm",))@testdef test_chart_distance_type_vlm(): """Switching the chart data type to Distance re-renders the chart for distance data — a computed repaint of the canvas, VLM-only.""" restart_app() if not wait_for_foreground(): record("computation_chart_distance_type_vlm", False, "setup_failed: app did not reach foreground", depth=1, jump_kind="value", tag="content") return set_steps_clean(2000) nodes = ui() opt = find_node(nodes, content_desc="Options") # chart-card overflow if opt is not None: tap_node(opt) settle("tap") nodes = ui() dist = find_node_ci(nodes, "Distance") if dist is not None: # the row's radio sits to the right; tapping the row label commits it tap_node(dist) settle("tap") settle("tap") ui() vlm_assert("computation_chart_distance_type", "Does the lower card display a chart (a graph area with axes/grid " "and plotted data), consistent with showing distance data?", RESULTS_DIR, expect="YES", depth=1, jump_kind="value", tag="content")
if __name__ == "__main__": run_suite(TESTS, "computation")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768#!/usr/bin/env python3"""INTERACTION module — EFFECT-BY-CONSEQUENCE on user DATA for Privacy FriendlyPedometer.
This lane owns CRUD lifecycles, 3+-step sequences where each action depends onthe last, MULTI-RECORD integrity, DATA persistence across process death, andlong-press / context (overflow) menus. Every test drives the app to the surfacevia the real user path, performs the action, then reads the CONSEQUENCE back outof a FRESH ui() and asserts it equals what was observed on the original app.
Golden model (recon.md), all verified live on the original: * Correct steps (MainActivity): summary card `periodMoreButton` (desc "Walking modes") -> popup radio Walking/Running + item "Correct steps" -> dialog (`alertTitle`="Correct steps", EditText `steps` PRE-FILLED with the current count, `button1`=SAVE, `button2`=CANCEL). To set a KNOWN value the field must be CLEARED first (MOVE_END then DEL x12) — typing APPENDS otherwise. SAVE persists `stepCount` across an in-app navigation AND across process death. * Walking modes (WalkingModesActivity, drawer->Settings->"Walking modes"): RecyclerView `walking_modes_list`, seeded cards `name`="Walking(active)" (0.50) and "Running" (0.70), FAB `add_walking_mode_btn` (desc "Add"), each card overflow `card_menu` (desc "Options") -> context menu Set as active / Learn / Edit / Delete. Add dialog: `input_name`, `step_length_edit`, `button1`=SAVE. Adding accumulates across runs -> the add test is idempotent. * Home summary popup radios: `title` TextView paired with a sibling `radio` RadioButton (the checked bit lives on the RadioButton, not the title). * Help (HelpActivity): ExpandableListView `generalExpandableListView`, group headers `listTitle`; tapping "Overview" reveals a child text row (subtree grows), tapping again collapses it. * Training (TrainingOverviewActivity -> TrainingActivity): FAB `start_training` -> live screen (`training_stop_button`="END TRAINING NOW"); stopping returns to the overview and leaves a `card_training_session` row in `training_overview_list`.
SAFETY: tests mutate REAL device state. Destructive controls (Delete / Remove /Clear / swipe-to-delete of a walking mode) are NEVER tapped. `training_stop_button`("End training now") is SAFE and is used only to clean up a started session. Datais never wiped with clear_data() (it bounces to the launcher + re-prompts perms);restart_app() / force_stop_and_relaunch() are used instead."""import osimport sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from android_testgen_kit import * # noqa: F403,E402
MODE_MARK = "ZTestMode" # sorts last; distinctive so read-back cannot collide
# ── shared entry helpers (plain helpers; the and_enter_*/and_reach_* NAME is what# the depth audit keys off — no @and_test decorator here) ────────────────────
def open_nav_drawer(): """Open the navigation drawer via the HAMBURGER (never open_drawer(), whose edge-swipe drops to the launcher). Returns the fresh drawer node list or None.""" ham = find_node(ui(), content_desc="Open navigation drawer") if not ham or not tap_node(ham): return None return ui()
def step_count(): """The home summary `stepCount` text, or None if not on the home surface.""" n = node_by_id(ui(), "stepCount") return n.get("text") if n else None
def and_enter_correct_steps_dialog(): """Home -> summary `periodMoreButton` (desc "Walking modes") popup -> tap the "Correct steps" item -> the dialog. Counts ONE surface (the dialog) via and_enter. Returns True once the `steps` EditText is present.""" more = find_node(ui(), content_desc="Walking modes") if more is None or not tap_node(more): return False settle("tap") cs = find_node_ci(ui(), "Correct steps") if cs is None or not tap_node(cs): return False settle("tap") if node_by_id(ui(), "steps") is None: return False and_enter("correct_steps_dialog") return True
def set_steps_clean(value): """From an OPEN Correct-steps dialog, replace the pre-filled `steps` value with `value` and tap SAVE. The field pre-fills with the current count and type_text APPENDS, so it is cleared first (MOVE_END + DEL x12). Returns True if SAVE was tapped.""" ed = node_by_id(ui(), "steps") if ed is None: return False tap_node(ed) settle("keyboard") press_key(123) # KEYCODE_MOVE_END for _ in range(12): press_key(67) # KEYCODE_DEL settle("keyboard") ed = node_by_id(ui(), "steps") # re-find after clearing if ed is None: return False type_text(ed, value) save = node_by_id(ui(), "button1") # button1 = SAVE, button2 = CANCEL if save is None or not tap_node(save): return False settle("tap") settle("tap") return True
def and_reach_walking_modes(): """restart -> drawer -> Settings -> "Walking modes" => WalkingModesActivity. Proves each hop with and_reach_surface (Settings header, then the WalkingModes-only card "Walking(active)"). Counts TWO surfaces. Returns True when the seeded "Walking(active)" card is visible.""" restart_app() if not wait_for_foreground(): return False d = open_nav_drawer() if d is None: return False settings = find_node_ci(d, "Settings") if settings is None or not and_reach_surface(settings, "General", "Day"): return False wm = find_node_ci(ui(), "Walking modes") if wm is None or not and_reach_surface(wm, "Walking(active)", "Notifications"): return False return True
def walking_mode_names(): """The `name` texts of every card currently in `walking_modes_list`.""" return [n.get("text", "") for n in ui() if n.get("resource-id", "").rsplit("/", 1)[-1] == "name" and n.get("text", "").strip()]
def expanded_child_texts(): """Text of every expanded ExpandableListView child row (`expandedListItem`) currently in the dump. Empty when no group is expanded.""" return [n.get("text", "") for n in ui() if n.get("resource-id", "").rsplit("/", 1)[-1] == "expandedListItem" and n.get("text", "").strip()]
def add_walking_mode(name, length): """From WalkingModesActivity, open the Add dialog (FAB desc "Add"), fill `input_name` + `step_length_edit`, tap SAVE. Counts ONE surface (the dialog). Both fields are empty (they render their HINT as text), so typing does not append. Returns True if SAVE was tapped.""" fab = find_node(ui(), content_desc="Add") or node_by_id(ui(), "add_walking_mode_btn") if fab is None or not tap_node(fab): return False settle("tap") if node_by_id(ui(), "input_name") is None: return False and_enter("add_mode_dialog") # NOTE: do NOT hide_keyboard() between the fields — in this dialog that path # falls through to BACK, which dismisses the whole dialog. type_text re-taps # (hence re-focuses) each field, and button1 (SAVE) renders above the keyboard, # so both fields and SAVE stay reachable with the IME up. type_text(node_by_id(ui(), "input_name"), name) type_text(node_by_id(ui(), "step_length_edit"), length) save = node_by_id(ui(), "button1") if save is None or not tap_node(save): return False settle("tap") settle("tap") return True
def radios_state(): """Pair each home-popup `title` TextView with its same-row `radio` RadioButton and return [(label, checked_str), ...]. The checked bit lives on the RadioButton, so the title alone cannot tell you which mode is active.""" nodes = ui() titles = [n for n in nodes if n.get("resource-id", "").rsplit("/", 1)[-1] == "title" and n.get("text", "").strip() and "_center" in n] radios = [n for n in nodes if n.get("resource-id", "").rsplit("/", 1)[-1] == "radio" and "_center" in n] out = [] for t in titles: ty = t["_center"][1] best, bd = None, 1e9 for r in radios: d = abs(r["_center"][1] - ty) if d < bd: bd, best = d, r if best is not None and bd < 60: out.append((t.get("text").strip(), best.get("checked"))) return out
def open_summary_popup(): """Tap the home summary `periodMoreButton` (desc "Walking modes") to open the Walking/Running/Correct-steps popup. Returns True if the popup showed a 'Running' entry.""" more = find_node(ui(), content_desc="Walking modes") if more is None or not tap_node(more): return False settle("tap") return find_node_ci(ui(), "Running") is not None
def and_reach_training_live(): """restart -> drawer -> Training (overview) -> start_training FAB => live TrainingActivity. Proves both hops. Counts TWO surfaces. Returns True when 'END TRAINING NOW' is visible.""" restart_app() if not wait_for_foreground(): return False d = open_nav_drawer() if d is None: return False tr = find_node_ci(d, "Training") if tr is None or not and_reach_surface(tr, "Start training", "Day"): return False fab = node_by_id(ui(), "start_training") if fab is None or not and_reach_surface(fab, "END TRAINING NOW", "Start training"): return False return True
def session_count(): """Number of `card_training_session` rows on the training overview.""" return sum(1 for n in ui() if n.get("resource-id", "").rsplit("/", 1)[-1] == "card_training_session")
# ════════════════════════════════════════════════════════════════════���═════════# A. CORRECT STEPS — CRUD-update of the day's step record (depth 1, dialog)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_correct_steps_save_persists",))def test_correct_steps_save_persists(): # clean-set stepCount to 300 via the dialog -> SAVE -> read stepCount back out # of a fresh home dump. A dialog that echoes but does not commit fails here. restart_app() if not wait_for_foreground(): record("interaction_correct_steps_save_persists", False, "setup_failed: app did not reach the foreground", depth=1, jump_kind="value", expect="stepCount 300") return if not and_enter_correct_steps_dialog(): record("interaction_correct_steps_save_persists", False, "feature_missing: no Correct-steps dialog reachable from the summary popup", depth=1, jump_kind="value", expect="stepCount 300") return saved = set_steps_clean("300") after = step_count() ok = bool(saved) and after == "300" record("interaction_correct_steps_save_persists", ok, "" if ok else f"behavior_wrong: SAVE 300 did not update stepCount (got {after!r})", depth=1, jump_kind="value", expect="stepCount 300 after SAVE")
@and_test(expects=("interaction_correct_steps_survives_death",))def test_correct_steps_survives_death(): # SIGNATURE persistence probe: clean-set 321 -> SAVE -> KILL the process and # relaunch -> stepCount must still read 321. An in-memory-only recreation that # never wrote the corrected count to storage cannot pass this. restart_app() if not wait_for_foreground(): record("interaction_correct_steps_survives_death", False, "setup_failed: app did not reach the foreground", depth=1, jump_kind="value", expect="stepCount 321 after relaunch") return if not and_enter_correct_steps_dialog(): record("interaction_correct_steps_survives_death", False, "feature_missing: no Correct-steps dialog reachable from the summary popup", depth=1, jump_kind="value", expect="stepCount 321 after relaunch") return saved = set_steps_clean("321") before = step_count() force_stop_and_relaunch() wait_for_foreground() after = step_count() ok = bool(saved) and before == "321" and after == "321" record("interaction_correct_steps_survives_death", ok, "" if ok else f"behavior_wrong: corrected steps did not survive process death " f"(before={before!r} after={after!r})", depth=1, jump_kind="value", expect="stepCount 321 after force-stop + relaunch")
@and_test(expects=("interaction_correct_steps_cancel_noop",))def test_correct_steps_cancel_noop(): # First SAVE a known baseline (250), then reopen, type a different value, and # tap CANCEL (button2). The record must be UNCHANGED (still 250) — CANCEL is # the negative half that makes the SAVE test discriminating. restart_app() if not wait_for_foreground(): record("interaction_correct_steps_cancel_noop", False, "setup_failed: app did not reach the foreground", depth=1, jump_kind="transition", expect="stepCount stays 250 after CANCEL") return if not and_enter_correct_steps_dialog() or not set_steps_clean("250"): record("interaction_correct_steps_cancel_noop", False, "feature_missing: could not establish the 250 baseline via SAVE", depth=1, jump_kind="transition", expect="stepCount stays 250 after CANCEL") return baseline = step_count() and_reset_depth() if not and_enter_correct_steps_dialog(): record("interaction_correct_steps_cancel_noop", False, "setup_failed: could not reopen the Correct-steps dialog", depth=1, jump_kind="transition", expect="stepCount stays 250 after CANCEL") return ed = node_by_id(ui(), "steps") tap_node(ed) settle("keyboard") press_key(123) for _ in range(12): press_key(67) type_text(node_by_id(ui(), "steps"), "999") # type a DIFFERENT value... cancel = node_by_id(ui(), "button2") # ...then CANCEL, not SAVE tapped = cancel is not None and tap_node(cancel) settle("tap") after = step_count() ok = bool(tapped) and baseline == "250" and after == "250" record("interaction_correct_steps_cancel_noop", ok, "" if ok else f"behavior_wrong: CANCEL changed the record " f"(baseline={baseline!r} after={after!r}, expected 250)", depth=1, jump_kind="transition", expect="stepCount stays 250 after typing 999 then CANCEL")
# ══════════════���═══════════════════════════════════════════════════════════════# B. WALKING MODES — CRUD-create + multi-record integrity + persistence (depth 2/3)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_add_walking_mode",))def test_add_walking_mode(): # CRUD-create behind Settings -> Walking modes (surface 2) + the Add dialog # (surface 3). Idempotent: modes accumulate across runs, so if ZTestMode is # already present we only assert its presence. The negative half — ABSENT # before the very first add — is proven the first time the suite runs. if not and_reach_walking_modes(): record("interaction_add_walking_mode", False, "setup_failed: could not reach WalkingModesActivity", depth=3, jump_kind="value", expect=f"card {MODE_MARK!r} present") return before = walking_mode_names() already = MODE_MARK in before if not already: if not add_walking_mode(MODE_MARK, "0.60"): record("interaction_add_walking_mode", False, "feature_missing: Add-walking-mode dialog has no working SAVE path", depth=3, jump_kind="value", expect=f"card {MODE_MARK!r} present") return target = scroll_into_view(MODE_MARK) after = walking_mode_names() present = target is not None or MODE_MARK in after # created this run => count strictly grew; already there => still >= 3 cards count_ok = (len(after) > len(before)) if not already else (len(after) >= 3) ok = present and count_ok record("interaction_add_walking_mode", ok, "" if ok else f"behavior_wrong: added mode did not appear " f"(before={before}, after={after})", depth=3, jump_kind="value", expect=f"card {MODE_MARK!r} appears in walking_modes_list")
@and_test(expects=("interaction_walking_mode_survives_death",))def test_walking_mode_survives_death(): # PERSISTENCE probe #2: ensure ZTestMode exists (add if needed), then KILL the # process, relaunch, re-navigate Settings -> Walking modes, and assert the # added record is STILL there. A recreation that keeps modes only in memory # loses it here. if not and_reach_walking_modes(): record("interaction_walking_mode_survives_death", False, "setup_failed: could not reach WalkingModesActivity", depth=2, jump_kind="value", expect=f"card {MODE_MARK!r} after relaunch") return if MODE_MARK not in walking_mode_names(): if not add_walking_mode(MODE_MARK, "0.60"): record("interaction_walking_mode_survives_death", False, "feature_missing: could not create the walking mode to test persistence", depth=2, jump_kind="value", expect=f"card {MODE_MARK!r} after relaunch") return # process death + re-navigate through the real user path and_reset_depth() if not and_reach_walking_modes(): # this itself does restart_app() record("interaction_walking_mode_survives_death", False, "setup_failed: could not re-reach WalkingModesActivity after relaunch", depth=2, jump_kind="value", expect=f"card {MODE_MARK!r} after relaunch") return present = scroll_into_view(MODE_MARK) is not None or MODE_MARK in walking_mode_names() record("interaction_walking_mode_survives_death", present, "" if present else "behavior_wrong: added walking mode did not survive process death", depth=2, jump_kind="value", expect=f"card {MODE_MARK!r} still present after force-stop + relaunch")
@and_test(expects=("interaction_multi_record_integrity",))def test_multi_record_integrity(): # MULTI-RECORD integrity: after adding ZTestMode there are >=3 modes. Assert # the two SEEDED records (Walking(active), Running) are BOTH still intact and # in their original order relative to each other, alongside the added one. # A recreation that recreates the list keeping only one row fails here. if not and_reach_walking_modes(): record("interaction_multi_record_integrity", False, "setup_failed: could not reach WalkingModesActivity", depth=2, jump_kind="value", expect="Walking(active) + Running + ZTestMode all present, seeds ordered") return if MODE_MARK not in walking_mode_names(): add_walking_mode(MODE_MARK, "0.60") scroll_into_view("Running") # make sure lower rows are dumped names = walking_mode_names() has_walking = any("Walking(active)" == x for x in names) has_running = any("Running" == x for x in names) has_added = MODE_MARK in names order_ok = (has_walking and has_running and names.index("Walking(active)") < names.index("Running")) ok = has_walking and has_running and has_added and order_ok record("interaction_multi_record_integrity", ok, "" if ok else f"behavior_wrong: seeded records not intact/ordered " f"alongside the added one (names={names})", depth=2, jump_kind="value", expect="Walking(active) before Running, both intact, ZTestMode also present")
@and_test(expects=("interaction_card_context_menu",))def test_card_context_menu(): # CONTEXT-MENU ownership (long-press / overflow). Tap a card's overflow # `card_menu` (desc "Options") and assert the context menu OPENED — proven by # the non-destructive items "Set as active" and "Learn" appearing (they are # NOT present on the plain list surface). Delete is never tapped; back out. if not and_reach_walking_modes(): record("interaction_card_context_menu", False, "setup_failed: could not reach WalkingModesActivity", depth=3, jump_kind="transition", expect="context menu 'Set as active' + 'Learn' appear") return menu = find_node(ui(), content_desc="Options") before = and_showing() opened = False if menu is not None and tap_node(menu): and_enter("card_context_menu") after = and_showing() nodes = ui() has_active = find_node_ci(nodes, "Set as active") is not None has_learn = find_node_ci(nodes, "Learn") is not None appeared = and_reach(before, after, "Set as active") opened = has_active and has_learn and appeared back() # dismiss the menu without choosing settle("tap") record("interaction_card_context_menu", opened, "" if opened else "feature_missing: card overflow did not open a context menu with Set as active / Learn", depth=3, jump_kind="transition", expect="'Set as active' and 'Learn' appear after tapping the card overflow")
# ══════════════════════════════════════════════════════════════════════════════# C. WALKING-MODE SWITCH — 3+-step select -> close -> reopen -> observe (depth 1)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_switch_active_mode",))def test_switch_active_mode(): # Multi-step, each step depends on the last: open popup (Walking checked) -> # tap Running -> popup CLOSES -> REOPEN -> observe Running now checked and # Walking unchecked. A dead shell that echoes the first tap without persisting # the selection fails on the reopened state. Reset to Walking afterward. restart_app() if not wait_for_foreground(): record("interaction_switch_active_mode", False, "setup_failed: app did not reach the foreground", depth=1, jump_kind="transition", expect="Running checked=true after reopen") return if not open_summary_popup(): record("interaction_switch_active_mode", False, "feature_missing: summary Walking-modes popup did not open", depth=1, jump_kind="transition", expect="Running checked=true after reopen") return and_enter("summary_popup") before = dict(radios_state()) run = find_node_ci(ui(), "Running") tapped = run is not None and tap_node(run) settle("tap") settle("tap") closed = find_node_ci(ui(), "Running") is None # popup dismissed after select reopened = open_summary_popup() after = dict(radios_state()) ok = (bool(tapped) and closed and reopened and before.get("Walking") == "true" and before.get("Running") == "false" and after.get("Running") == "true" and after.get("Walking") == "false") # reset the active mode back to Walking so the app is left as found if reopened: walk = find_node_ci(ui(), "Walking") if walk is not None: tap_node(walk) settle("tap") else: back() record("interaction_switch_active_mode", ok, "" if ok else f"behavior_wrong: active-mode selection did not flip on reopen " f"(before={before}, after={after})", depth=1, jump_kind="transition", expect="after selecting Running and reopening: Running checked, Walking unchecked")
# ══════════════════════════════════════════════════════════════════════════════# D. HELP — expandable-tree interaction (depth 1)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_help_expand_collapse",))def test_help_expand_collapse(): # Tree-data interaction: tap the "Overview" group header -> a descriptive # child text row appears beneath it (subtree GROWS) -> tap again -> it # collapses back. Assert the child text is present when expanded and gone when # collapsed (a specific observed child, not just a node-count delta). restart_app() if not wait_for_foreground(): record("interaction_help_expand_collapse", False, "setup_failed: app did not reach the foreground", depth=1, jump_kind="transition", expect="Overview child row appears then collapses") return d = open_nav_drawer() if d is None or not tap_node(find_node_ci(d, "Help")): record("interaction_help_expand_collapse", False, "setup_failed: could not reach HelpActivity from the drawer", depth=1, jump_kind="transition", expect="Overview child row appears then collapses") return settle("tap") and_enter("help") ov = find_node_ci(ui(), "Overview") if ov is None: record("interaction_help_expand_collapse", False, "feature_missing: Help 'Overview' group header not found", depth=1, jump_kind="transition", expect="Overview child row appears then collapses") return child_snippet = "This app can count your steps"
def overview_child_shown(): # the child row is a long paragraph (id expandedListItem); match by prefix return any(t.startswith(child_snippet) for t in expanded_child_texts())
collapsed_before = not overview_child_shown() # no child before expanding tap_node(ov) settle("tap") expanded = overview_child_shown() # child paragraph appeared ov2 = find_node_ci(ui(), "Overview") if ov2 is not None: tap_node(ov2) settle("tap") recollapsed = not overview_child_shown() # child gone again ok = collapsed_before and expanded and recollapsed record("interaction_help_expand_collapse", ok, "" if ok else "behavior_wrong: expanding/collapsing 'Overview' did not toggle its child row", depth=1, jump_kind="transition", expect="'This app can count your steps...' child appears on expand, gone on collapse")
# ══════════════════════════════════════════════════════════════════════════════# E. TRAINING — CRUD-create of a session record (depth 2)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_training_creates_session",))def test_training_creates_session(): # CRUD-create: start a training (FAB), let it run a moment, then END TRAINING # NOW (SAFE) -> back on the overview a `card_training_session` row exists. # Sessions accumulate across runs, so assert AT LEAST ONE session and that the # count did not shrink. depth=2 (overview -> live), then back to overview. if not and_reach_training_live(): record("interaction_training_creates_session", False, "setup_failed: could not reach the live TrainingActivity", depth=2, jump_kind="value", expect="a training session row exists on the overview") return settle("tap") settle("tap") # let the session accrue a moment stop = node_by_id(ui(), "training_stop_button") stopped = stop is not None and tap_node(stop) settle("tap") settle("tap") # some builds pop a save/OK dialog on stop — commit it if present (never Cancel) ok_btn = node_by_id(ui(), "button1") if ok_btn is not None: tap_node(ok_btn) settle("tap") on_overview = node_by_id(ui(), "start_training") is not None after = session_count() ok = bool(stopped) and on_overview and after >= 1 record("interaction_training_creates_session", ok, "" if ok else f"behavior_wrong: stopping training left no session on the overview " f"(on_overview={on_overview}, sessions={after})", depth=2, jump_kind="value", expect=">=1 card_training_session row on the overview after END TRAINING NOW")
# ═══════════════════════════════════════════════════════════════════════���══════# VLM — EXACTLY 7 rendered-property questions. Each navigates to the right surface# first, screenshots, and asks ONE specific YES/NO a blank screen would fail.# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("interaction_vlm_walking_modes_list_vlm",))def test_vlm_walking_modes_list(): # After ensuring ZTestMode exists there are >=3 cards stacked vertically. if not and_reach_walking_modes(): record("interaction_vlm_walking_modes_list_vlm", False, "setup_failed: could not reach WalkingModesActivity to screenshot", depth=2, jump_kind="reach", tag="layout") return if MODE_MARK not in walking_mode_names(): add_walking_mode(MODE_MARK, "0.60") scroll_into_view("Running") vlm_assert("interaction_vlm_walking_modes_list", "Are there three or more walking-mode rows stacked vertically one " "below another, filling the list from the top of the screen downward?", RESULTS_DIR, depth=2, jump_kind="reach", tag="position")
@and_test(expects=("interaction_vlm_walking_mode_card_vlm",))def test_vlm_walking_mode_card(): # Each seeded card renders a name plus a 'Step length:' value ending 'meters'. if not and_reach_walking_modes(): record("interaction_vlm_walking_mode_card_vlm", False, "setup_failed: could not reach WalkingModesActivity to screenshot", depth=2, jump_kind="reach", tag="content") return vlm_assert("interaction_vlm_walking_mode_card", "On every walking-mode row, is there a vertical three-dot overflow " "menu icon aligned to the far RIGHT edge, with the mode name and its " "'Step length' text on the LEFT side of the same row?", RESULTS_DIR, depth=2, jump_kind="reach", tag="position")
@and_test(expects=("interaction_vlm_context_menu_vlm",))def test_vlm_context_menu(): # The card overflow context menu, showing the non-destructive items. if not and_reach_walking_modes(): record("interaction_vlm_context_menu_vlm", False, "setup_failed: could not reach WalkingModesActivity to screenshot", depth=3, jump_kind="transition", tag="content") return menu = find_node(ui(), content_desc="Options") if menu is None or not tap_node(menu): record("interaction_vlm_context_menu_vlm", False, "feature_missing: card overflow did not open", depth=3, jump_kind="transition", tag="content") return and_enter("card_context_menu") settle("tap") vlm_assert("interaction_vlm_context_menu", "Is a small pop-up context menu shown listing text options including " "'Set as active' and 'Learn'?", RESULTS_DIR, depth=3, jump_kind="transition", tag="content") back() # dismiss without choosing settle("tap")
@and_test(expects=("interaction_vlm_correct_steps_dialog_vlm",))def test_vlm_correct_steps_dialog(): # The Correct-steps dialog open on top of the home report. restart_app() if not wait_for_foreground() or not and_enter_correct_steps_dialog(): record("interaction_vlm_correct_steps_dialog_vlm", False, "setup_failed: could not open the Correct-steps dialog to screenshot", depth=1, jump_kind="transition", tag="layout") return vlm_assert("interaction_vlm_correct_steps_dialog", "In the 'Correct steps' dialog, are the 'CANCEL' and 'SAVE' text " "buttons positioned side by side in the bottom-right corner, with " "'SAVE' to the right of 'CANCEL'?", RESULTS_DIR, depth=1, jump_kind="transition", tag="position") b2 = node_by_id(ui(), "button2") # CANCEL out, change nothing if b2 is not None: tap_node(b2) settle("tap")
@and_test(expects=("interaction_vlm_summary_popup_vlm",))def test_vlm_summary_popup(): # The home summary Walking-modes popup with its radio list. restart_app() if not wait_for_foreground() or not open_summary_popup(): record("interaction_vlm_summary_popup_vlm", False, "setup_failed: could not open the summary Walking-modes popup to screenshot", depth=1, jump_kind="transition", tag="shape") return and_enter("summary_popup") vlm_assert("interaction_vlm_summary_popup", "Is a small pop-up menu shown listing 'Walking' and 'Running' each " "with a round radio button on the right, plus a 'Correct steps' " "option, and is exactly one radio button filled in (selected)?", RESULTS_DIR, depth=1, jump_kind="transition", tag="shape") back() # dismiss, leave mode unchanged settle("tap")
@and_test(expects=("interaction_vlm_help_expanded_vlm",))def test_vlm_help_expanded(): # Help 'Overview' expanded -> descriptive text renders below the heading. restart_app() if not wait_for_foreground(): record("interaction_vlm_help_expanded_vlm", False, "setup_failed: app did not reach the foreground", depth=1, jump_kind="transition", tag="content") return d = open_nav_drawer() if d is None or not tap_node(find_node_ci(d, "Help")): record("interaction_vlm_help_expanded_vlm", False, "setup_failed: could not reach HelpActivity to screenshot", depth=1, jump_kind="transition", tag="content") return settle("tap") and_enter("help") ov = find_node_ci(ui(), "Overview") if ov is None or not tap_node(ov): record("interaction_vlm_help_expanded_vlm", False, "feature_missing: could not expand the 'Overview' help topic", depth=1, jump_kind="transition", tag="content") return settle("tap") vlm_assert("interaction_vlm_help_expanded", "Under the 'Overview' heading of this help list, is a paragraph of " "descriptive body text now shown (the 'Overview' topic is expanded)?", RESULTS_DIR, depth=1, jump_kind="transition", tag="content")
@and_test(expects=("interaction_vlm_training_live_vlm",))def test_vlm_training_live(): # The live training screen grid: duration, distance, velocity, calories, steps. if not and_reach_training_live(): record("interaction_vlm_training_live_vlm", False, "setup_failed: could not reach the live TrainingActivity to screenshot", depth=2, jump_kind="reach", tag="layout") return vlm_assert("interaction_vlm_training_live", "Is a large duration timer centred near the TOP of this screen, with " "four workout stats arranged in a 2-by-2 grid in the middle, and a " "full-width 'END TRAINING NOW' button pinned at the BOTTOM?", RESULTS_DIR, depth=2, jump_kind="reach", tag="position") stop = node_by_id(ui(), "training_stop_button") # cleanup: stop the session if stop is not None: tap_node(stop) settle("tap")
TESTS = [ # A. Correct steps — CRUD-update + persistence + cancel-noop (dialog, depth 1) test_correct_steps_save_persists, test_correct_steps_survives_death, # persistence #1 test_correct_steps_cancel_noop, # B. Walking modes — create + persistence + multi-record + context menu test_add_walking_mode, test_walking_mode_survives_death, # persistence #2 test_multi_record_integrity, test_card_context_menu, # C. Walking-mode switch — 3+-step select/close/reopen/observe test_switch_active_mode, # D. Help — expandable-tree interaction test_help_expand_collapse, # E. Training — CRUD-create of a session record test_training_creates_session, # VLM — exactly 7 rendered-property questions test_vlm_walking_modes_list, test_vlm_walking_mode_card, test_vlm_context_menu, test_vlm_correct_steps_dialog, test_vlm_summary_popup, test_vlm_help_expanded, test_vlm_training_live,]
if __name__ == "__main__": run_suite(TESTS, "interaction")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401#!/usr/bin/env python3"""NAVIGATION module — surface REACHABILITY + back-stack integrity.
Sole owner of jump_kind="reach" and of depth>=2 chains for Privacy FriendlyPedometer. Every jump is proven with and_reach(before, after, target, source):the TARGET surface's discriminating element APPEARED *and* the SOURCE surface'sDISAPPEARED. Reaching a screen by relaunching is NOT navigation — every reachhere goes drawer-item -> screen or FAB/list -> screen and is backed by anand_reach*/and_enter* call.
Golden model (recon.md): Home (MainActivity) = ViewPager of Day/Week/Month reports; drawer (opened via the HAMBURGER, content-desc "Open navigation drawer") reaches Training, Distance Measurement, Settings, Help, About. Drawer items are CheckedTextView (design_menu_item_text); toolbar titles are TextView — so "Training" as a drawer label vs the TrainingOverview title never collide in a surface set. Home discriminator behind the open drawer = "Day"."""import osimport sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from android_testgen_kit import * # noqa: F403,E402
# ── shared entry helpers (plain helpers; the and_* NAME is what the depth audit# keys off — no @and_test decorator here) ──────────────────────────────────
def open_nav_drawer(): """Open the navigation drawer via the HAMBURGER (never open_drawer(), whose edge-swipe drops to the launcher). Returns the fresh drawer node list, or None if the hamburger is absent.""" ham = find_node(ui(), content_desc="Open navigation drawer") if not ham or not tap_node(ham): return None return ui()
def and_reach_from_drawer(label, target, source="Day"): """restart -> open drawer -> tap the drawer item -> prove the jump. The reach is the ITEM tap that lands on the new activity; opening the drawer itself is only an overlay on the same activity, never claimed as a reach.""" restart_app() if not wait_for_foreground(): return False d = open_nav_drawer() if d is None: return False item = find_node_ci(d, label) if item is None: return False return and_reach_surface(item, target, source)
def and_enter_settings(): """restart -> drawer -> Settings. Lands on the PreferencesActivity header list (General / Notifications / Walking modes). Counts one surface.""" ok = and_reach_from_drawer("Settings", "General", "Day") return ok
def and_reach_setting_child(child_label, target, source): """From a fresh Settings header list, tap a header row and prove the child prefs screen was reached. This is the SECOND hop of a depth-2 chain; the first hop (and_enter_settings) has already counted surface 1.""" row = find_node_ci(ui(), child_label) if row is None: return False return and_reach_surface(row, target, source)
# ══════════════════════════════════════════════════════════════════════════════# FORWARD REACH — the 5 top-level drawer destinations (depth 1)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("nav_reach_training",))def test_reach_training(): # Home -> drawer -> "Training" => TrainingOverviewActivity. # target: FAB content-desc "Start training" (overview-only, unambiguous vs # the drawer CheckedTextView "Training"); source: home tab "Day". ok = and_reach_from_drawer("Training", "Start training", "Day") record("nav_reach_training", ok, "" if ok else "feature_missing: could not reach TrainingOverviewActivity from the drawer", depth=1, jump_kind="reach", expect="TrainingOverview 'Start training' FAB visible; home 'Day' tab gone")
@and_test(expects=("nav_reach_distance",))def test_reach_distance(): # Home -> drawer -> "Distance Measurement" => DistanceMeasurementActivity. ok = and_reach_from_drawer("Distance Measurement", "START DISTANCE MEASUREMENT", "Day") record("nav_reach_distance", ok, "" if ok else "feature_missing: could not reach DistanceMeasurementActivity from the drawer", depth=1, jump_kind="reach", expect="'START DISTANCE MEASUREMENT' button visible; home 'Day' tab gone")
@and_test(expects=("nav_reach_settings",))def test_reach_settings(): # Home -> drawer -> "Settings" => PreferencesActivity header list. ok = and_reach_from_drawer("Settings", "General", "Day") record("nav_reach_settings", ok, "" if ok else "feature_missing: could not reach the Settings headers from the drawer", depth=1, jump_kind="reach", expect="Settings 'General' header visible; home 'Day' tab gone")
@and_test(expects=("nav_reach_help",))def test_reach_help(): # Home -> drawer -> "Help" => HelpActivity ("Overview" group header). ok = and_reach_from_drawer("Help", "Overview", "Day") record("nav_reach_help", ok, "" if ok else "feature_missing: could not reach HelpActivity from the drawer", depth=1, jump_kind="reach", expect="Help 'Overview' group header visible; home 'Day' tab gone")
@and_test(expects=("nav_reach_about",))def test_reach_about(): # Home -> drawer -> "About" => AboutActivity (appName). ok = and_reach_from_drawer("About", "Privacy Friendly Pedometer", "Day") record("nav_reach_about", ok, "" if ok else "feature_missing: could not reach AboutActivity from the drawer", depth=1, jump_kind="reach", expect="About appName 'Privacy Friendly Pedometer' visible; home 'Day' tab gone")
# ══════════════════════════════════════════════════════════════════════════════# DEPTH>=2 CHAINS — Settings header -> a sub-prefs surface# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("nav_chain_settings_general",))def test_chain_settings_general(): # depth 2: Home -> drawer -> Settings (surface 1) -> tap "General" (surface 2). s1 = and_enter_settings() s2 = s1 and and_reach_setting_child( "General", "Permanent step counter", "Notifications") record("nav_chain_settings_general", bool(s2), "" if s2 else "feature_missing: Settings -> General chain did not reach the General prefs screen", depth=2, jump_kind="reach", expect="General 'Permanent step counter' title visible; Settings 'Notifications' header gone")
@and_test(expects=("nav_chain_settings_notifications",))def test_chain_settings_notifications(): # depth 2: Home -> drawer -> Settings -> tap "Notifications". s1 = and_enter_settings() s2 = s1 and and_reach_setting_child( "Notifications", "Enable motivation alert", "General") record("nav_chain_settings_notifications", bool(s2), "" if s2 else "feature_missing: Settings -> Notifications chain did not reach the Notifications prefs screen", depth=2, jump_kind="reach", expect="Notifications 'Enable motivation alert' title visible; Settings 'General' header gone")
@and_test(expects=("nav_chain_settings_walkingmodes",))def test_chain_settings_walkingmodes(): # depth 2: Home -> drawer -> Settings -> tap "Walking modes" => WalkingModesActivity. # target: seeded card "Walking(active)" (activity-only); NOT the title # "Walking modes" which also exists as the Settings header row. s1 = and_enter_settings() s2 = s1 and and_reach_setting_child( "Walking modes", "Walking(active)", "Notifications") record("nav_chain_settings_walkingmodes", bool(s2), "" if s2 else "feature_missing: Settings -> Walking modes chain did not reach WalkingModesActivity", depth=2, jump_kind="reach", expect="WalkingModes card 'Walking(active)' visible; Settings 'Notifications' header gone")
@and_test(expects=("nav_chain_training_live",))def test_chain_training_live(): # depth 2: Home -> drawer -> Training (surface 1) -> start_training FAB # (surface 2) => TrainingActivity. CLEAN UP with training_stop_button (SAFE: # "End training now", not Delete) so no training is left running. s1 = and_reach_from_drawer("Training", "Start training", "Day") s2 = False if s1: fab = node_by_id(ui(), "start_training") s2 = fab is not None and and_reach_surface( fab, "END TRAINING NOW", "Start training") # cleanup — return to the overview regardless of the assertion outcome stop = node_by_id(ui(), "training_stop_button") if stop is not None: tap_node(stop) record("nav_chain_training_live", bool(s2), "" if s2 else "feature_missing: Training overview FAB did not reach the live TrainingActivity", depth=2, jump_kind="reach", expect="TrainingActivity 'END TRAINING NOW' button visible; overview 'Start training' FAB gone")
# ══════════════════════════════════════════════════════════════════════════════# BACK-STACK INTEGRITY — pops unwind the stack surface by surface# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("nav_backstack_about_home",))def test_backstack_about_home(): # depth 1 down (drawer -> About), then BACK => MainActivity restored. # Prove the REVERSE reach: home "Day" reappears and About appName disappears. down = and_reach_from_drawer("About", "Privacy Friendly Pedometer", "Day") up = False if down: before = and_showing() and_back() after = and_showing() up = and_reach(before, after, "Day", "Privacy Friendly Pedometer") record("nav_backstack_about_home", bool(up), "" if up else "behavior_wrong: BACK from About did not restore the home MainActivity", depth=1, jump_kind="reach", expect="home 'Day' tab restored after one BACK; About appName gone")
@and_test(expects=("nav_backstack_general_settings",))def test_backstack_general_settings(): # depth 2 down (Settings -> General), then BACK => Settings headers restored. # Prove the reverse reach: "Notifications" header reappears, "Permanent step # counter" (General-only) disappears. s1 = and_enter_settings() s2 = s1 and and_reach_setting_child( "General", "Permanent step counter", "Notifications") up = False if s2: before = and_showing() and_back() after = and_showing() up = and_reach(before, after, "Notifications", "Permanent step counter") record("nav_backstack_general_settings", bool(up), "" if up else "behavior_wrong: BACK from General did not restore the Settings header list", depth=2, jump_kind="reach", expect="Settings 'Notifications' header restored after one BACK; General 'Permanent step counter' gone")
@and_test(expects=("nav_backstack_walkingmodes_deep",))def test_backstack_walkingmodes_deep(): # Deepest chain popped hop by hop: Home -> Settings -> Walking modes, then # BACK (=> Settings headers), then BACK (=> home). Assert the surface after # EACH pop, so the back stack is proven to unwind one surface at a time. s1 = and_enter_settings() s2 = s1 and and_reach_setting_child( "Walking modes", "Walking(active)", "Notifications") hop1 = hop2 = False if s2: b1 = and_showing() and_back() # WalkingModes -> Settings headers a1 = and_showing() hop1 = and_reach(b1, a1, "Notifications", "Walking(active)") and_back() # Settings headers -> home a2 = and_showing() hop2 = and_reach(a1, a2, "Day", "Notifications") ok = bool(s2 and hop1 and hop2) record("nav_backstack_walkingmodes_deep", ok, "" if ok else "behavior_wrong: two BACKs from Walking modes did not unwind Settings then home hop by hop", depth=2, jump_kind="reach", expect="1st BACK restores Settings 'Notifications'; 2nd BACK restores home 'Day'")
@and_test(expects=("nav_backstack_distance_home",))def test_backstack_distance_home(): # depth 1 down (drawer -> Distance Measurement), then BACK => home restored. down = and_reach_from_drawer("Distance Measurement", "START DISTANCE MEASUREMENT", "Day") up = False if down: before = and_showing() and_back() after = and_showing() up = and_reach(before, after, "Day", "START DISTANCE MEASUREMENT") record("nav_backstack_distance_home", bool(up), "" if up else "behavior_wrong: BACK from Distance Measurement did not restore the home MainActivity", depth=1, jump_kind="reach", expect="home 'Day' tab restored after one BACK; 'START DISTANCE MEASUREMENT' gone")
# ══════════════════════════════════════════════════════════════════════════════# VLM — rendered destination end-states (EXACTLY 6). Navigate to the correct# surface first, then screenshot + ask ONE specific YES/NO about what renders.# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("nav_vlm_training_overview_vlm",))def test_vlm_training_overview(): ok = and_reach_from_drawer("Training", "Start training", "Day") if ok: vlm_assert("nav_vlm_training_overview", "Is there a round blue floating action button with a white plus " "sign in the bottom-right corner of this screen?", RESULTS_DIR, depth=1, jump_kind="reach", tag="position") else: record("nav_vlm_training_overview_vlm", False, "setup_failed: could not reach TrainingOverviewActivity to screenshot", depth=1, jump_kind="reach", tag="position")
@and_test(expects=("nav_vlm_distance_vlm",))def test_vlm_distance(): ok = and_reach_from_drawer("Distance Measurement", "START DISTANCE MEASUREMENT", "Day") if ok: vlm_assert("nav_vlm_distance", "Is there a full-width dark-blue button labelled 'START DISTANCE " "MEASUREMENT' pinned to the bottom of this screen?", RESULTS_DIR, depth=1, jump_kind="reach", tag="position") else: record("nav_vlm_distance_vlm", False, "setup_failed: could not reach DistanceMeasurementActivity to screenshot", depth=1, jump_kind="reach", tag="position")
@and_test(expects=("nav_vlm_settings_headers_vlm",))def test_vlm_settings_headers(): ok = and_reach_from_drawer("Settings", "General", "Day") if ok: vlm_assert("nav_vlm_settings_headers", "Does this screen show a vertical settings list with three rows " "labelled 'General', 'Notifications' and 'Walking modes', each " "with an icon on the left?", RESULTS_DIR, depth=1, jump_kind="reach", tag="layout") else: record("nav_vlm_settings_headers_vlm", False, "setup_failed: could not reach the Settings headers to screenshot", depth=1, jump_kind="reach", tag="layout")
@and_test(expects=("nav_vlm_about_vlm",))def test_vlm_about(): ok = and_reach_from_drawer("About", "Privacy Friendly Pedometer", "Day") if ok: vlm_assert("nav_vlm_about", "Does this About screen show the SECUSO logo (a round emblem to " "the left of the word 'SECUSO') in its middle area?", RESULTS_DIR, depth=1, jump_kind="reach", tag="shape") else: record("nav_vlm_about_vlm", False, "setup_failed: could not reach AboutActivity to screenshot", depth=1, jump_kind="reach", tag="shape")
@and_test(expects=("nav_vlm_help_vlm",))def test_vlm_help(): ok = and_reach_from_drawer("Help", "Overview", "Day") if ok: vlm_assert("nav_vlm_help", "Does this screen show a top app bar titled 'Help' and, below it, " "a vertical list of help topics starting with 'Overview'?", RESULTS_DIR, depth=1, jump_kind="reach", tag="layout") else: record("nav_vlm_help_vlm", False, "setup_failed: could not reach HelpActivity to screenshot", depth=1, jump_kind="reach", tag="layout")
@and_test(expects=("nav_vlm_training_live_vlm",))def test_vlm_training_live(): # depth 2: reach the LIVE TrainingActivity, screenshot, then clean up. s1 = and_reach_from_drawer("Training", "Start training", "Day") reached = False if s1: fab = node_by_id(ui(), "start_training") reached = fab is not None and and_reach_surface( fab, "END TRAINING NOW", "Start training") if reached: vlm_assert("nav_vlm_training_live", "Is there a prominent full-width button labelled 'END TRAINING " "NOW' at the bottom of this screen?", RESULTS_DIR, depth=2, jump_kind="reach", tag="position") stop = node_by_id(ui(), "training_stop_button") if stop is not None: tap_node(stop) # cleanup: leave no training running else: record("nav_vlm_training_live_vlm", False, "setup_failed: could not reach the live TrainingActivity to screenshot", depth=2, jump_kind="reach", tag="position")
TESTS = [ # forward reach (5 drawer destinations) test_reach_training, test_reach_distance, test_reach_settings, test_reach_help, test_reach_about, # depth>=2 chains (4) test_chain_settings_general, test_chain_settings_notifications, test_chain_settings_walkingmodes, test_chain_training_live, # back-stack integrity (4) test_backstack_about_home, test_backstack_general_settings, test_backstack_walkingmodes_deep, test_backstack_distance_home, # VLM rendered destinations (6) test_vlm_training_overview, test_vlm_distance, test_vlm_settings_headers, test_vlm_about, test_vlm_help, test_vlm_training_live,]
if __name__ == "__main__": run_suite(TESTS, "navigation")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145#!/usr/bin/env python3"""STATES module — widget STATE through before/after interaction.
This module owns CHECKED and FOCUSED and every selected/enabled/mode transitionPAIRED with the app-authored consequence, plus SETTINGS/mode persistence acrossprocess death. Nothing here is a bare flip: a `checked`/`selected` change isalways paired with the observable effect the app authors around it (a rangeperiod label, a shown/hidden button, a radio that stays selected on reopen).
GROUND TRUTH (verified live on the running original, which is authoritative):
* Pause/continue (E): toolbar Button `menu_pause_step_detection` (content-desc "Pause step detection"). Tapping it REPLACES the node with `menu_continue_step_detection` (desc "Continue step detection") and the pause node DISAPPEARS. Tapping again reverts. The app-authored consequence is this identity + content-desc flip (an icon button, so no `checked`).
* Tabs (A): the tab is a LinearLayout with content-desc "Day"/"Week"/"Month". On launch "Day" has selected="true"; the others selected="false". Tapping "Week" moves selected="true" to Week AND the two `period` labels change to a range ("02. - 08. August", contains " - "). Month -> "<Month> <YY>" (^[A-Za-z]+ \\d{2}$). So each tab test pairs the `selected` flip with the computed period label consequence.
* Walking-mode popup (C): summary `periodMoreButton` (desc "Walking modes") opens a ListView of rows; each row is a `title` TextView plus a sibling RadioButton id `radio` (checkable=true). On open the "Walking" row's radio is checked=true, "Running" false. Selecting "Running" closes the popup; reopening shows the "Running" radio checked=true — the app-authored consequence. (The device may carry extra seeded modes, so rows are matched by title text, never by count.) RESET to Walking afterwards.
* Chart-type popup (D): chart `periodMoreButton` (desc "Options") opens a radio list Steps(checked)/Distance/Calories. Selecting "Distance" and reopening shows Distance checked=true, Steps false. RESET to Steps afterwards.
* Distance measurement (G): DistanceMeasurementActivity, Button `start_button` ("START DISTANCE MEASUREMENT"). Tapping it REPLACES it with `stop_button` ("STOP DISTANCE MEASUREMENT"); start disappears. A page-level state machine (idle vs measuring). Tapping stop reverts. Asserted on the same Activity. NOTE: starting a measurement makes the app request the LOCATION runtime permission the first time; a left-over system dialog would otherwise leak onto the next test, so every test enters through launch_clean(), which grants any pending permission dialog through the GUI (never `pm grant`).
* Drawer (nav_view): each item is a CheckedTextView `design_menu_item_text`; the item for the CURRENT screen is checked=true ("Pedometer" on Home), the rest false. Beware: the toolbar title and the drawer header are ALSO the text "Pedometer" but are plain TextViews — _drawer_item() matches the CheckedTextView by resource-id suffix so the right node is read.
* Settings General (H): PreferencesActivity list of prefs. Each switch is a `switch_widget` Switch whose row also has an `android:id/title` TextView; the switch itself is clickable="false" AND SO IS EVERY OTHER NODE IN THE ROW (the title, the widget_frame, the row LinearLayout) — nothing carries clickable="true". Tapping the narrow title is therefore a no-op; the reliable toggle is a tap on the FULL-WIDTH row CONTAINER's centre (the widest node whose vertical bounds contain the title's y-centre and whose height is a normal row height), which is what _tap_pref_row does (verified live: velocity false->true->false via this tap). Defaults: "Show current velocity"=OFF, "Use phone's step counting hardware"=OFF, "Permanent step counter"=ON, "Keep processor awake"=ON, "Wake lock during training"=ON. Toggling "Show current velocity" ON PERSISTS across force_stop_and_relaunch() back to General — the signature persistence probe an in-memory recreation fails. Each settings toggle test ENSURES the switch is OFF first (idempotent across repeat runs even if a prior run left it ON), asserts the OFF->ON flip, then restores OFF so the suite is order-free.
CONDITIONAL GUARD: "Use phone's step counting hardware" is a hardware-gated preference — the app refuses to turn it ON when the device lacks a step-counting sensor (PackageManager has neither android.hardware.sensor.stepcounter nor ...stepdetector). On such a device the row tap correctly leaves the switch OFF; on a sensor-equipped device it flips to ON. The test asserts EITHER the OFF->ON flip OR (still OFF AND the feature is provably absent) — both are the app's authored, observed behaviour, never a bare existence check. The feature is read with `pm list features` (a device query, not a state-seed).
PAIRING title -> switch: switches are stacked tightly, so a title's switch is the`switch_widget` whose y-center is nearest the title's y-center (see _row_switch).Radio popups pair the same way via _radio_for_title.
DEPTH: pause/tab/drawer flips are same-surface (depth 0). Popups are depth 1,backed by and_enter_popup(). Settings->General is depth 2, backed byand_reach_general(). Persistence relaunches, then re-navigates Settings->General(depth 2 again). jump_kind is "transition" for flips, "value" for the persistenceassertion of one specific resulting state."""import osimport reimport sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from android_testgen_kit import * # noqa: F403,E402
TESTS = []
def test(fn): """Register a test function for run_suite().""" TESTS.append(fn) return fn
# ── shared helpers ───────────────────────────────────────────────────────────
def _ycenter(node): b = node.get("_bounds") return (b[1] + b[3]) // 2 if b else None
# Allow buttons on the STOCK system permission dialog, matched by resource-id# LAST SEGMENT (never a package literal, so this stays portable) and, as a# fallback, by the exact button label. "Deny/Don't allow" is deliberately absent:# this helper only ever GRANTS, and does so through the real GUI (no `pm grant`)._PERM_ALLOW_IDS = ( "permission_allow_button", "permission_allow_foreground_only_button", "permission_allow_one_time_button",)_PERM_ALLOW_TEXTS = ("Allow", "While using the app", "Only this time")
def _permission_dialog_present(nodes=None): nodes = ui() if nodes is None else nodes for rid in _PERM_ALLOW_IDS: if node_by_id(nodes, rid) is not None: return True return any(find_node(nodes, text=t) is not None for t in _PERM_ALLOW_TEXTS)
def grant_pending_permission(max_dialogs=3): """Dismiss (by GRANTING) any stock runtime-permission dialog currently on screen — the app requests location when a distance measurement starts, and a left-over dialog otherwise leaks onto the next test. Portable and GUI-only. Returns True if it dismissed at least one dialog.""" dismissed = False for _ in range(max_dialogs): nodes = ui() btn = None for rid in _PERM_ALLOW_IDS: btn = node_by_id(nodes, rid) if btn is not None: break if btn is None: for t in _PERM_ALLOW_TEXTS: btn = find_node(nodes, text=t) if btn is not None: break if btn is None: break tap_node(btn) settle("tap") dismissed = True return dismissed
def _clear_pending_dialog(): """Grant a stray permission dialog and re-foreground the app if granting it bounced us to the launcher.""" for _ in range(3): if not _permission_dialog_present(): return grant_pending_permission() if not is_app_foreground(): launch_app() wait_for_foreground()
def launch_clean(): """restart_app(), then clear any pending permission dialog and make sure we land on the app's own MainActivity. This is the entry point every test uses instead of a bare restart_app().""" restart_app() wait_for_foreground() _clear_pending_dialog()
def _on_home_surface(nodes=None): """True when the current surface is the app's home/pedometer screen — a Home-only marker is present (the tab strip `tabs`, or the drawer hamburger). Used to leakage-proof tests that assume they start on Home.""" nodes = ui() if nodes is None else nodes return (node_by_id(nodes, "tabs") is not None or find_node(nodes, content_desc="Open navigation drawer") is not None)
def open_hamburger(): """Open the navigation drawer via the hamburger button (recon: open_drawer() edge-swipe drops to the launcher on this emulator). Clears a stray permission dialog first, since a left-over one would hide the hamburger.""" _clear_pending_dialog() ham = find_node(ui(), content_desc="Open navigation drawer") return tap_node(ham) if ham else False
def _drawer_item(nodes, label): """The drawer menu row (CheckedTextView `design_menu_item_text`) whose text matches `label` — NOT the toolbar title or drawer header of the same text.""" for n in nodes: rid = (n.get("resource-id") or "").rsplit("/", 1)[-1] if (rid == "design_menu_item_text" and n.get("text", "").strip().lower() == label.strip().lower()): return n return None
def and_reach_general(): """Navigate drawer -> Settings -> General and PROVE both surface jumps. Counts TWO surfaces (drawer->Settings headers, headers->General) so a declared depth=2 is backed by real navigation, not typed.""" if not open_hamburger(): return False, "setup_failed: hamburger not found" settle("tap") settings = _drawer_item(ui(), "Settings") or find_node_ci(ui(), "Settings") if settings is None or not tap_node(settings): return False, "setup_failed: Settings drawer item not found" and_enter("settings_headers") settle("tap") gen = find_node_ci(ui(), "General") if gen is None: return False, "setup_failed: General header not found" before = and_showing() if not tap_node(gen): return False, "setup_failed: General not tappable" after = and_showing() # General surface is proven by the appearance of a switch_widget/known pref. if not surface_changed(before, after): return False, "behavior_wrong: General screen did not open" and_enter("general") return True, ""
def _row_switch(nodes, title_text): """Return (title_node, switch_node) for a General pref row, pairing the `switch_widget` whose y-center is nearest the title's y-center. Robust to the tightly-stacked list where a switch sits just BELOW its title.""" title = None for n in nodes: rid = (n.get("resource-id") or "").rsplit("/", 1)[-1] if rid == "title" and n.get("text", "").strip().lower() == title_text.strip().lower(): title = n break if title is None: return None, None ty = _ycenter(title) switches = [n for n in nodes if (n.get("resource-id") or "").rsplit("/", 1)[-1] == "switch_widget" and n.get("_bounds")] if ty is None or not switches: return title, None best = min(switches, key=lambda s: abs(_ycenter(s) - ty)) return title, best
def _radio_for_title(nodes, title_text): """Return (title_node, radio_node) for a popup list row, pairing the `radio` RadioButton whose y-center is nearest the `title` TextView's y-center (same row). Rows are matched by title TEXT, never by index/count, so extra seeded modes on the device do not shift the pairing (see module docstring §C).""" title = None for n in nodes: rid = (n.get("resource-id") or "").rsplit("/", 1)[-1] if rid == "title" and n.get("text", "").strip().lower() == title_text.strip().lower(): title = n break if title is None: return None, None ty = _ycenter(title) radios = [n for n in nodes if (n.get("resource-id") or "").rsplit("/", 1)[-1] == "radio" and n.get("_bounds")] if ty is None or not radios: return title, None best = min(radios, key=lambda r: abs(_ycenter(r) - ty)) return title, best
def _velocity_switch_state(): """Scroll 'Show current velocity' into view and return its switch checked string ('true'/'false'/None). Re-dumps, so the returned nodes are fresh.""" t = scroll_into_view("Show current velocity") if t is None: return None, None, None nodes = ui() title, sw = _row_switch(nodes, "Show current velocity") return nodes, title, sw
def _tap_pref_row(title_text): """Tap the FULL-WIDTH row CONTAINER centre for the preference whose title is `title_text`. In this app's AndroidX preference rows NO node is clickable="true" (not the title, the switch_widget, or the widget_frame), so tapping the narrow title is a no-op; the container tap is what toggles the switch (verified live). Steps: find the `title` node, take its y-centre `ty`, pick the node with the LARGEST width whose bounds satisfy b[1] <= ty <= b[3] and (b[3]-b[1]) <= 400 (a normal row height, excluding the whole list), and tap its centre. Returns True if it tapped, False if the title/row was absent.""" nodes = ui() title = None for n in nodes: rid = (n.get("resource-id") or "").rsplit("/", 1)[-1] if rid == "title" and n.get("text", "").strip().lower() == title_text.strip().lower(): title = n break if title is None or not title.get("_bounds"): return False ty = _ycenter(title) best_b, best_w = None, -1 for n in nodes: b = n.get("_bounds") if not b: continue if b[1] <= ty <= b[3] and (b[3] - b[1]) <= 400: w = b[2] - b[0] if w > best_w: best_w, best_b = w, b if best_b is None: return False tap((best_b[0] + best_b[2]) // 2, (best_b[1] + best_b[3]) // 2) settle("tap") return True
def _toggle_pref_row(title_text): """Toggle a preference by tapping its full-width ROW CONTAINER (the switch and every other row node are clickable="false"), re-scrolling the title into view first so the tap lands on the current coordinates. Returns the switch's checked string AFTER the tap.""" t = scroll_into_view(title_text) if t is None: return None _tap_pref_row(title_text) # re-scroll (a toggle can shift the list) and read the fresh state scroll_into_view(title_text) _, sw = _row_switch(ui(), title_text) return sw.get("checked") if sw else None
def _ensure_pref_off(title_text): """Make the switch for `title_text` read OFF, tapping its row if needed. Idempotent regardless of what a prior run left behind.""" scroll_into_view(title_text) _, sw = _row_switch(ui(), title_text) if sw is not None and sw.get("checked") == "true": _toggle_pref_row(title_text) scroll_into_view(title_text) _, sw2 = _row_switch(ui(), title_text) return sw2.get("checked") if sw2 else None
def _device_has_step_hardware(): """True iff the device advertises a hardware step-counting sensor. The 'Use phone's step counting hardware' preference is guarded on this: without the feature the app refuses to enable the switch. Read via `pm list features` (a device QUERY, not a state-seed like `pm grant`/`settings put`).""" feats = adb_shell("pm", "list", "features") return ("android.hardware.sensor.stepcounter" in feats or "android.hardware.sensor.stepdetector" in feats)
def open_summary_popup(): """Tap the summary card's `periodMoreButton` (desc 'Walking modes') and confirm the popup opened (a `radio` row appeared). Counts one surface.""" btn = find_node(ui(), content_desc="Walking modes") if btn is None or not tap_node(btn): return False settle("tap") if node_by_id(ui(), "radio") is None: return False and_enter("wm_popup") return True
def open_chart_popup(): """Tap the chart card's `periodMoreButton` (desc 'Options') and confirm the popup opened. Counts one surface.""" btn = find_node(ui(), content_desc="Options") if btn is None or not tap_node(btn): return False settle("tap") if node_by_id(ui(), "radio") is None: return False and_enter("chart_popup") return True
def reach_distance_measurement(): """Navigate drawer -> Distance Measurement and PROVE the jump (start_button appeared). Counts one surface.""" if not open_hamburger(): return False settle("tap") item = _drawer_item(ui(), "Distance Measurement") or find_node_ci(ui(), "Distance Measurement") if item is None: return False before = and_showing() if not tap_node(item): return False after = and_showing() if not and_reach(before, after, "start_button"): # fall back to a text-based reach in case id key differs if not any("distance" in k.lower() for k in (after - before)): return False and_enter("distance_measurement") return True
def distance_tap_start(): """Tap START and return the fresh nodes once the measuring state settles. Starting a measurement may raise the LOCATION permission dialog the first time; grant it through the GUI and re-tap START so the state machine actually advances. Returns nodes after the (possibly retried) START.""" start = node_by_id(ui(), "start_button") if start is None: return ui() tap_node(start) settle("tap") if _permission_dialog_present(): grant_pending_permission() # granting can bounce to launcher / re-render — re-navigate + re-tap. if not is_app_foreground(): launch_app() wait_for_foreground() reach_distance_measurement() start = node_by_id(ui(), "start_button") if start is not None: tap_node(start) settle("tap") return ui()
def _tab(nodes, desc): return find_node(nodes, content_desc=desc)
def _period_texts(nodes): return [n.get("text", "") for n in nodes if (n.get("resource-id") or "").rsplit("/", 1)[-1] == "period"]
# ══════════════════════════════════════════════════════════════════════════════# E. Pause / continue step detection (toolbar) — same-surface identity flip# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_pause_to_continue", "states_pause_icon_vlm"))@testdef test_pause_to_continue(): launch_clean() nodes = ui() pause = node_by_id(nodes, "menu_pause_step_detection") if pause is None: record("states_pause_to_continue", False, "feature_missing: no 'menu_pause_step_detection' toolbar button", depth=0, jump_kind="transition", expect="button becomes Continue step detection; pause button gone") vlm_assert("states_pause_icon", "Is there a pause icon (two vertical bars) " "in the top-right of the blue toolbar?", RESULTS_DIR, depth=0, jump_kind="transition", tag="shape") return before_pause = pause.get("content-desc") tap_node(pause) fresh = ui() cont = node_by_id(fresh, "menu_continue_step_detection") pause_gone = node_by_id(fresh, "menu_pause_step_detection") is None ok = (cont is not None and cont.get("content-desc") == "Continue step detection" and pause_gone and before_pause == "Pause step detection") record("states_pause_to_continue", ok, "" if ok else "behavior_wrong: pause button did not flip to " "'Continue step detection' with the pause node gone", depth=0, jump_kind="transition", expect="Pause step detection -> Continue step detection; pause node gone") # VLM: after pausing, the toolbar icon should read as a play/continue glyph. vlm_assert("states_pause_icon", "Look at the icon button in the top-right of the blue toolbar. Is it " "now a single right-pointing 'play' / triangle style icon (indicating " "detection is paused and can be continued) rather than two pause bars?", RESULTS_DIR, depth=0, jump_kind="transition", tag="shape") # restore: tap continue back to pause tap_node(node_by_id(ui(), "menu_continue_step_detection") or {})
@and_test(expects=("states_continue_back_to_pause",))@testdef test_continue_back_to_pause(): launch_clean() nodes = ui() pause = node_by_id(nodes, "menu_pause_step_detection") if pause is None: record("states_continue_back_to_pause", False, "feature_missing: no 'menu_pause_step_detection' toolbar button", depth=0, jump_kind="transition", expect="Continue -> Pause step detection; continue node gone") return # go to the paused state first tap_node(pause) cont = node_by_id(ui(), "menu_continue_step_detection") if cont is None: record("states_continue_back_to_pause", False, "setup_failed: could not reach the paused (Continue) state", depth=0, jump_kind="transition", expect="Continue -> Pause step detection; continue node gone") return tap_node(cont) fresh = ui() pause_back = node_by_id(fresh, "menu_pause_step_detection") cont_gone = node_by_id(fresh, "menu_continue_step_detection") is None ok = (pause_back is not None and pause_back.get("content-desc") == "Pause step detection" and cont_gone) record("states_continue_back_to_pause", ok, "" if ok else "behavior_wrong: Continue did not revert to " "'Pause step detection' with the continue node gone", depth=0, jump_kind="transition", expect="Continue step detection -> Pause step detection; continue node gone")
# ══════════════════════════════════════════════════════════════════════════════# A. Tabs — selected flip PAIRED with the computed period label# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_tab_day_selected_on_launch", "states_tab_day_highlight_vlm"))@testdef test_tab_day_selected_on_launch(): launch_clean() nodes = ui() day = _tab(nodes, "Day") week = _tab(nodes, "Week") month = _tab(nodes, "Month") if day is None or week is None or month is None: record("states_tab_day_selected_on_launch", False, "feature_missing: Day/Week/Month tabs not found", depth=0, jump_kind="transition", expect="Day tab selected=true; Week/Month selected=false on launch") vlm_assert("states_tab_day_highlight", "Is the 'DAY' tab visually highlighted?", RESULTS_DIR, depth=0, jump_kind="transition", tag="color") return ok = (day.get("selected") == "true" and week.get("selected") == "false" and month.get("selected") == "false") record("states_tab_day_selected_on_launch", ok, "" if ok else "behavior_wrong: Day tab is not the selected one on launch", depth=0, jump_kind="transition", expect="Day selected=true; Week=false; Month=false on launch") # VLM: the selected tab is drawn with a highlight colour + underline indicator. vlm_assert("states_tab_day_highlight", "Among the three tabs DAY, WEEK, MONTH at the top, is 'DAY' the " "highlighted/selected one (its label a different, brighter colour such " "as yellow AND with a coloured underline indicator beneath it) while " "WEEK and MONTH are plain white with no underline?", RESULTS_DIR, depth=0, jump_kind="transition", tag="color")
@and_test(expects=("states_tab_switch_day_to_week", "states_tab_week_highlight_vlm"))@testdef test_tab_switch_day_to_week(): launch_clean() nodes = ui() day = _tab(nodes, "Day") week = _tab(nodes, "Week") if day is None or week is None: record("states_tab_switch_day_to_week", False, "feature_missing: Day/Week tabs not found", depth=0, jump_kind="transition", expect="Week selected=true after tap; period label becomes a range") vlm_assert("states_tab_week_highlight", "Is the 'WEEK' tab the highlighted/selected one?", RESULTS_DIR, depth=0, jump_kind="transition", tag="color") return day_before = day.get("selected") tap_node(week) fresh = ui() week_after = _tab(fresh, "Week") day_after = _tab(fresh, "Day") periods = _period_texts(fresh) range_shown = any(" - " in p for p in periods) ok = (day_before == "true" and week_after is not None and week_after.get("selected") == "true" and day_after is not None and day_after.get("selected") == "false" and range_shown) record("states_tab_switch_day_to_week", ok, "" if ok else "behavior_wrong: selected did not move Day->Week or the " "period label did not become a range", depth=0, jump_kind="transition", expect="Week selected=true, Day selected=false; period label a range " "containing ' - '") # VLM: the highlight MOVED from Day to Week. vlm_assert("states_tab_week_highlight", "Among the three tabs DAY, WEEK, MONTH at the top, is 'WEEK' now the " "highlighted/selected one (brighter/different colour label AND a " "coloured underline indicator beneath WEEK) instead of DAY?", RESULTS_DIR, depth=0, jump_kind="transition", tag="color")
@and_test(expects=("states_tab_switch_week_to_month",))@testdef test_tab_switch_week_to_month(): launch_clean() nodes = ui() week = _tab(nodes, "Week") month = _tab(nodes, "Month") if week is None or month is None: record("states_tab_switch_week_to_month", False, "feature_missing: Week/Month tabs not found", depth=0, jump_kind="transition", expect="Month selected=true after tap; period matches '<Month> <YY>'") return tap_node(week) settle("tap") month = _tab(ui(), "Month") tap_node(month) fresh = ui() month_after = _tab(fresh, "Month") week_after = _tab(fresh, "Week") periods = _period_texts(fresh) month_pattern = any(re.match(r"^[A-Za-z]+ \d{2}$", p.strip()) for p in periods) ok = (month_after is not None and month_after.get("selected") == "true" and week_after is not None and week_after.get("selected") == "false" and month_pattern) record("states_tab_switch_week_to_month", ok, "" if ok else "behavior_wrong: selected did not move Week->Month or the " "period label did not match '<Month> <YY>'", depth=0, jump_kind="transition", expect="Month selected=true, Week selected=false; period '<Month> <YY>'")
@and_test(expects=("states_tab_back_to_day",))@testdef test_tab_back_to_day(): launch_clean() nodes = ui() week = _tab(nodes, "Week") if week is None or _tab(nodes, "Day") is None: record("states_tab_back_to_day", False, "feature_missing: Day/Week tabs not found", depth=0, jump_kind="transition", expect="Day selected=true again after returning from Week") return tap_node(week) settle("tap") day = _tab(ui(), "Day") tap_node(day) fresh = ui() day_after = _tab(fresh, "Day") week_after = _tab(fresh, "Week") periods = _period_texts(fresh) # Day period is a single day: "DD. Month" — no range, no year-2-digit pattern. day_single = any(re.match(r"^\d{1,2}\. [A-Za-z]+$", p.strip()) for p in periods) ok = (day_after is not None and day_after.get("selected") == "true" and week_after is not None and week_after.get("selected") == "false" and day_single) record("states_tab_back_to_day", ok, "" if ok else "behavior_wrong: selected did not return to Day or the " "period label is not a single 'DD. Month' day", depth=0, jump_kind="transition", expect="Day selected=true, Week selected=false; period 'DD. Month'")
# ══════════════════════════════════════════════════════════════════════════════# C. Walking-mode radio (summary popup) — depth 1# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_walking_radio_default", "states_walking_radio_default_vlm"))@testdef test_walking_radio_default(): launch_clean() if find_node(ui(), content_desc="Walking modes") is None: record("states_walking_radio_default", False, "feature_missing: summary 'Walking modes' button not found", depth=1, jump_kind="transition", expect="Walking radio checked=true, Running checked=false on open") vlm_assert("states_walking_radio_default", "Is a radio button filled next to 'Walking'?", RESULTS_DIR, depth=1, jump_kind="transition", tag="shape") return if not open_summary_popup(): record("states_walking_radio_default", False, "setup_failed: walking-mode popup did not open", depth=1, jump_kind="transition", expect="Walking radio checked=true, Running checked=false on open") vlm_assert("states_walking_radio_default", "Is a radio button filled next to 'Walking'?", RESULTS_DIR, depth=1, jump_kind="transition", tag="shape") return nodes = ui() _, walk_radio = _radio_for_title(nodes, "Walking") _, run_radio = _radio_for_title(nodes, "Running") ok = (walk_radio is not None and walk_radio.get("checked") == "true" and run_radio is not None and run_radio.get("checked") == "false") record("states_walking_radio_default", ok, "" if ok else "behavior_wrong: Walking radio not checked / Running not " "unchecked when the popup opens", depth=1, jump_kind="transition", expect="Walking radio checked=true, Running checked=false on open") # VLM: the Walking radio is the filled (blue) one. vlm_assert("states_walking_radio_default", "In this popup listing walking modes, is the round radio button next " "to 'Walking' filled in (a solid coloured/blue dot = selected) while " "the radio next to 'Running' is an empty hollow circle?", RESULTS_DIR, depth=1, jump_kind="transition", tag="shape") back() # close popup
@and_test(expects=("states_walking_select_running", "states_running_radio_vlm"))@testdef test_walking_select_running(): launch_clean() if find_node(ui(), content_desc="Walking modes") is None: record("states_walking_select_running", False, "feature_missing: summary 'Walking modes' button not found", depth=1, jump_kind="transition", expect="Running radio checked=true after selecting it and reopening") vlm_assert("states_running_radio", "Is the radio next to 'Running' filled/selected?", RESULTS_DIR, depth=1, jump_kind="transition", tag="shape") return if not open_summary_popup(): record("states_walking_select_running", False, "setup_failed: walking-mode popup did not open", depth=1, jump_kind="transition", expect="Running radio checked=true after selecting it and reopening") vlm_assert("states_running_radio", "Is the radio next to 'Running' filled/selected?", RESULTS_DIR, depth=1, jump_kind="transition", tag="shape") return # select Running by tapping its title row run_title, _ = _radio_for_title(ui(), "Running") if run_title is None or not tap_node(run_title): record("states_walking_select_running", False, "setup_failed: 'Running' row not tappable", depth=1, jump_kind="transition", expect="Running radio checked=true after selecting it and reopening") vlm_assert("states_running_radio", "Is the radio next to 'Running' filled/selected?", RESULTS_DIR, depth=1, jump_kind="transition", tag="shape") return settle("tap") # reopen popup — the selection must have stuck reopened = open_summary_popup() nodes = ui() _, run_radio = _radio_for_title(nodes, "Running") _, walk_radio = _radio_for_title(nodes, "Walking") ok = (reopened and run_radio is not None and run_radio.get("checked") == "true" and walk_radio is not None and walk_radio.get("checked") == "false") record("states_walking_select_running", ok, "" if ok else "behavior_wrong: Running radio did not become checked (and " "Walking unchecked) after selection + reopen", depth=1, jump_kind="transition", expect="Running radio checked=true, Walking checked=false on reopen") # VLM while popup shows Running selected. vlm_assert("states_running_radio", "In this walking-modes popup, is the round radio button next to " "'Running' now filled in (solid coloured/blue dot = selected)?", RESULTS_DIR, depth=1, jump_kind="transition", tag="shape") # RESET active mode back to Walking if reopened: walk_title, _ = _radio_for_title(ui(), "Walking") if walk_title: tap_node(walk_title)
# ══════════════════════════════════════════════════════════════════════════════# D. Chart data-type radio (chart popup) — depth 1# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_chart_radio_default", "states_chart_steps_radio_vlm"))@testdef test_chart_radio_default(): launch_clean() if find_node(ui(), content_desc="Options") is None: record("states_chart_radio_default", False, "feature_missing: chart 'Options' button not found", depth=1, jump_kind="transition", expect="Steps radio checked=true, Distance/Calories false on open") vlm_assert("states_chart_steps_radio", "Is a radio filled next to 'Steps'?", RESULTS_DIR, depth=1, jump_kind="transition", tag="shape") return if not open_chart_popup(): record("states_chart_radio_default", False, "setup_failed: chart-type popup did not open", depth=1, jump_kind="transition", expect="Steps radio checked=true, Distance/Calories false on open") vlm_assert("states_chart_steps_radio", "Is a radio filled next to 'Steps'?", RESULTS_DIR, depth=1, jump_kind="transition", tag="shape") return nodes = ui() _, steps_radio = _radio_for_title(nodes, "Steps") _, dist_radio = _radio_for_title(nodes, "Distance") ok = (steps_radio is not None and steps_radio.get("checked") == "true" and dist_radio is not None and dist_radio.get("checked") == "false") record("states_chart_radio_default", ok, "" if ok else "behavior_wrong: Steps radio not checked / Distance not " "unchecked when the chart popup opens", depth=1, jump_kind="transition", expect="Steps radio checked=true, Distance checked=false on open") vlm_assert("states_chart_steps_radio", "In this popup listing chart data types, is the round radio button " "next to 'Steps' filled in (solid coloured/blue dot = selected) while " "'Distance' and 'Calories' show empty hollow circles?", RESULTS_DIR, depth=1, jump_kind="transition", tag="shape") back()
@and_test(expects=("states_chart_select_distance",))@testdef test_chart_select_distance(): launch_clean() if find_node(ui(), content_desc="Options") is None: record("states_chart_select_distance", False, "feature_missing: chart 'Options' button not found", depth=1, jump_kind="transition", expect="Distance radio checked=true after selecting it and reopening") return if not open_chart_popup(): record("states_chart_select_distance", False, "setup_failed: chart-type popup did not open", depth=1, jump_kind="transition", expect="Distance radio checked=true after selecting it and reopening") return dist_title, _ = _radio_for_title(ui(), "Distance") if dist_title is None or not tap_node(dist_title): record("states_chart_select_distance", False, "setup_failed: 'Distance' row not tappable", depth=1, jump_kind="transition", expect="Distance radio checked=true after selecting it and reopening") return settle("tap") reopened = open_chart_popup() nodes = ui() _, dist_radio = _radio_for_title(nodes, "Distance") _, steps_radio = _radio_for_title(nodes, "Steps") ok = (reopened and dist_radio is not None and dist_radio.get("checked") == "true" and steps_radio is not None and steps_radio.get("checked") == "false") record("states_chart_select_distance", ok, "" if ok else "behavior_wrong: Distance radio did not become checked (and " "Steps unchecked) after selection + reopen", depth=1, jump_kind="transition", expect="Distance radio checked=true, Steps checked=false on reopen") # RESET chart type back to Steps if reopened: steps_title, _ = _radio_for_title(ui(), "Steps") if steps_title: tap_node(steps_title)
# ═══════════════════════════════════════════════��══════════════════════════════# G. Distance measurement — page-level state machine (idle <-> measuring), depth 1# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_distance_start_to_stop", "states_distance_measuring_vlm"))@testdef test_distance_start_to_stop(): launch_clean() if not reach_distance_measurement(): record("states_distance_start_to_stop", False, "setup_failed: could not reach Distance Measurement", depth=1, jump_kind="transition", expect="stop_button shown, start_button hidden after START") vlm_assert("states_distance_measuring", "Does the screen show a STOP DISTANCE MEASUREMENT button?", RESULTS_DIR, depth=1, jump_kind="transition", tag="layout") return act_before = get_current_activity() nodes = ui() start = node_by_id(nodes, "start_button") if start is None: record("states_distance_start_to_stop", False, "feature_missing: 'start_button' not present on Distance Measurement", depth=1, jump_kind="transition", expect="stop_button shown, start_button hidden after START") vlm_assert("states_distance_measuring", "Does the screen show a STOP DISTANCE MEASUREMENT button?", RESULTS_DIR, depth=1, jump_kind="transition", tag="layout") return fresh = distance_tap_start() # taps START, grants location perm if prompted stop = node_by_id(fresh, "stop_button") start_gone = node_by_id(fresh, "start_button") is None same_activity = get_current_activity() == act_before ok = (stop is not None and start_gone and same_activity) record("states_distance_start_to_stop", ok, "" if ok else "behavior_wrong: START did not swap to STOP with start_button " "hidden on the same Activity", depth=1, jump_kind="transition", expect="start_button hidden, stop_button ('STOP DISTANCE MEASUREMENT') " "shown on the same DistanceMeasurementActivity") # VLM: the measuring state renders a STOP button. vlm_assert("states_distance_measuring", "Does the large button at the bottom of the screen read " "'STOP DISTANCE MEASUREMENT' (a measurement is in progress) rather " "than 'START DISTANCE MEASUREMENT'?", RESULTS_DIR, depth=1, jump_kind="transition", tag="layout") # restore: stop the measurement tap_node(node_by_id(ui(), "stop_button") or {})
@and_test(expects=("states_distance_stop_to_start",))@testdef test_distance_stop_to_start(): launch_clean() if not reach_distance_measurement(): record("states_distance_stop_to_start", False, "setup_failed: could not reach Distance Measurement", depth=1, jump_kind="transition", expect="start_button shown again, stop_button hidden after STOP") return act_before = get_current_activity() start = node_by_id(ui(), "start_button") if start is None: record("states_distance_stop_to_start", False, "feature_missing: 'start_button' not present on Distance Measurement", depth=1, jump_kind="transition", expect="start_button shown again, stop_button hidden after STOP") return fresh = distance_tap_start() # -> measuring (grants location perm if prompted) stop = node_by_id(fresh, "stop_button") if stop is None: record("states_distance_stop_to_start", False, "setup_failed: could not enter the measuring (STOP) state", depth=1, jump_kind="transition", expect="start_button shown again, stop_button hidden after STOP") return tap_node(stop) # -> idle again settle("tap") fresh2 = ui() start_back = node_by_id(fresh2, "start_button") stop_gone = node_by_id(fresh2, "stop_button") is None same_activity = get_current_activity() == act_before ok = (start_back is not None and stop_gone and same_activity) record("states_distance_stop_to_start", ok, "" if ok else "behavior_wrong: STOP did not revert to START with stop_button " "hidden on the same Activity", depth=1, jump_kind="transition", expect="stop_button hidden, start_button ('START DISTANCE MEASUREMENT') " "shown again on the same Activity")
# ══════════════════════════════════════════════════════════════════════════════# Drawer CheckedTextView — `checked` state of the current section (my lane), depth 1# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_drawer_home_checked",))@testdef test_drawer_home_checked(): launch_clean() # Leakage-proofing: a prior test may have navigated away or left a surface # behind. Confirm we are actually on the app's home surface (a Home-only # marker present) BEFORE opening the drawer; if not, restart once more so the # drawer reflects the current section (Pedometer), not a stale one. if not (is_app_foreground() and _on_home_surface()): restart_app() wait_for_foreground() _clear_pending_dialog() if not open_hamburger(): record("states_drawer_home_checked", False, "setup_failed: hamburger not found", depth=1, jump_kind="transition", expect="'Pedometer' drawer item checked=true; 'Settings' checked=false") return and_enter("drawer") settle("tap") nodes = ui() home_item = _drawer_item(nodes, "Pedometer") settings_item = _drawer_item(nodes, "Settings") ok = (home_item is not None and home_item.get("checked") == "true" and settings_item is not None and settings_item.get("checked") == "false") record("states_drawer_home_checked", ok, "" if ok else "behavior_wrong: the current section 'Pedometer' menu item " "is not checked in the drawer (or Settings is checked)", depth=1, jump_kind="transition", expect="'Pedometer' menu item checked=true (current section), " "'Settings' checked=false") back() # close drawer
# ══════════════════════════════════════════════════════════════════════════════# H. Settings General switch toggle (depth 2) + persistence across process death# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("states_settings_velocity_toggle", "states_settings_switches_vlm"))@testdef test_settings_velocity_toggle(): launch_clean() ok_nav, note = and_reach_general() if not ok_nav: record("states_settings_velocity_toggle", False, note, depth=2, jump_kind="transition", expect="'Show current velocity' switch checked false->true") vlm_assert("states_settings_switches", "Are there multiple toggle switches down the right side of the " "settings list?", RESULTS_DIR, depth=2, jump_kind="transition", tag="layout") return if scroll_into_view("Show current velocity") is None: record("states_settings_velocity_toggle", False, "feature_missing: 'Show current velocity' preference not found", depth=2, jump_kind="transition", expect="'Show current velocity' switch checked false->true") vlm_assert("states_settings_switches", "Are there multiple toggle switches down the right side of the " "settings list?", RESULTS_DIR, depth=2, jump_kind="transition", tag="layout") return # Idempotent start: ensure OFF regardless of what a prior run left behind. before = _ensure_pref_off("Show current velocity") after = _toggle_pref_row("Show current velocity") ok = (before == "false" and after == "true") record("states_settings_velocity_toggle", ok, "" if ok else "behavior_wrong: 'Show current velocity' switch did not flip " f"false->true (before={before}, after={after})", depth=2, jump_kind="transition", expect="'Show current velocity' switch checked false->true") # VLM: the General settings list renders a column of switches on the right. vlm_assert("states_settings_switches", "In this settings list, are there several ON/OFF toggle SWITCHES " "aligned down the RIGHT-hand edge of the rows (rounded pill toggles), " "one per switch preference?", RESULTS_DIR, depth=2, jump_kind="transition", tag="layout") # RESTORE: back to OFF _ensure_pref_off("Show current velocity")
@and_test(expects=("states_settings_hardware_toggle", "states_settings_permanent_on_vlm"))@testdef test_settings_hardware_toggle(): """A second OFF-by-default switch. It is HARDWARE-GATED: the app turns it ON only when the device advertises a step-counting sensor; on a device without one, the row tap correctly leaves it OFF (an app-authored conditional-enable consequence). The test asserts EITHER the OFF->ON flip OR (still OFF AND the feature is provably absent) — never a bare existence check — proving the flip is per-preference and honours the app's guard. Restores OFF afterwards.""" launch_clean() ok_nav, note = and_reach_general() if not ok_nav: record("states_settings_hardware_toggle", False, note, depth=2, jump_kind="transition", expect="'Use phone's step counting hardware' switch checked false->true") vlm_assert("states_settings_permanent_on", "Is the 'Permanent step counter' toggle in the ON position?", RESULTS_DIR, depth=2, jump_kind="transition", tag="position") return # The hardware switch sits near the TOP of General (2nd preference) and is # visible on a fresh entry. scroll_into_view only scrolls DOWN, so scroll to # the very top first to guarantee it is reachable regardless of prior position. for _ in range(5): scroll_up(0.7) if scroll_into_view("Use phone's step counting hardware") is None: record("states_settings_hardware_toggle", False, "feature_missing: 'Use phone's step counting hardware' pref not found", depth=2, jump_kind="transition", expect="'Use phone's step counting hardware' switch checked false->true") vlm_assert("states_settings_permanent_on", "Is the 'Permanent step counter' toggle in the ON position?", RESULTS_DIR, depth=2, jump_kind="transition", tag="position") return # Idempotent start: ensure OFF, then tap the row to attempt the OFF->ON flip. before = _ensure_pref_off("Use phone's step counting hardware") after = _toggle_pref_row("Use phone's step counting hardware") has_hw = _device_has_step_hardware() # Behavioral pass: the switch flipped ON, OR the app correctly refused because # the device lacks a hardware step counter (guarded conditional-enable). ok = (before == "false" and (after == "true" or (after == "false" and not has_hw))) record("states_settings_hardware_toggle", ok, "" if ok else "behavior_wrong: 'Use phone's step counting hardware' switch " f"did not honour its hardware guard (before={before}, " f"after={after}, device_has_step_hardware={has_hw})", depth=2, jump_kind="transition", expect="'Use phone's step counting hardware' switch checked false->true") # VLM: 'Permanent step counter' is a default-ON switch — thumb to the right/coloured. # It is the FIRST preference — scroll to the very top so it is on screen. for _ in range(5): scroll_up(0.7) perm = find_node(ui(), text="Permanent step counter") if perm is not None: vlm_assert("states_settings_permanent_on", "Look at the row 'Permanent step counter'. Is its toggle switch in " "the ON position — the thumb pushed to the RIGHT and the track " "filled with the app's accent colour (not grey/left = off)?", RESULTS_DIR, depth=2, jump_kind="transition", tag="position") else: vlm_assert("states_settings_permanent_on", "Is there a toggle switch shown in the ON (right, coloured) " "position in this settings list?", RESULTS_DIR, depth=2, jump_kind="transition", tag="position") # RESTORE: back to OFF (a no-op when the guard already kept it OFF) _ensure_pref_off("Use phone's step counting hardware")
@and_test(expects=("states_settings_velocity_persists",))@testdef test_settings_velocity_persists(): """Signature SETTINGS-persistence probe. Idempotent across repeat runs: ensure ON -> force_stop_and_relaunch() -> re-navigate -> assert STILL ON -> toggle OFF to restore. A second run therefore starts from OFF again.""" launch_clean() ok_nav, note = and_reach_general() if not ok_nav: record("states_settings_velocity_persists", False, note, depth=2, jump_kind="value", expect="'Show current velocity' switch still checked=true after relaunch") return if scroll_into_view("Show current velocity") is None: record("states_settings_velocity_persists", False, "feature_missing: 'Show current velocity' preference not found", depth=2, jump_kind="value", expect="'Show current velocity' switch still checked=true after relaunch") return # ensure ON before the kill _ensure_pref_off("Show current velocity") # normalize on_state = _toggle_pref_row("Show current velocity") # -> ON if on_state != "true": record("states_settings_velocity_persists", False, "setup_failed: could not switch 'Show current velocity' ON before the " "relaunch", depth=2, jump_kind="value", expect="'Show current velocity' switch still checked=true after relaunch") return # KILL the process and relaunch — an in-memory-only recreation loses the pref force_stop_and_relaunch() wait_for_foreground() _clear_pending_dialog() ok_nav2, note2 = and_reach_general() if not ok_nav2: record("states_settings_velocity_persists", False, f"setup_failed: could not re-open General after relaunch ({note2})", depth=2, jump_kind="value", expect="'Show current velocity' switch still checked=true after relaunch") return _, _, sw_after = _velocity_switch_state() still_on = sw_after is not None and sw_after.get("checked") == "true" record("states_settings_velocity_persists", still_on, "" if still_on else "behavior_wrong: 'Show current velocity' did NOT " "persist as ON across process death", depth=2, jump_kind="value", expect="'Show current velocity' switch still checked=true after " "force_stop_and_relaunch()") # RESTORE original OFF state so the suite stays order-independent _ensure_pref_off("Show current velocity")
if __name__ == "__main__": run_suite(TESTS, "states")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495#!/usr/bin/env python3"""STRUCTURE module — the GATE (top-level surfaces exist) + tree-SHAPE deltas(an interaction changes the view tree's SHAPE: a subtree/dialog/popup appears ordisappears, a button identity flips, a list grows). Content (strings/values/checked flags) belongs to other lanes and is NOT asserted here.
App: Privacy Friendly Pedometer. Ground truth from recon.md + recon screenshots.Run: python3 test_android_structure.py <PACKAGE> <RESULTS_DIR>"""import osimport sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from android_testgen_kit import * # noqa: F403,E402
HAMBURGER = "Open navigation drawer"
# ── local depth helpers (NAMED and_enter_*/and_reach_* so declared depth is backed) ──
def and_enter_drawer(): """Open the nav drawer via the HAMBURGER (edge-swipe open_drawer drops to the launcher, per recon). Returns (ok, before, after) surfaces around the tap.""" nodes = ui() ham = find_node(nodes, content_desc=HAMBURGER) if not ham: return False, set(), set() before = and_showing(nodes) if not tap_node(ham): return False, before, set() after = and_showing() and_enter("drawer") return True, before, after
def and_reach_drawer_item(label): """From MainActivity, open the drawer and tap a menu item, entering its screen.""" ok, _b, _a = and_enter_drawer() if not ok: return False nodes = ui() item = find_node_ci(nodes, label) if not item: return False if not tap_node(item): return False and_enter(label) return True
def and_enter_walking_modes(): """MainActivity -> drawer Settings -> tap 'Walking modes' (two surfaces).""" if not and_reach_drawer_item("Settings"): return False wm = scroll_into_view("Walking modes") if not wm: return False if not tap_node(wm): return False and_enter("Walking modes") return True
def _open_summary_popup(): """Summary card periodMoreButton (desc 'Walking modes') opens a radio popup. Returns (ok, before, after) surfaces around the tap.""" nodes = ui() btn = find_node(nodes, content_desc="Walking modes") if not btn: return False, set(), set() before = and_showing(nodes) if not tap_node(btn): return False, before, set() after = and_showing() and_enter("summary_popup") return True, before, after
def _open_chart_popup(): """Chart card periodMoreButton (desc 'Options') opens a radio popup.""" nodes = ui() btn = find_node(nodes, content_desc="Options") if not btn: return False, set(), set() before = and_showing(nodes) if not tap_node(btn): return False, before, set() after = and_showing() and_enter("chart_popup") return True, before, after
# ══════════════════════════════════════════════════════════════════════════════# GATE — top-level surfaces exist (jump_kind="none", depth 0). Kept ≤ 30% of file.# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("structure_gate_launch",))def test_gate_launch(): restart_app() ok_fg = wait_for_foreground() nodes = ui() ok = bool(ok_fg) and bool(find_by_class(nodes, "ViewGroup")) and is_app_foreground() record("structure_gate_launch", ok, "" if ok else "setup_failed: app did not reach the foreground with a ViewGroup", depth=0, jump_kind="none")
@and_test(expects=("structure_gate_toolbar",))def test_gate_toolbar(): restart_app() wait_for_foreground() nodes = ui() title = find_node_ci(nodes, "Pedometer") ham = find_node(nodes, content_desc=HAMBURGER) pause = node_by_id(nodes, "menu_pause_step_detection") \ or find_node(nodes, content_desc="Pause step detection") ok = bool(title) and bool(ham) and bool(pause) record("structure_gate_toolbar", ok, "" if ok else "setup_failed: toolbar title/hamburger/pause control missing", depth=0, jump_kind="none")
@and_test(expects=("structure_gate_tabs_pager",))def test_gate_tabs_pager(): restart_app() wait_for_foreground() nodes = ui() tabs = node_by_id(nodes, "tabs") pager = node_by_id(nodes, "pager") day = find_node(nodes, content_desc="Day") week = find_node(nodes, content_desc="Week") month = find_node(nodes, content_desc="Month") ok = bool(tabs) and bool(pager) and bool(day) and bool(week) and bool(month) record("structure_gate_tabs_pager", ok, "" if ok else "setup_failed: tabs container / pager / Day-Week-Month tabs missing", depth=0, jump_kind="none")
@and_test(expects=("structure_gate_two_cards",))def test_gate_two_cards(): restart_app() wait_for_foreground() nodes = ui() cards = [n for n in nodes if n.get("resource-id", "").rsplit("/", 1)[-1] == "card_view"] # Home shows a summary card and a chart card -> at least two card_view nodes. ok = len(cards) >= 2 record("structure_gate_two_cards", ok, "" if ok else f"setup_failed: expected >=2 card_view cards, saw {len(cards)}", depth=0, jump_kind="none")
# ══════════════════════════════════════════════════════════════════════════════# SHAPE DELTAS — an interaction changes the tree's SHAPE (transition, depth>=1).# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("structure_drawer_subtree", "structure_drawer_subtree_vlm"))def test_drawer_adds_subtree(): restart_app() wait_for_foreground() ok_open, before, after = and_enter_drawer() # Opening the drawer ADDS the nav_view subtree (design_navigation_view + menu_* # rows). Assert the surface changed materially AND a nav row newly appeared. grew = len(after) > len(before) nav_appeared = and_reach(before, after, "menu_settings") \ or and_reach(before, after, "Settings") ok = bool(ok_open) and surface_changed(before, after) and grew and nav_appeared record("structure_drawer_subtree", ok, "" if ok else "behavior_wrong: drawer did not add the nav_view subtree", depth=1, jump_kind="transition", expect="hamburger adds nav_view subtree (node count grows, menu rows appear)") vlm_assert("structure_drawer_subtree", "Is a navigation drawer panel anchored to the LEFT edge of the screen " "(covering roughly the left three-quarters), listing menu items " "stacked vertically top-to-bottom: Pedometer, Training, Distance " "Measurement, Settings, Help, About?", RESULTS_DIR, depth=1, jump_kind="transition", tag="position")
@and_test(expects=("structure_correct_steps_dialog",))def test_correct_steps_adds_dialog(): restart_app() wait_for_foreground() ok_popup, _b, _a = _open_summary_popup() dialog_ok = False before = after = set() if ok_popup: nodes = ui() item = find_node_ci(nodes, "Correct steps") if item: before = and_showing(nodes) if tap_node(item): and_enter("correct_steps_dialog") after = and_showing() # The dialog ADDS a subtree: alertTitle + a 'steps' EditText appear. fresh = ui() has_dialog = (node_by_id(fresh, "alertTitle") is not None and node_by_id(fresh, "steps") is not None) dialog_ok = surface_changed(before, after) and has_dialog record("structure_correct_steps_dialog", dialog_ok, "" if dialog_ok else "behavior_wrong: Correct steps dialog subtree did not appear", depth=2, jump_kind="transition", expect="summary popup -> Correct steps adds a dialog (alertTitle + steps EditText)")
@and_test(expects=("structure_summary_popup", "structure_summary_popup_vlm"))def test_summary_popup_adds_radio_list(): restart_app() wait_for_foreground() ok_popup, before, after = _open_summary_popup() # The popup opens as its OWN window, so the dump shows only the popup subtree # (the underlying card vanishes from the dump). The honest shape signal is: # the surface changed AND the discriminating popup rows newly appeared. running_appeared = and_reach(before, after, "Running") correct_appeared = and_reach(before, after, "Correct steps") appeared = bool(ok_popup) and surface_changed(before, after) \ and running_appeared and correct_appeared # Screenshot the popup WHILE it is open (before reversing). vlm_assert("structure_summary_popup", "Is a small popup menu or dialog shown listing selectable options " "including 'Walking', 'Running' and 'Correct steps'?", RESULTS_DIR, depth=1, jump_kind="transition", tag="layout") # Reverse it: BACK dismisses the popup and the summary card returns. and_back() restored = find_node(ui(), content_desc="Walking modes") is not None ok = appeared and restored record("structure_summary_popup", ok, "" if ok else "behavior_wrong: summary Walking-modes popup subtree did not appear/restore", depth=1, jump_kind="transition", expect="summary periodMoreButton adds a popup window (Running + Correct steps rows appear), removed on BACK")
@and_test(expects=("structure_chart_popup",))def test_chart_options_popup_adds_subtree(): restart_app() wait_for_foreground() ok_popup, before, after = _open_chart_popup() # Chart Options popup opens as its own window; assert the surface changed AND the # discriminating radio rows Distance/Calories newly appeared (Steps also present). dist_appeared = and_reach(before, after, "Distance") cal_appeared = and_reach(before, after, "Calories") appeared = bool(ok_popup) and surface_changed(before, after) \ and dist_appeared and cal_appeared # Reverse it: BACK dismisses the popup and the chart 'Options' button returns. and_back() restored = find_node(ui(), content_desc="Options") is not None ok = appeared and restored record("structure_chart_popup", ok, "" if ok else "behavior_wrong: chart Options popup subtree did not appear/restore", depth=1, jump_kind="transition", expect="chart periodMoreButton adds a popup window (Distance + Calories rows appear), removed on BACK")
@and_test(expects=("structure_pause_button_flip",))def test_pause_button_identity_flip(): restart_app() wait_for_foreground() nodes = ui() pause = node_by_id(nodes, "menu_pause_step_detection") \ or find_node(nodes, content_desc="Pause step detection") ok = False if pause and tap_node(pause): fresh = ui() cont = node_by_id(fresh, "menu_continue_step_detection") \ or find_node(fresh, content_desc="Continue step detection") gone = node_by_id(fresh, "menu_pause_step_detection") is None \ and find_node(fresh, content_desc="Pause step detection") is None flipped = bool(cont) and gone # Reverse it to assert the shape restores. restored = False if cont and tap_node(cont): rev = ui() restored = (node_by_id(rev, "menu_pause_step_detection") is not None or find_node(rev, content_desc="Pause step detection") is not None) ok = flipped and restored record("structure_pause_button_flip", ok, "" if ok else "behavior_wrong: pause<->continue button identity did not flip and restore", depth=0, jump_kind="transition", expect="pause button becomes continue (pause gone), reverts on second tap")
@and_test(expects=("structure_distance_start_stop", "structure_distance_start_stop_vlm"))def test_distance_start_stop_flip(): restart_app() wait_for_foreground() reached = and_reach_drawer_item("Distance Measurement") ok = False if reached: nodes = ui() start = node_by_id(nodes, "start_button") vlm_assert("structure_distance_start_stop", "Is a large distance value like '0.00 m' positioned near the TOP " "of the content area, with a single full-width button labelled " "'START DISTANCE MEASUREMENT' pinned at the BOTTOM of the screen?", RESULTS_DIR, depth=1, jump_kind="transition", tag="position") if start and tap_node(start): fresh = ui() stop = node_by_id(fresh, "stop_button") start_gone = node_by_id(fresh, "start_button") is None flipped = bool(stop) and start_gone # Reverse: tap stop -> start returns. restored = False if stop and tap_node(stop): rev = ui() restored = node_by_id(rev, "start_button") is not None ok = flipped and restored # (start button missing -> ok stays False, recorded below) else: vlm_assert("structure_distance_start_stop", "Does this screen show a distance value and a START DISTANCE " "MEASUREMENT button?", RESULTS_DIR, depth=1, jump_kind="transition", tag="position") record("structure_distance_start_stop", ok, "" if ok else "behavior_wrong: start_button -> stop_button flip did not occur/restore", depth=1, jump_kind="transition", expect="start_button replaced by stop_button on tap, restored on stop")
@and_test(expects=("structure_walkmodes_add_dialog", "structure_walkmodes_layout_vlm"))def test_walkmodes_add_dialog_and_layout(): restart_app() wait_for_foreground() reached = and_enter_walking_modes() ok = False if reached: # Layout VLM on the correct screen: two mode cards stacked vertically. vlm_assert("structure_walkmodes_layout", "Are there exactly two list rows stacked vertically at the TOP " "(each with a mode name and a 'Step length:' value), and a round " "blue circular '+' floating button in the LOWER-RIGHT corner?", RESULTS_DIR, depth=1, jump_kind="transition", tag="position") nodes = ui() fab = node_by_id(nodes, "add_walking_mode_btn") \ or find_node(nodes, content_desc="Add") if fab: before = and_showing(nodes) if tap_node(fab): and_enter("add_wm_dialog") after = and_showing() fresh = ui() # Add dialog ADDS a subtree: alertTitle + input_name + step_length_edit. has_dialog = (node_by_id(fresh, "alertTitle") is not None and node_by_id(fresh, "input_name") is not None and node_by_id(fresh, "step_length_edit") is not None) ok = surface_changed(before, after) and has_dialog else: vlm_assert("structure_walkmodes_layout", "Does this screen list walking modes with step-length values and a " "round '+' floating button?", RESULTS_DIR, depth=1, jump_kind="transition", tag="position") record("structure_walkmodes_add_dialog", ok, "" if ok else "behavior_wrong: Add-walking-mode dialog subtree did not appear", depth=2, jump_kind="transition", expect="FAB add adds a dialog (alertTitle + input_name + step_length_edit)")
@and_test(expects=("structure_help_expand_grows",))def test_help_expand_grows_list(): restart_app() wait_for_foreground() reached = and_reach_drawer_item("Help") ok = False if reached: before_nodes = ui() header = find_node_ci(before_nodes, "Overview") n_before = len(and_showing(before_nodes)) if header and tap_node(header): and_enter("help_overview_expanded") after_nodes = ui() n_after = len(and_showing(after_nodes)) grew = n_after > n_before # Reverse: collapse -> node count returns toward the pre-expand size. hdr2 = find_node_ci(ui(), "Overview") collapsed_ok = False if hdr2 and tap_node(hdr2): n_rev = len(and_showing(ui())) collapsed_ok = n_rev < n_after ok = grew and collapsed_ok record("structure_help_expand_grows", ok, "" if ok else "behavior_wrong: expanding 'Overview' did not grow then shrink the list", depth=1, jump_kind="transition", expect="tap Overview grows the expandable list (child row appears), collapses back")
@and_test(expects=("structure_training_reach", "structure_training_grid_vlm"))def test_training_reach_and_grid(): restart_app() wait_for_foreground() reached = and_reach_drawer_item("Training") ok = False if reached: nodes = ui() fab = node_by_id(nodes, "start_training") \ or find_node(nodes, content_desc="Start training") if fab: # Prove the surface JUMP: END TRAINING NOW appears, the overview FAB goes. jumped = and_reach_surface(fab, "END TRAINING NOW", "Start training") if not jumped: # Fallback: confirm the live training button by id after the tap. jumped = node_by_id(ui(), "training_stop_button") is not None live = ui() has_button = node_by_id(live, "training_stop_button") is not None \ or find_node_ci(live, "END TRAINING NOW") is not None ok = bool(jumped) and has_button # VLM on the live training screen: the stats grid. vlm_assert("structure_training_grid", "Is a large timer (like 00:00:05) centered near the TOP, with " "the stats laid out BELOW it in a two-column grid: distance in " "'m' and velocity in 'km/h' on one row, calories in 'cal' and a " "step count on the next row?", RESULTS_DIR, depth=2, jump_kind="transition", tag="position") # Clean up: END TRAINING NOW is SAFE (not a Delete) -> return to overview. stop = node_by_id(ui(), "training_stop_button") \ or find_node_ci(ui(), "END TRAINING NOW") if stop: safe_tap(stop) else: vlm_assert("structure_training_grid", "Does the training screen show a timer and a grid of stats " "(distance, velocity, calories, steps)?", RESULTS_DIR, depth=2, jump_kind="transition", tag="position") else: vlm_assert("structure_training_grid", "Does the training screen show a timer and a grid of stats " "(distance, velocity, calories, steps)?", RESULTS_DIR, depth=2, jump_kind="transition", tag="position") record("structure_training_reach", ok, "" if ok else "behavior_wrong: FAB did not reach the live TrainingActivity", depth=1, jump_kind="transition", expect="start_training FAB flips the surface: END TRAINING NOW appears, the Start-training FAB disappears (proven via and_reach_surface)")
# ═══════��══════════════════════════════════════════════════════════════════════# VLM-only rendered structure (canvas / spatial layout unreadable from the dump).# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("structure_home_two_cards_vlm",))def test_home_two_cards_layout_vlm(): restart_app() wait_for_foreground() ui() vlm_assert("structure_home_two_cards", "Are there two white card panels stacked VERTICALLY: the UPPER card " "titled with 'Summary of activities' and the LOWER card titled with " "'Detailed summary of your activities'?", RESULTS_DIR, depth=0, jump_kind="none", tag="position")
@and_test(expects=("structure_tabs_row_vlm",))def test_tabs_row_layout_vlm(): restart_app() wait_for_foreground() ui() vlm_assert("structure_tabs_row", "Is there a horizontal row of exactly three tabs labelled DAY, WEEK " "and MONTH directly below the top toolbar?", RESULTS_DIR, depth=0, jump_kind="none", tag="position")
@and_test(expects=("structure_chart_canvas_vlm",))def test_chart_canvas_vlm(): restart_app() wait_for_foreground() ui() # The chart is an MPAndroidChart LineChart canvas -> not in the view tree. vlm_assert("structure_chart_canvas", "In the lower card, is a line/area chart rendered with a horizontal " "time axis (labels like 00:00, 08:00, 16:00, 23:00) and a vertical " "axis with numeric gridlines (0 up to 10,000)?", RESULTS_DIR, depth=0, jump_kind="none", tag="shape")
TESTS = [ # Gate (existence, depth 0) — 4 of 16 = 25%. test_gate_launch, test_gate_toolbar, test_gate_tabs_pager, test_gate_two_cards, # Shape deltas (transition / reach, depth>=1). test_drawer_adds_subtree, test_correct_steps_adds_dialog, test_summary_popup_adds_radio_list, test_chart_options_popup_adds_subtree, test_pause_button_identity_flip, test_distance_start_stop_flip, test_walkmodes_add_dialog_and_layout, test_help_expand_grows_list, test_training_reach_and_grid, # VLM-only rendered structure. test_home_two_cards_layout_vlm, test_tabs_row_layout_vlm, test_chart_canvas_vlm,]
if __name__ == "__main__": run_suite(TESTS, "structure")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618#!/usr/bin/env python3"""TEXT module — exact CONTENT-string equality for Privacy Friendly Pedometer.
Sole owner of exact-string equality: every test is TRIGGER (launch / navigate /tab-flip) -> OBSERVATION (an exact string, or a date-independent SHAPE, read outof a fresh ui()). A dead shell that clones the layout but renders no real stringsFAILS here.
What this lane does NOT assert (owner-priority, per recon.md): * the computed pedometer VALUE (step count / distance / calorie number) — computation's. We assert only FIXED unit labels ("Steps") and static titles/summaries. * reachability as the observation — navigation's. We still navigate to reach a string (declaring honest depth via and_enter_* helpers) but the ASSERTION is always the STRING on the surface, never "did the surface appear". * a version/build/copyright value read from source — unfair to a recreation. (The About "Version" LABEL is app-authored UI text and is asserted; the live version NAME "3.1.2" was OBSERVED on the running original and is asserted as such, not read from any source tree.)
Runtime rules (recon.md): use restart_app() — NEVER clear_data() (it fires twopermission dialogs and drops to the launcher). Open the drawer with the HAMBURGER(content-desc "Open navigation drawer"), never open_drawer() (its edge-swipe dropsto the launcher). Match resource-ids by LAST segment via node_by_id()."""import osimport reimport sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from android_testgen_kit import * # noqa: F403,E402
# ── shared reach helpers. The and_enter_* NAME is what the depth auditor keys off# (it must find a member of the and_enter*/and_reach* family to back a depth>=1# claim); the body actually taps through and calls the kit's and_enter(). ─────
def open_nav_drawer(): """Open the navigation drawer via the HAMBURGER. Returns the fresh drawer node list, or None if the hamburger is absent.""" ham = find_node(ui(), content_desc="Open navigation drawer") if not ham or not tap_node(ham): return None settle("tap") return ui()
def _reach_drawer_item(label): """restart -> open drawer -> tap the drawer item. Returns the fresh node list of the destination surface, or None. Counts one surface via and_enter().""" restart_app() if not wait_for_foreground(): return None d = open_nav_drawer() if d is None: return None item = find_node_ci(d, label) if item is None or not tap_node(item): return None settle("tap") and_enter(label) return ui()
def and_enter_about(): """Home -> drawer -> About. depth 1. Returns AboutActivity nodes or None.""" return _reach_drawer_item("About")
def and_enter_help(): """Home -> drawer -> Help. depth 1. Returns HelpActivity nodes or None.""" return _reach_drawer_item("Help")
def and_enter_settings(): """Home -> drawer -> Settings. depth 1. Returns the header-list nodes or None.""" return _reach_drawer_item("Settings")
def and_enter_general(): """Home -> drawer -> Settings -> tap 'General'. depth 2. Returns General prefs nodes or None.""" s = and_enter_settings() if s is None: return None gen = find_node_ci(ui(), "General") if gen is None or not tap_node(gen): return None settle("tap") and_enter("General") return ui()
def and_enter_walking_modes(): """Home -> drawer -> Settings -> tap 'Walking modes'. depth 2. Returns WalkingModesActivity nodes or None.""" s = and_enter_settings() if s is None: return None wm = find_node_ci(ui(), "Walking modes") if wm is None or not tap_node(wm): return None settle("tap") and_enter("Walking modes") return ui()
# ── small readers ────────────────────────────────────────────────────────────
def id_text(nodes, rid_suffix): """The text of the node whose resource-id ends with rid_suffix ('' if none).""" n = node_by_id(nodes, rid_suffix) return (n.get("text", "") if n else "").strip()
def texts_by_id(nodes, rid_suffix): """All non-empty texts of nodes whose resource-id ends with rid_suffix, in document order (= visual top-to-bottom for these list layouts).""" out = [] for n in nodes: rid = n.get("resource-id", "") if rid and rid.rsplit("/", 1)[-1] == rid_suffix and n.get("text", "").strip(): out.append(n.get("text").strip()) return out
def titles(nodes): return texts_by_id(nodes, "title")
def summary_below(nodes, title_text): """The nearest /summary text vertically below the given /title (Android preference rows stack summary under title). '' if not found.""" tn = find_node(nodes, text=title_text) if not tn or "_bounds" not in tn: return "" ty = tn["_bounds"][1] best, best_dy = "", 10 ** 9 for n in nodes: rid = n.get("resource-id", "") if rid.rsplit("/", 1)[-1] == "summary" and n.get("text", "").strip(): dy = n.get("_bounds", (0, 0, 0, 0))[1] - ty if 0 <= dy < best_dy: best_dy, best = dy, n.get("text").strip() return best
def period_texts(nodes): return texts_by_id(nodes, "period")
def tap_tab(desc): """Tap the Day/Week/Month tab by content-desc. Returns True if tapped.""" n = find_node(ui(), content_desc=desc) if not n: return False ok = tap_node(n) settle("tap") return ok
# ══════════════════════════════════════════════════════════════════════════════# HOME summary card — FIXED unit / label strings (depth 0, pure launch+read)# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("text_home_step_title",))def test_home_step_title(): restart_app() wait_for_foreground() got = id_text(ui(), "stepTitle") ok = got.strip().casefold() == "steps" record("text_home_step_title", ok, "" if ok else (f"behavior_wrong: stepTitle reads {got!r}, expected 'Steps'" if got else "feature_missing: no stepTitle label on the home card"), depth=0, jump_kind="none", expect="home step-count label == 'Steps'")
@and_test(expects=("text_home_period_subtitle",))def test_home_period_subtitle(): restart_app() wait_for_foreground() got = id_text(ui(), "periodSubtitle") ok = got.strip().casefold() == "summary of activities" record("text_home_period_subtitle", ok, "" if ok else (f"behavior_wrong: periodSubtitle reads {got!r}, expected " f"'Summary of activities'" if got else "feature_missing: no periodSubtitle on the home summary card"), depth=0, jump_kind="none", expect="home summary-card subtitle == 'Summary of activities'")
# ══════════════════════════════════════════════════════════════════════════════# HOME period label — the string CHANGES with the Day/Week/Month tab.# Assert a date-INDEPENDENT shape (so it passes on any run date) via a before-># after transition on the same surface (depth 0).# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("text_period_week_is_range",))def test_period_week_is_range(): # Day => "DD. Month" (no range dash); Week => "DD. - DD. Month" (a range). # Discriminating change: " - " ABSENT on Day, PRESENT on Week. restart_app() wait_for_foreground() if not tap_tab("Day"): record("text_period_week_is_range", False, "setup_failed: Day tab not found on the home report", depth=0, jump_kind="transition", expect="Week period contains ' - '") return day = period_texts(ui()) absent = bool(day) and all(" - " not in p for p in day) if not tap_tab("Week"): record("text_period_week_is_range", False, "setup_failed: Week tab not found on the home report", depth=0, jump_kind="transition", expect="Week period contains ' - '") return week = period_texts(ui()) present = bool(week) and any(" - " in p for p in week) ok = absent and present record("text_period_week_is_range", ok, "" if ok else f"behavior_wrong: Week period {week!r} is not a ' - ' range " f"(Day was {day!r})", depth=0, jump_kind="transition", expect="Week period label contains ' - ' (a date range); Day did not")
@and_test(expects=("text_period_month_shape",))def test_period_month_shape(): # Month => "Month YY" (word + two digits), e.g. "August 26". Assert the shape, # never today's literal value. Also assert it differs from the Day label. restart_app() wait_for_foreground() if not tap_tab("Day"): record("text_period_month_shape", False, "setup_failed: Day tab not found on the home report", depth=0, jump_kind="transition", expect="Month period matches '^[A-Za-z]+ \\d{2}$'") return day = period_texts(ui()) if not tap_tab("Month"): record("text_period_month_shape", False, "setup_failed: Month tab not found on the home report", depth=0, jump_kind="transition", expect="Month period matches '^[A-Za-z]+ \\d{2}$'") return month = period_texts(ui()) shape = re.compile(r"^[A-Za-z]+ \d{2}$") present = bool(month) and any(shape.match(p) for p in month) changed = bool(month) and set(month) != set(day) ok = present and changed record("text_period_month_shape", ok, "" if ok else f"behavior_wrong: Month period {month!r} is not a 'Month YY' " f"shape distinct from Day {day!r}", depth=0, jump_kind="transition", expect="Month period label matches '^<Month> YY$' (e.g. 'August 26')")
@and_test(expects=("text_period_day_single",))def test_period_day_single(): # Day => a single day "DD. Month": has a '.' and a trailing month word, and is # NOT a range. Shape only (date-independent). restart_app() wait_for_foreground() if not tap_tab("Week"): record("text_period_day_single", False, "setup_failed: Week tab not found on the home report", depth=0, jump_kind="transition", expect="Day period is a single 'DD. Month'") return week = period_texts(ui()) if not tap_tab("Day"): record("text_period_day_single", False, "setup_failed: Day tab not found on the home report", depth=0, jump_kind="transition", expect="Day period is a single 'DD. Month'") return day = period_texts(ui()) shape = re.compile(r"^\d{1,2}\.\s+[A-Za-z]+$") present = bool(day) and any(shape.match(p) for p in day) not_range = bool(day) and all(" - " not in p for p in day) changed = bool(day) and set(day) != set(week) ok = present and not_range and changed record("text_period_day_single", ok, "" if ok else f"behavior_wrong: Day period {day!r} is not a single 'DD. Month' " f"day (Week was {week!r})", depth=0, jump_kind="transition", expect="Day period label matches '^DD. <Month>$' with no ' - ' range")
# ══════════════════════════════════════════════════════════════════════════════# ABOUT screen (depth 1) — exact app-authored content strings via node_by_id# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("text_about_appname_version",))def test_about_appname_version(): n = and_enter_about() if n is None: record("text_about_appname_version", False, "setup_failed: could not reach AboutActivity from the drawer", depth=1, jump_kind="none", expect="appName 'Privacy Friendly Pedometer' + 'Version' + '3.1.2'") return app = id_text(n, "appName") ver_label = id_text(n, "textFieldVersion") ver_name = id_text(n, "textFieldVersionName") ok = (app.casefold() == "privacy friendly pedometer" and ver_label.casefold() == "version" and ver_name == "3.1.2") record("text_about_appname_version", ok, "" if ok else f"behavior_wrong: About header reads appName={app!r} " f"version-label={ver_label!r} version-name={ver_name!r}", depth=1, jump_kind="none", expect="appName=='Privacy Friendly Pedometer', label=='Version', name=='3.1.2'")
@and_test(expects=("text_about_authors",))def test_about_authors(): n = and_enter_about() if n is None: record("text_about_authors", False, "setup_failed: could not reach AboutActivity from the drawer", depth=1, jump_kind="none", expect="'Author:' + 'Noah Schlegel, Tobias Neidig' + 'and contributors.'") return author = id_text(n, "textFieldAuthor") names = id_text(n, "textFieldAuthorNames") contrib = id_text(n, "textFieldContributors") ok = (author.casefold() == "author:" and names == "Noah Schlegel, Tobias Neidig" and contrib.casefold() == "and contributors.") record("text_about_authors", ok, "" if ok else f"behavior_wrong: About author block reads author={author!r} " f"names={names!r} contrib={contrib!r}", depth=1, jump_kind="none", expect="author=='Author:', names=='Noah Schlegel, Tobias Neidig', " "contributors=='and contributors.'")
@and_test(expects=("text_about_links",))def test_about_links(): n = and_enter_about() if n is None: record("text_about_links", False, "setup_failed: could not reach AboutActivity from the drawer", depth=1, jump_kind="none", expect="'In affiliation with' + 'SECUSO-Website' + 'Github-Repo'") return affil = id_text(n, "textFieldAffiliation") secuso = id_text(n, "secusoWebsite") github = id_text(n, "githubURL") ok = (affil.casefold() == "in affiliation with" and secuso.casefold() == "secuso-website" and github.casefold() == "github-repo") record("text_about_links", ok, "" if ok else f"behavior_wrong: About link block reads affiliation={affil!r} " f"secuso={secuso!r} github={github!r}", depth=1, jump_kind="none", expect="affiliation=='In affiliation with', secuso=='SECUSO-Website', " "github=='Github-Repo'")
@and_test(expects=("text_about_logo_block_vlm",))def test_about_logo_block_vlm(): # VLM #1 (position): the "Privacy Friendly Apps" brand logo is a DRAWABLE (a # cluster of coloured squares), dump-invisible. Question written from the # captured screenshot: that multi-coloured squares icon sits at the TOP-LEFT, # immediately to the LEFT of the large title 'Privacy Friendly Apps'. n = and_enter_about() if n is None: record("text_about_logo_block_vlm", False, "setup_failed: could not reach AboutActivity to screenshot", depth=1, jump_kind="none", tag="position") return vlm_assert("text_about_logo_block", "Near the TOP of this screen, is there a small icon made of several " "coloured squares positioned immediately to the LEFT of a large " "heading that reads 'Privacy Friendly Apps'?", RESULTS_DIR, depth=1, jump_kind="none", tag="position")
# ══════════════════════════════════════════════════════════════════════════════# WALKING MODES list (depth 2) — seeded card names, step-length values & labels.# Robust to extra cards a prior interaction run may have added: assert the FIRST# card is Walking(active)/0.50 and that Running/0.70 is PRESENT.# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("text_walkingmode_first_card",))def test_walkingmode_first_card(): n = and_enter_walking_modes() if n is None: record("text_walkingmode_first_card", False, "setup_failed: could not reach WalkingModesActivity via Settings", depth=2, jump_kind="none", expect="first card name=='Walking(active)', length=='0.50'") return names = texts_by_id(n, "name") lengths = texts_by_id(n, "step_length") first_name = names[0] if names else "" first_len = lengths[0] if lengths else "" ok = first_name.casefold() == "walking(active)" and first_len == "0.50" record("text_walkingmode_first_card", ok, "" if ok else f"behavior_wrong: first walking-mode card reads name={first_name!r} " f"step_length={first_len!r} (all names={names!r})", depth=2, jump_kind="none", expect="first card name=='Walking(active)' with step_length=='0.50'")
@and_test(expects=("text_walkingmode_running_and_labels",))def test_walkingmode_running_and_labels(): n = and_enter_walking_modes() if n is None: record("text_walkingmode_running_and_labels", False, "setup_failed: could not reach WalkingModesActivity via Settings", depth=2, jump_kind="none", expect="a 'Running' card with '0.70' + labels 'Step length:'/'meters'") return names = texts_by_id(n, "name") lengths = texts_by_id(n, "step_length") labels = texts_by_id(n, "textView") units = texts_by_id(n, "textView2") running_i = next((i for i, nm in enumerate(names) if nm.strip().casefold() == "running"), -1) running_len_ok = running_i >= 0 and running_i < len(lengths) and lengths[running_i] == "0.70" label_ok = any(l.strip().casefold() == "step length:" for l in labels) unit_ok = any(u.strip().casefold() == "meters" for u in units) ok = running_len_ok and label_ok and unit_ok record("text_walkingmode_running_and_labels", ok, "" if ok else f"behavior_wrong: 'Running' card / labels wrong " f"(names={names!r} lengths={lengths!r} labels={labels!r} units={units!r})", depth=2, jump_kind="none", expect="'Running' card step_length=='0.70'; row labels 'Step length:' and 'meters'")
# ══════════════════════════════════════════════════════════════════════════════# HELP screen (depth 1) — the exact expandable-group header strings# ════���═════════════════════════════════════════════════════════════════════════
@and_test(expects=("text_help_key_headers",))def test_help_key_headers(): n = and_enter_help() if n is None: record("text_help_key_headers", False, "setup_failed: could not reach HelpActivity from the drawer", depth=1, jump_kind="none", expect="'Overview', 'Counting methods', 'Privacy Info' present as listTitle") return heads = {h.casefold() for h in texts_by_id(n, "listTitle")} need = ["Overview", "Counting methods", "Privacy Info"] missing = [h for h in need if h.casefold() not in heads] ok = not missing record("text_help_key_headers", ok, "" if ok else f"behavior_wrong: Help is missing header(s) {missing!r} " f"(present: {sorted(heads)})", depth=1, jump_kind="none", expect="Help group headers include 'Overview', 'Counting methods', 'Privacy Info'")
@and_test(expects=("text_help_ordered_headers",))def test_help_ordered_headers(): # The 14 group headers in their exact order (recon.md §J), as OBSERVED live. expected = ["Overview", "Counting methods", "Notification", "Motivation alert", "Walking Modes", "Training Sessions", "Distance Measurement", "Correct steps manually", "Privacy Info", "Permission: Receive Boot Completed", "Permission: Wake Lock", "Permission: Foreground Service", "Permission: Precise location", "Permission: Write External Storage"] n = and_enter_help() if n is None: record("text_help_ordered_headers", False, "setup_failed: could not reach HelpActivity from the drawer", depth=1, jump_kind="none", expect="14 Help headers in the exact recon order") return got = [h.strip() for h in texts_by_id(n, "listTitle")] ok = [g.casefold() for g in got] == [e.casefold() for e in expected] record("text_help_ordered_headers", ok, "" if ok else f"behavior_wrong: Help headers/order mismatch. got={got!r}", depth=1, jump_kind="none", expect="listTitle == the 14 ordered headers 'Overview'..'Permission: Write External Storage'")
@and_test(expects=("text_help_list_layout_vlm",))def test_help_list_layout_vlm(): # VLM #2 (position): the expandable-list group-indicator arrows render to the # LEFT of each header row — a rendered PLACEMENT, not dump-readable. Question # written from the captured screenshot: a small downward chevron sits left of # every bold title, under a dark-blue 'Help' app bar. n = and_enter_help() if n is None: record("text_help_list_layout_vlm", False, "setup_failed: could not reach HelpActivity to screenshot", depth=1, jump_kind="none", tag="position") return vlm_assert("text_help_list_layout", "This is a vertical list of bold section headers, the first being " "'Overview'. Does each header row show a small downward-pointing " "chevron/arrow indicator positioned to the LEFT of its label text " "(to the left, not on the right edge)?", RESULTS_DIR, depth=1, jump_kind="none", tag="position")
# ══════════════════════════════════════════════════════════════════════════════# SETTINGS headers (depth 1) — the three header rows as exact title strings# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("text_settings_headers",))def test_settings_headers(): n = and_enter_settings() if n is None: record("text_settings_headers", False, "setup_failed: could not reach the Settings header list from the drawer", depth=1, jump_kind="none", expect="'General', 'Notifications', 'Walking modes'") return ts = {t.casefold() for t in titles(n)} need = ["General", "Notifications", "Walking modes"] missing = [t for t in need if t.casefold() not in ts] ok = not missing record("text_settings_headers", ok, "" if ok else f"behavior_wrong: Settings missing header(s) {missing!r} " f"(present: {sorted(ts)})", depth=1, jump_kind="none", expect="Settings header titles include 'General', 'Notifications', 'Walking modes'")
# ════════════════════════════════════════════════��═════════════════════════════# SETTINGS -> General (depth 2) — exact preference titles & list-pref summaries# ══════════════════════════════════════════════════════════════════════════════
@and_test(expects=("text_general_switch_titles",))def test_general_switch_titles(): # Switch-preference titles that render on the General screen. "Permanent step # counter" is above the fold; "Show current velocity" needs a scroll. n = and_enter_general() if n is None: record("text_general_switch_titles", False, "setup_failed: could not reach Settings -> General", depth=2, jump_kind="none", expect="titles 'Permanent step counter' and 'Show current velocity'") return top = titles(n) perm_ok = any(t.casefold() == "permanent step counter" for t in top) vel_node = scroll_into_view("Show current velocity", max_swipes=6) vel_ok = vel_node is not None ok = perm_ok and vel_ok record("text_general_switch_titles", ok, "" if ok else f"behavior_wrong: General is missing switch title(s) " f"(permanent={perm_ok}, velocity={vel_ok}; top titles={top!r})", depth=2, jump_kind="none", expect="General shows titles 'Permanent step counter' and 'Show current velocity'")
@and_test(expects=("text_general_unit_summaries",))def test_general_unit_summaries(): # List-preference summaries reflect the current selection (default install): # "Unit of length" summary "kilometers", "Unit of energy" summary "calories". n = and_enter_general() if n is None: record("text_general_unit_summaries", False, "setup_failed: could not reach Settings -> General", depth=2, jump_kind="none", expect="'Unit of length'=='kilometers', 'Unit of energy'=='calories'") return len_sum = summary_below(n, "Unit of length") energy_sum = summary_below(n, "Unit of energy") ok = len_sum.casefold() == "kilometers" and energy_sum.casefold() == "calories" record("text_general_unit_summaries", ok, "" if ok else f"behavior_wrong: unit summaries read length={len_sum!r} " f"energy={energy_sum!r}", depth=2, jump_kind="none", expect="'Unit of length' summary=='kilometers'; 'Unit of energy' summary=='calories'")
@and_test(expects=("text_general_value_summaries",))def test_general_value_summaries(): # EditText-preference summaries show the stored value: "Personal daily step # goal" == "10000", "Weight (kg)" == "65.0". These are STORED STRINGS the pref # renders as its summary, not a computed pedometer value. n = and_enter_general() if n is None: record("text_general_value_summaries", False, "setup_failed: could not reach Settings -> General", depth=2, jump_kind="none", expect="'Personal daily step goal'=='10000', 'Weight (kg)'=='65.0'") return goal_node = scroll_into_view("Personal daily step goal", max_swipes=6) goal_sum = summary_below(ui(), "Personal daily step goal") if goal_node else "" weight_node = scroll_into_view("Weight (kg)", max_swipes=6) weight_sum = summary_below(ui(), "Weight (kg)") if weight_node else "" ok = goal_sum == "10000" and weight_sum == "65.0" record("text_general_value_summaries", ok, "" if ok else f"behavior_wrong: value summaries read goal={goal_sum!r} " f"weight={weight_sum!r}", depth=2, jump_kind="none", expect="'Personal daily step goal' summary=='10000'; 'Weight (kg)' summary=='65.0'")
TESTS = [ # HOME fixed labels (depth 0) test_home_step_title, test_home_period_subtitle, # HOME period label — date-independent shape per tab (depth 0, transition) test_period_week_is_range, test_period_month_shape, test_period_day_single, # ABOUT (depth 1) test_about_appname_version, test_about_authors, test_about_links, test_about_logo_block_vlm, # VLM #1 (position) # WALKING MODES (depth 2) test_walkingmode_first_card, test_walkingmode_running_and_labels, # HELP (depth 1) test_help_key_headers, test_help_ordered_headers, test_help_list_layout_vlm, # VLM #2 (position) # SETTINGS headers (depth 1) test_settings_headers, # SETTINGS -> General (depth 2) test_general_switch_titles, test_general_unit_summaries, test_general_value_summaries,]
if __name__ == "__main__": run_suite(TESTS, "text")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792{ "manifest_version": 1, "kit_api_version": 1, "task_id": "privacy-friendly-pedometer", "baseline_model": "claude-opus-4-8", "baseline_package": "", "total": 120, "manifest_sha": "33fa43ef91c1", "tests": [ { "name": "computation::computation_calorie_number_with_unit", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_chart_distance_type_vlm", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_chart_plotted_vlm", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_distance_two_decimals", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_distance_unit_km_when_ge_100m", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_distance_unit_meters_small", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_period_changes_day_to_week", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_period_day", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_period_month_pattern", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_period_week_is_range", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_steps_100", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_steps_1000", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_steps_199", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_steps_200", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_steps_2000", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_steps_50", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_steps_arbitrary", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_steps_large", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_steps_zero", "module": "computation", "baseline_status": "passed" }, { "name": "computation::computation_summary_numbers_vlm", "module": "computation", "baseline_status": "passed" }, { "name": "interaction::interaction_add_walking_mode", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_card_context_menu", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_correct_steps_cancel_noop", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_correct_steps_save_persists", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_correct_steps_survives_death", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_help_expand_collapse", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_multi_record_integrity", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_switch_active_mode", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_training_creates_session", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_vlm_context_menu_vlm", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_vlm_correct_steps_dialog_vlm", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_vlm_help_expanded_vlm", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_vlm_summary_popup_vlm", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_vlm_training_live_vlm", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_vlm_walking_mode_card_vlm", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_vlm_walking_modes_list_vlm", "module": "interaction", "baseline_status": "passed" }, { "name": "interaction::interaction_walking_mode_survives_death", "module": "interaction", "baseline_status": "passed" }, { "name": "navigation::nav_backstack_about_home", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_backstack_distance_home", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_backstack_general_settings", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_backstack_walkingmodes_deep", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_chain_settings_general", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_chain_settings_notifications", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_chain_settings_walkingmodes", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_chain_training_live", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_reach_about", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_reach_distance", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_reach_help", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_reach_settings", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_reach_training", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_vlm_about_vlm", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_vlm_distance_vlm", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_vlm_help_vlm", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_vlm_settings_headers_vlm", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_vlm_training_live_vlm", "module": "navigation", "baseline_status": "passed" }, { "name": "navigation::nav_vlm_training_overview_vlm", "module": "navigation", "baseline_status": "passed" }, { "name": "states::states_chart_radio_default", "module": "states", "baseline_status": "passed" }, { "name": "states::states_chart_select_distance", "module": "states", "baseline_status": "passed" }, { "name": "states::states_chart_steps_radio_vlm", "module": "states", "baseline_status": "passed" }, { "name": "states::states_continue_back_to_pause", "module": "states", "baseline_status": "passed" }, { "name": "states::states_distance_measuring_vlm", "module": "states", "baseline_status": "passed" }, { "name": "states::states_distance_start_to_stop", "module": "states", "baseline_status": "passed" }, { "name": "states::states_distance_stop_to_start", "module": "states", "baseline_status": "passed" }, { "name": "states::states_drawer_home_checked", "module": "states", "baseline_status": "passed" }, { "name": "states::states_pause_icon_vlm", "module": "states", "baseline_status": "passed" }, { "name": "states::states_pause_to_continue", "module": "states", "baseline_status": "passed" }, { "name": "states::states_running_radio_vlm", "module": "states", "baseline_status": "passed" }, { "name": "states::states_settings_hardware_toggle", "module": "states", "baseline_status": "passed" }, { "name": "states::states_settings_permanent_on_vlm", "module": "states", "baseline_status": "passed" }, { "name": "states::states_settings_switches_vlm", "module": "states", "baseline_status": "passed" }, { "name": "states::states_settings_velocity_persists", "module": "states", "baseline_status": "passed" }, { "name": "states::states_settings_velocity_toggle", "module": "states", "baseline_status": "passed" }, { "name": "states::states_tab_back_to_day", "module": "states", "baseline_status": "passed" }, { "name": "states::states_tab_day_highlight_vlm", "module": "states", "baseline_status": "passed" }, { "name": "states::states_tab_day_selected_on_launch", "module": "states", "baseline_status": "passed" }, { "name": "states::states_tab_switch_day_to_week", "module": "states", "baseline_status": "passed" }, { "name": "states::states_tab_switch_week_to_month", "module": "states", "baseline_status": "passed" }, { "name": "states::states_tab_week_highlight_vlm", "module": "states", "baseline_status": "passed" }, { "name": "states::states_walking_radio_default", "module": "states", "baseline_status": "passed" }, { "name": "states::states_walking_radio_default_vlm", "module": "states", "baseline_status": "passed" }, { "name": "states::states_walking_select_running", "module": "states", "baseline_status": "passed" }, { "name": "structure::structure_chart_canvas_vlm", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_chart_popup", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_correct_steps_dialog", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_distance_start_stop", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_distance_start_stop_vlm", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_drawer_subtree", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_drawer_subtree_vlm", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_gate_launch", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_gate_tabs_pager", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_gate_toolbar", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_gate_two_cards", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_help_expand_grows", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_home_two_cards_vlm", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_pause_button_flip", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_summary_popup", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_summary_popup_vlm", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_tabs_row_vlm", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_training_grid_vlm", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_training_reach", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_walkmodes_add_dialog", "module": "structure", "baseline_status": "passed" }, { "name": "structure::structure_walkmodes_layout_vlm", "module": "structure", "baseline_status": "passed" }, { "name": "text::text_about_appname_version", "module": "text", "baseline_status": "passed" }, { "name": "text::text_about_authors", "module": "text", "baseline_status": "passed" }, { "name": "text::text_about_links", "module": "text", "baseline_status": "passed" }, { "name": "text::text_about_logo_block_vlm", "module": "text", "baseline_status": "passed" }, { "name": "text::text_general_switch_titles", "module": "text", "baseline_status": "passed" }, { "name": "text::text_general_unit_summaries", "module": "text", "baseline_status": "passed" }, { "name": "text::text_general_value_summaries", "module": "text", "baseline_status": "passed" }, { "name": "text::text_help_key_headers", "module": "text", "baseline_status": "passed" }, { "name": "text::text_help_list_layout_vlm", "module": "text", "baseline_status": "passed" }, { "name": "text::text_help_ordered_headers", "module": "text", "baseline_status": "passed" }, { "name": "text::text_home_period_subtitle", "module": "text", "baseline_status": "passed" }, { "name": "text::text_home_step_title", "module": "text", "baseline_status": "passed" }, { "name": "text::text_period_day_single", "module": "text", "baseline_status": "passed" }, { "name": "text::text_period_month_shape", "module": "text", "baseline_status": "passed" }, { "name": "text::text_period_week_is_range", "module": "text", "baseline_status": "passed" }, { "name": "text::text_settings_headers", "module": "text", "baseline_status": "passed" }, { "name": "text::text_walkingmode_first_card", "module": "text", "baseline_status": "passed" }, { "name": "text::text_walkingmode_running_and_labels", "module": "text", "baseline_status": "passed" } ], "ignored": [], "vlm_assertions": [ { "name": "computation::computation_chart_plotted_vlm", "module": "computation", "tag": "shape" }, { "name": "computation::computation_summary_numbers_vlm", "module": "computation", "tag": "content" }, { "name": "computation::computation_chart_distance_type_vlm", "module": "computation", "tag": "content" }, { "name": "interaction::interaction_vlm_walking_modes_list_vlm", "module": "interaction", "tag": "position" }, { "name": "interaction::interaction_vlm_walking_mode_card_vlm", "module": "interaction", "tag": "position" }, { "name": "interaction::interaction_vlm_context_menu_vlm", "module": "interaction", "tag": "content" }, { "name": "interaction::interaction_vlm_correct_steps_dialog_vlm", "module": "interaction", "tag": "position" }, { "name": "interaction::interaction_vlm_summary_popup_vlm", "module": "interaction", "tag": "shape" }, { "name": "interaction::interaction_vlm_help_expanded_vlm", "module": "interaction", "tag": "content" }, { "name": "interaction::interaction_vlm_training_live_vlm", "module": "interaction", "tag": "position" }, { "name": "navigation::nav_vlm_training_overview_vlm", "module": "navigation", "tag": "position" }, { "name": "navigation::nav_vlm_distance_vlm", "module": "navigation", "tag": "position" }, { "name": "navigation::nav_vlm_settings_headers_vlm", "module": "navigation", "tag": "layout" }, { "name": "navigation::nav_vlm_about_vlm", "module": "navigation", "tag": "shape" }, { "name": "navigation::nav_vlm_help_vlm", "module": "navigation", "tag": "layout" }, { "name": "navigation::nav_vlm_training_live_vlm", "module": "navigation", "tag": "position" }, { "name": "states::states_pause_icon_vlm", "module": "states", "tag": "shape" }, { "name": "states::states_tab_day_highlight_vlm", "module": "states", "tag": "color" }, { "name": "states::states_tab_week_highlight_vlm", "module": "states", "tag": "color" }, { "name": "states::states_walking_radio_default_vlm", "module": "states", "tag": "shape" }, { "name": "states::states_running_radio_vlm", "module": "states", "tag": "shape" }, { "name": "states::states_chart_steps_radio_vlm", "module": "states", "tag": "shape" }, { "name": "states::states_distance_measuring_vlm", "module": "states", "tag": "layout" }, { "name": "states::states_settings_switches_vlm", "module": "states", "tag": "layout" }, { "name": "states::states_settings_permanent_on_vlm", "module": "states", "tag": "position" }, { "name": "structure::structure_drawer_subtree_vlm", "module": "structure", "tag": "position" }, { "name": "structure::structure_summary_popup_vlm", "module": "structure", "tag": "layout" }, { "name": "structure::structure_distance_start_stop_vlm", "module": "structure", "tag": "position" }, { "name": "structure::structure_walkmodes_layout_vlm", "module": "structure", "tag": "position" }, { "name": "structure::structure_training_grid_vlm", "module": "structure", "tag": "position" }, { "name": "structure::structure_home_two_cards_vlm", "module": "structure", "tag": "position" }, { "name": "structure::structure_tabs_row_vlm", "module": "structure", "tag": "position" }, { "name": "structure::structure_chart_canvas_vlm", "module": "structure", "tag": "shape" }, { "name": "text::text_about_logo_block_vlm", "module": "text", "tag": "position" }, { "name": "text::text_help_list_layout_vlm", "module": "text", "tag": "position" } ], "vlm_total": 35, "n_vlm_unverified": 0, "vlm_log_found": true}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723{ "schema_version": 2, "instance_id": "android/secuso-privacy-friendly-pedometer", "grading": { "mode": "inline", "model": null, "scored_separately": true }, "totals": { "assertions": 35, "with_verdict": 35, "calibrated": 0, "usable": null, "scored_records": 35, "unbacked_records": 0 }, "assertions": [ { "id": "structure_drawer_subtree_vlm", "screenshot": "structure_drawer_subtree_vlm.png", "assertion": "Is a navigation drawer panel open on the left side, showing a vertical list of menu items (such as Pedometer, Training, Settings, Help, About)?", "form": "question", "expected": true, "aspect": "layout", "modality": null, "links_to": "structure_drawer_subtree", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "structure_summary_popup_vlm", "screenshot": "structure_summary_popup_vlm.png", "assertion": "Is a small popup menu or dialog shown listing selectable options including 'Walking', 'Running' and 'Correct steps'?", "form": "question", "expected": true, "aspect": "layout", "modality": null, "links_to": "structure_summary_popup", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "structure_distance_start_stop_vlm", "screenshot": "structure_distance_start_stop_vlm.png", "assertion": "Does this screen show a large distance value like '0.00 m' near the top and a single wide button labelled 'START DISTANCE MEASUREMENT' at the bottom?", "form": "question", "expected": true, "aspect": "layout", "modality": null, "links_to": "structure_distance_start_stop", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "structure_walkmodes_layout_vlm", "screenshot": "structure_walkmodes_layout_vlm.png", "assertion": "Are there exactly two list rows stacked vertically, each showing a mode name and a 'Step length:' value in meters, with a round blue '+' floating button in the lower-right corner?", "form": "question", "expected": true, "aspect": "layout", "modality": null, "links_to": "structure_walkmodes_layout", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "structure_training_grid_vlm", "screenshot": "structure_training_grid_vlm.png", "assertion": "Does this screen show a large timer near the top and a grid of stats below it including distance in 'm', velocity in 'km/h', calories in 'cal' and a step count?", "form": "question", "expected": true, "aspect": "layout", "modality": null, "links_to": "structure_training_grid", "rigor": { "jump_kind": "transition", "depth": 2 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "structure_home_two_cards_vlm", "screenshot": "structure_home_two_cards_vlm.png", "assertion": "Are there two stacked white card panels: an upper 'Summary of activities' card and a lower 'Detailed summary of your activities' card?", "form": "question", "expected": true, "aspect": "layout", "modality": null, "links_to": "structure_home_two_cards", "rigor": { "jump_kind": "none", "depth": 0 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "structure_tabs_row_vlm", "screenshot": "structure_tabs_row_vlm.png", "assertion": "Is there a horizontal row of exactly three tabs labelled DAY, WEEK and MONTH directly below the top toolbar?", "form": "question", "expected": true, "aspect": "position", "modality": null, "links_to": "structure_tabs_row", "rigor": { "jump_kind": "none", "depth": 0 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "structure_chart_canvas_vlm", "screenshot": "structure_chart_canvas_vlm.png", "assertion": "In the lower card, is a line/area chart rendered with a horizontal time axis (labels like 00:00, 08:00, 16:00, 23:00) and a vertical axis with numeric gridlines (0 up to 10,000)?", "form": "question", "expected": true, "aspect": "shape", "modality": null, "links_to": "structure_chart_canvas", "rigor": { "jump_kind": "none", "depth": 0 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "nav_vlm_training_overview_vlm", "screenshot": "nav_vlm_training_overview_vlm.png", "assertion": "Is there a round blue floating action button with a white plus sign in the bottom-right corner of this screen?", "form": "question", "expected": true, "aspect": "position", "modality": null, "links_to": "nav_vlm_training_overview", "rigor": { "jump_kind": "reach", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "nav_vlm_distance_vlm", "screenshot": "nav_vlm_distance_vlm.png", "assertion": "Is there a full-width dark-blue button labelled 'START DISTANCE MEASUREMENT' pinned to the bottom of this screen?", "form": "question", "expected": true, "aspect": "position", "modality": null, "links_to": "nav_vlm_distance", "rigor": { "jump_kind": "reach", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "nav_vlm_settings_headers_vlm", "screenshot": "nav_vlm_settings_headers_vlm.png", "assertion": "Does this screen show a vertical settings list with three rows labelled 'General', 'Notifications' and 'Walking modes', each with an icon on the left?", "form": "question", "expected": true, "aspect": "layout", "modality": null, "links_to": "nav_vlm_settings_headers", "rigor": { "jump_kind": "reach", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "nav_vlm_about_vlm", "screenshot": "nav_vlm_about_vlm.png", "assertion": "Does this About screen show the SECUSO logo (a round emblem to the left of the word 'SECUSO') in its middle area?", "form": "question", "expected": true, "aspect": "shape", "modality": null, "links_to": "nav_vlm_about", "rigor": { "jump_kind": "reach", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "nav_vlm_help_vlm", "screenshot": "nav_vlm_help_vlm.png", "assertion": "Does this screen show a top app bar titled 'Help' and, below it, a vertical list of help topics starting with 'Overview'?", "form": "question", "expected": true, "aspect": "layout", "modality": null, "links_to": "nav_vlm_help", "rigor": { "jump_kind": "reach", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "nav_vlm_training_live_vlm", "screenshot": "nav_vlm_training_live_vlm.png", "assertion": "Is there a prominent full-width button labelled 'END TRAINING NOW' at the bottom of this screen?", "form": "question", "expected": true, "aspect": "position", "modality": null, "links_to": "nav_vlm_training_live", "rigor": { "jump_kind": "reach", "depth": 2 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "interaction_vlm_walking_modes_list_vlm", "screenshot": "interaction_vlm_walking_modes_list_vlm.png", "assertion": "Are there three or more walking-mode cards stacked vertically in a list on this screen, each on its own row?", "form": "question", "expected": true, "aspect": "layout", "modality": null, "links_to": "interaction_vlm_walking_modes_list", "rigor": { "jump_kind": "reach", "depth": 2 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "interaction_vlm_walking_mode_card_vlm", "screenshot": "interaction_vlm_walking_mode_card_vlm.png", "assertion": "Does each walking-mode card show a bold mode name (such as 'Walking(active)' or 'Running') together with a line reading 'Step length:' followed by a number and the word 'meters'?", "form": "question", "expected": true, "aspect": "content", "modality": null, "links_to": "interaction_vlm_walking_mode_card", "rigor": { "jump_kind": "reach", "depth": 2 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "interaction_vlm_context_menu_vlm", "screenshot": "interaction_vlm_context_menu_vlm.png", "assertion": "Is a small pop-up context menu shown listing text options including 'Set as active' and 'Learn'?", "form": "question", "expected": true, "aspect": "content", "modality": null, "links_to": "interaction_vlm_context_menu", "rigor": { "jump_kind": "transition", "depth": 3 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "interaction_vlm_correct_steps_dialog_vlm", "screenshot": "interaction_vlm_correct_steps_dialog_vlm.png", "assertion": "Is a dialog shown titled 'Correct steps' containing a numeric input field and two text buttons labelled 'CANCEL' and 'SAVE'?", "form": "question", "expected": true, "aspect": "layout", "modality": null, "links_to": "interaction_vlm_correct_steps_dialog", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "interaction_vlm_summary_popup_vlm", "screenshot": "interaction_vlm_summary_popup_vlm.png", "assertion": "Is a small pop-up menu shown listing 'Walking' and 'Running' each with a round radio button on the right, plus a 'Correct steps' option, and is exactly one radio button filled in (selected)?", "form": "question", "expected": true, "aspect": "shape", "modality": null, "links_to": "interaction_vlm_summary_popup", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "interaction_vlm_help_expanded_vlm", "screenshot": "interaction_vlm_help_expanded_vlm.png", "assertion": "Under the 'Overview' heading of this help list, is a paragraph of descriptive body text now shown (the 'Overview' topic is expanded)?", "form": "question", "expected": true, "aspect": "content", "modality": null, "links_to": "interaction_vlm_help_expanded", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "interaction_vlm_training_live_vlm", "screenshot": "interaction_vlm_training_live_vlm.png", "assertion": "Does this training screen show live workout stats — a duration timer near the top and figures for distance, velocity, calories and steps — above a full-width 'END TRAINING NOW' button?", "form": "question", "expected": true, "aspect": "layout", "modality": null, "links_to": "interaction_vlm_training_live", "rigor": { "jump_kind": "reach", "depth": 2 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "computation_chart_plotted_vlm", "screenshot": "computation_chart_plotted_vlm.png", "assertion": "Does the lower card show a line chart with a plotted line and round data points across a grid (not an empty or blank graph)?", "form": "question", "expected": true, "aspect": "shape", "modality": null, "links_to": "computation_chart_plotted", "rigor": { "jump_kind": "value", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "computation_summary_numbers_vlm", "screenshot": "computation_summary_numbers_vlm.png", "assertion": "In the upper summary card, is a numeric step count shown as a large number next to the word 'Steps', with a distance value and a unit (m or km) below it?", "form": "question", "expected": true, "aspect": "content", "modality": null, "links_to": "computation_summary_numbers", "rigor": { "jump_kind": "value", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "computation_chart_distance_type_vlm", "screenshot": "computation_chart_distance_type_vlm.png", "assertion": "Does the lower card display a chart (a graph area with axes/grid and plotted data), consistent with showing distance data?", "form": "question", "expected": true, "aspect": "content", "modality": null, "links_to": "computation_chart_distance_type", "rigor": { "jump_kind": "value", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "states_pause_icon_vlm", "screenshot": "states_pause_icon_vlm.png", "assertion": "Look at the icon button in the top-right of the blue toolbar. Is it now a single right-pointing 'play' / triangle style icon (indicating detection is paused and can be continued) rather than two pause bars?", "form": "question", "expected": true, "aspect": "shape", "modality": null, "links_to": "states_pause_icon", "rigor": { "jump_kind": "transition", "depth": 0 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "states_tab_day_highlight_vlm", "screenshot": "states_tab_day_highlight_vlm.png", "assertion": "Among the three tabs DAY, WEEK, MONTH at the top, is 'DAY' the highlighted/selected one (its label a different, brighter colour such as yellow AND with a coloured underline indicator beneath it) while WEEK and MONTH are plain white with no underline?", "form": "question", "expected": true, "aspect": "color", "modality": null, "links_to": "states_tab_day_highlight", "rigor": { "jump_kind": "transition", "depth": 0 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "states_tab_week_highlight_vlm", "screenshot": "states_tab_week_highlight_vlm.png", "assertion": "Among the three tabs DAY, WEEK, MONTH at the top, is 'WEEK' now the highlighted/selected one (brighter/different colour label AND a coloured underline indicator beneath WEEK) instead of DAY?", "form": "question", "expected": true, "aspect": "color", "modality": null, "links_to": "states_tab_week_highlight", "rigor": { "jump_kind": "transition", "depth": 0 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "states_walking_radio_default_vlm", "screenshot": "states_walking_radio_default_vlm.png", "assertion": "In this popup listing walking modes, is the round radio button next to 'Walking' filled in (a solid coloured/blue dot = selected) while the radio next to 'Running' is an empty hollow circle?", "form": "question", "expected": true, "aspect": "shape", "modality": null, "links_to": "states_walking_radio_default", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "states_running_radio_vlm", "screenshot": "states_running_radio_vlm.png", "assertion": "In this walking-modes popup, is the round radio button next to 'Running' now filled in (solid coloured/blue dot = selected)?", "form": "question", "expected": true, "aspect": "shape", "modality": null, "links_to": "states_running_radio", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "states_chart_steps_radio_vlm", "screenshot": "states_chart_steps_radio_vlm.png", "assertion": "In this popup listing chart data types, is the round radio button next to 'Steps' filled in (solid coloured/blue dot = selected) while 'Distance' and 'Calories' show empty hollow circles?", "form": "question", "expected": true, "aspect": "shape", "modality": null, "links_to": "states_chart_steps_radio", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "states_distance_measuring_vlm", "screenshot": "states_distance_measuring_vlm.png", "assertion": "Does the large button at the bottom of the screen read 'STOP DISTANCE MEASUREMENT' (a measurement is in progress) rather than 'START DISTANCE MEASUREMENT'?", "form": "question", "expected": true, "aspect": "layout", "modality": null, "links_to": "states_distance_measuring", "rigor": { "jump_kind": "transition", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "states_settings_switches_vlm", "screenshot": "states_settings_switches_vlm.png", "assertion": "In this settings list, are there several ON/OFF toggle SWITCHES aligned down the RIGHT-hand edge of the rows (rounded pill toggles), one per switch preference?", "form": "question", "expected": true, "aspect": "layout", "modality": null, "links_to": "states_settings_switches", "rigor": { "jump_kind": "transition", "depth": 2 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "states_settings_permanent_on_vlm", "screenshot": "states_settings_permanent_on_vlm.png", "assertion": "Is the 'Permanent step counter' toggle in the ON position?", "form": "question", "expected": true, "aspect": "position", "modality": null, "links_to": "states_settings_permanent_on", "rigor": { "jump_kind": "transition", "depth": 2 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "text_about_logo_block_vlm", "screenshot": "text_about_logo_block_vlm.png", "assertion": "Is the title text 'Privacy Friendly Pedometer' shown near the top of this screen with an app icon or logo image directly above or beside it?", "form": "question", "expected": true, "aspect": "position", "modality": null, "links_to": "text_about_logo_block", "rigor": { "jump_kind": "none", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null }, { "id": "text_help_list_layout_vlm", "screenshot": "text_help_list_layout_vlm.png", "assertion": "Is this screen a vertically stacked list of collapsed section headers (the first is 'Overview'), each row showing an expand/collapse chevron or arrow on its right side?", "form": "question", "expected": true, "aspect": "layout", "modality": null, "links_to": "text_help_list_layout", "rigor": { "jump_kind": "none", "depth": 1 }, "verdict": { "answer": true, "passed": true, "raw": null }, "calibration": null } ], "merged_from_files": 1, "source_shapes": { "list": 1 }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license forsoftware and other kinds of works.
The licenses for most software and other practical works are designedto take away your freedom to share and change the works. By contrast,the GNU General Public License is intended to guarantee your freedom toshare and change all versions of a program--to make sure it remains freesoftware for all its users. We, the Free Software Foundation, use theGNU General Public License for most of our software; it applies also toany other work released this way by its authors. You can apply it toyour programs, too.
When we speak of free software, we are referring to freedom, notprice. Our General Public Licenses are designed to make sure that youhave the freedom to distribute copies of free software (and charge forthem if you wish), that you receive source code or can get it if youwant it, that you can change the software or use pieces of it in newfree programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying youthese rights or asking you to surrender the rights. Therefore, you havecertain responsibilities if you distribute copies of the software, or ifyou modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whethergratis or for a fee, you must pass on to the recipients the samefreedoms that you received. You must make sure that they, too, receiveor can get the source code. And you must show them these terms so theyknow their rights.
Developers that use the GNU GPL protect your rights with two steps:(1) assert copyright on the software, and (2) offer you this Licensegiving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explainsthat there is no warranty for this free software. For both users' andauthors' sake, the GPL requires that modified versions be marked aschanged, so that their problems will not be attributed erroneously toauthors of previous versions.
Some devices are designed to deny users access to install or runmodified versions of the software inside them, although the manufacturercan do so. This is fundamentally incompatible with the aim ofprotecting users' freedom to change the software. The systematicpattern of such abuse occurs in the area of products for individuals touse, which is precisely where it is most unacceptable. Therefore, wehave designed this version of the GPL to prohibit the practice for thoseproducts. If such problems arise substantially in other domains, westand ready to extend this provision to those domains in future versionsof the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.States should not allow patents to restrict development and use ofsoftware on general-purpose computers, but in those that do, we wish toavoid the special danger that patents applied to a free program couldmake it effectively proprietary. To prevent this, the GPL assures thatpatents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution andmodification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds ofworks, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under thisLicense. Each licensee is addressed as "you". "Licensees" and"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the workin a fashion requiring copyright permission, other than the making of anexact copy. The resulting work is called a "modified version" of theearlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work basedon the Program.
To "propagate" a work means to do anything with it that, withoutpermission, would make you directly or secondarily liable forinfringement under applicable copyright law, except executing it on acomputer or modifying a private copy. Propagation includes copying,distribution (with or without modification), making available to thepublic, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables otherparties to make or receive copies. Mere interaction with a user througha computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"to the extent that it includes a convenient and prominently visiblefeature that (1) displays an appropriate copyright notice, and (2)tells the user that there is no warranty for the work (except to theextent that warranties are provided), that licensees may convey thework under this License, and how to view a copy of this License. Ifthe interface presents a list of user commands or options, such as amenu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the workfor making modifications to it. "Object code" means any non-sourceform of a work.
A "Standard Interface" means an interface that either is an officialstandard defined by a recognized standards body, or, in the case ofinterfaces specified for a particular programming language, one thatis widely used among developers working in that language.
The "System Libraries" of an executable work include anything, otherthan the work as a whole, that (a) is included in the normal form ofpackaging a Major Component, but which is not part of that MajorComponent, and (b) serves only to enable use of the work with thatMajor Component, or to implement a Standard Interface for which animplementation is available to the public in source code form. A"Major Component", in this context, means a major essential component(kernel, window system, and so on) of the specific operating system(if any) on which the executable work runs, or a compiler used toproduce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means allthe source code needed to generate, install, and (for an executablework) run the object code and to modify the work, including scripts tocontrol those activities. However, it does not include the work'sSystem Libraries, or general-purpose tools or generally available freeprograms which are used unmodified in performing those activities butwhich are not part of the work. For example, Corresponding Sourceincludes interface definition files associated with source files forthe work, and the source code for shared libraries and dynamicallylinked subprograms that the work is specifically designed to require,such as by intimate data communication or control flow between thosesubprograms and other parts of the work.
The Corresponding Source need not include anything that userscan regenerate automatically from other parts of the CorrespondingSource.
The Corresponding Source for a work in source code form is thatsame work.
2. Basic Permissions.
All rights granted under this License are granted for the term ofcopyright on the Program, and are irrevocable provided the statedconditions are met. This License explicitly affirms your unlimitedpermission to run the unmodified Program. The output from running acovered work is covered by this License only if the output, given itscontent, constitutes a covered work. This License acknowledges yourrights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do notconvey, without conditions so long as your license otherwise remainsin force. You may convey covered works to others for the sole purposeof having them make modifications exclusively for you, or provide youwith facilities for running those works, provided that you comply withthe terms of this License in conveying all material for which you donot control copyright. Those thus making or running the covered worksfor you must do so exclusively on your behalf, under your directionand control, on terms that prohibit them from making any copies ofyour copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely underthe conditions stated below. Sublicensing is not allowed; section 10makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technologicalmeasure under any applicable law fulfilling obligations under article11 of the WIPO copyright treaty adopted on 20 December 1996, orsimilar laws prohibiting or restricting circumvention of suchmeasures.
When you convey a covered work, you waive any legal power to forbidcircumvention of technological measures to the extent such circumventionis effected by exercising rights under this License with respect tothe covered work, and you disclaim any intention to limit operation ormodification of the work as a means of enforcing, against the work'susers, your or third parties' legal rights to forbid circumvention oftechnological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as youreceive it, in any medium, provided that you conspicuously andappropriately publish on each copy an appropriate copyright notice;keep intact all notices stating that this License and anynon-permissive terms added in accord with section 7 apply to the code;keep intact all notices of the absence of any warranty; and give allrecipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications toproduce it from the Program, in the form of source code under theterms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independentworks, which are not by their nature extensions of the covered work,and which are not combined with it such as to form a larger program,in or on a volume of a storage or distribution medium, is called an"aggregate" if the compilation and its resulting copyright are notused to limit the access or legal rights of the compilation's usersbeyond what the individual works permit. Inclusion of a covered workin an aggregate does not cause this License to apply to the otherparts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the termsof sections 4 and 5, provided that you also convey themachine-readable Corresponding Source under the terms of this License,in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excludedfrom the Corresponding Source as a System Library, need not beincluded in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means anytangible personal property which is normally used for personal, family,or household purposes, or (2) anything designed or sold for incorporationinto a dwelling. In determining whether a product is a consumer product,doubtful cases shall be resolved in favor of coverage. For a particularproduct received by a particular user, "normally used" refers to atypical or common use of that class of product, regardless of the statusof the particular user or of the way in which the particular useractually uses, or expects or is expected to use, the product. A productis a consumer product regardless of whether the product has substantialcommercial, industrial or non-consumer uses, unless such uses representthe only significant mode of use of the product.
"Installation Information" for a User Product means any methods,procedures, authorization keys, or other information required to installand execute modified versions of a covered work in that User Product froma modified version of its Corresponding Source. The information mustsuffice to ensure that the continued functioning of the modified objectcode is in no case prevented or interfered with solely becausemodification has been made.
If you convey an object code work under this section in, or with, orspecifically for use in, a User Product, and the conveying occurs aspart of a transaction in which the right of possession and use of theUser Product is transferred to the recipient in perpetuity or for afixed term (regardless of how the transaction is characterized), theCorresponding Source conveyed under this section must be accompaniedby the Installation Information. But this requirement does not applyif neither you nor any third party retains the ability to installmodified object code on the User Product (for example, the work hasbeen installed in ROM).
The requirement to provide Installation Information does not include arequirement to continue to provide support service, warranty, or updatesfor a work that has been modified or installed by the recipient, or forthe User Product in which it has been modified or installed. Access to anetwork may be denied when the modification itself materially andadversely affects the operation of the network or violates the rules andprotocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,in accord with this section must be in a format that is publiclydocumented (and with an implementation available to the public insource code form), and must require no special password or key forunpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of thisLicense by making exceptions from one or more of its conditions.Additional permissions that are applicable to the entire Program shallbe treated as though they were included in this License, to the extentthat they are valid under applicable law. If additional permissionsapply only to part of the Program, that part may be used separatelyunder those permissions, but the entire Program remains governed bythis License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your optionremove any additional permissions from that copy, or from any part ofit. (Additional permissions may be written to require their ownremoval in certain cases when you modify the work.) You may placeadditional permissions on material, added by you to a covered work,for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material youadd to a covered work, you may (if authorized by the copyright holders ofthat material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "furtherrestrictions" within the meaning of section 10. If the Program as youreceived it, or any part of it, contains a notice stating that it isgoverned by this License along with a term that is a furtherrestriction, you may remove that term. If a license document containsa further restriction but permits relicensing or conveying under thisLicense, you may add to a covered work material governed by the termsof that license document, provided that the further restriction doesnot survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, youmust place, in the relevant source files, a statement of theadditional terms that apply to those files, or a notice indicatingwhere to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in theform of a separately written license, or stated as exceptions;the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expresslyprovided under this License. Any attempt otherwise to propagate ormodify it is void, and will automatically terminate your rights underthis License (including any patent licenses granted under the thirdparagraph of section 11).
However, if you cease all violation of this License, then yourlicense from a particular copyright holder is reinstated (a)provisionally, unless and until the copyright holder explicitly andfinally terminates your license, and (b) permanently, if the copyrightholder fails to notify you of the violation by some reasonable meansprior to 60 days after the cessation.
Moreover, your license from a particular copyright holder isreinstated permanently if the copyright holder notifies you of theviolation by some reasonable means, this is the first time you havereceived notice of violation of this License (for any work) from thatcopyright holder, and you cure the violation prior to 30 days afteryour receipt of the notice.
Termination of your rights under this section does not terminate thelicenses of parties who have received copies or rights from you underthis License. If your rights have been terminated and not permanentlyreinstated, you do not qualify to receive new licenses for the samematerial under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive orrun a copy of the Program. Ancillary propagation of a covered workoccurring solely as a consequence of using peer-to-peer transmissionto receive a copy likewise does not require acceptance. However,nothing other than this License grants you permission to propagate ormodify any covered work. These actions infringe copyright if you donot accept this License. Therefore, by modifying or propagating acovered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automaticallyreceives a license from the original licensors, to run, modify andpropagate that work, subject to this License. You are not responsiblefor enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of anorganization, or substantially all assets of one, or subdividing anorganization, or merging organizations. If propagation of a coveredwork results from an entity transaction, each party to thattransaction who receives a copy of the work also receives whateverlicenses to the work the party's predecessor in interest had or couldgive under the previous paragraph, plus a right to possession of theCorresponding Source of the work from the predecessor in interest, ifthe predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of therights granted or affirmed under this License. For example, you maynot impose a license fee, royalty, or other charge for exercise ofrights granted under this License, and you may not initiate litigation(including a cross-claim or counterclaim in a lawsuit) alleging thatany patent claim is infringed by making, using, selling, offering forsale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under thisLicense of the Program or a work on which the Program is based. Thework thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claimsowned or controlled by the contributor, whether already acquired orhereafter acquired, that would be infringed by some manner, permittedby this License, of making, using, or selling its contributor version,but do not include claims that would be infringed only as aconsequence of further modification of the contributor version. Forpurposes of this definition, "control" includes the right to grantpatent sublicenses in a manner consistent with the requirements ofthis License.
Each contributor grants you a non-exclusive, worldwide, royalty-freepatent license under the contributor's essential patent claims, tomake, use, sell, offer for sale, import and otherwise run, modify andpropagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any expressagreement or commitment, however denominated, not to enforce a patent(such as an express permission to practice a patent or covenant not tosue for patent infringement). To "grant" such a patent license to aparty means to make such an agreement or commitment not to enforce apatent against the party.
If you convey a covered work, knowingly relying on a patent license,and the Corresponding Source of the work is not available for anyoneto copy, free of charge and under the terms of this License, through apublicly available network server or other readily accessible means,then you must either (1) cause the Corresponding Source to be soavailable, or (2) arrange to deprive yourself of the benefit of thepatent license for this particular work, or (3) arrange, in a mannerconsistent with the requirements of this License, to extend the patentlicense to downstream recipients. "Knowingly relying" means you haveactual knowledge that, but for the patent license, your conveying thecovered work in a country, or your recipient's use of the covered workin a country, would infringe one or more identifiable patents in thatcountry that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction orarrangement, you convey, or propagate by procuring conveyance of, acovered work, and grant a patent license to some of the partiesreceiving the covered work authorizing them to use, propagate, modifyor convey a specific copy of the covered work, then the patent licenseyou grant is automatically extended to all recipients of the coveredwork and works based on it.
A patent license is "discriminatory" if it does not include withinthe scope of its coverage, prohibits the exercise of, or isconditioned on the non-exercise of one or more of the rights that arespecifically granted under this License. You may not convey a coveredwork if you are a party to an arrangement with a third party that isin the business of distributing software, under which you make paymentto the third party based on the extent of your activity of conveyingthe work, and under which the third party grants, to any of theparties who would receive the covered work from you, a discriminatorypatent license (a) in connection with copies of the covered workconveyed by you (or copies made from those copies), or (b) primarilyfor and in connection with specific products or compilations thatcontain the covered work, unless you entered into that arrangement,or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limitingany implied license or other defenses to infringement that mayotherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement orotherwise) that contradict the conditions of this License, they do notexcuse you from the conditions of this License. If you cannot convey acovered work so as to satisfy simultaneously your obligations under thisLicense and any other pertinent obligations, then as a consequence you maynot convey it at all. For example, if you agree to terms that obligate youto collect a royalty for further conveying from those to whom you conveythe Program, the only way you could satisfy both those terms and thisLicense would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you havepermission to link or combine any covered work with a work licensedunder version 3 of the GNU Affero General Public License into a singlecombined work, and to convey the resulting work. The terms of thisLicense will continue to apply to the part which is the covered work,but the special requirements of the GNU Affero General Public License,section 13, concerning interaction through a network will apply to thecombination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions ofthe GNU General Public License from time to time. Such new versions willbe similar in spirit to the present version, but may differ in detail toaddress new problems or concerns.
Each version is given a distinguishing version number. If theProgram specifies that a certain numbered version of the GNU GeneralPublic License "or any later version" applies to it, you have theoption of following the terms and conditions either of that numberedversion or of any later version published by the Free SoftwareFoundation. If the Program does not specify a version number of theGNU General Public License, you may choose any version ever publishedby the Free Software Foundation.
If the Program specifies that a proxy can decide which futureversions of the GNU General Public License can be used, that proxy'spublic statement of acceptance of a version permanently authorizes youto choose that version for the Program.
Later license versions may give you additional or differentpermissions. However, no additional obligations are imposed on anyauthor or copyright holder as a result of your choosing to follow alater version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BYAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHTHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTYOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULARPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAMIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OFALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITINGWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYSTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANYGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THEUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OFDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRDPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OFSUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability providedabove cannot be given local legal effect according to their terms,reviewing courts shall apply local law that most closely approximatesan absolute waiver of all civil liability in connection with theProgram, unless a warranty or assumption of liability accompanies acopy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatestpossible use to the public, the best way to achieve this is to make itfree software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safestto attach them to the start of each source file to most effectivelystate the exclusion of warranty; and each file should have at leastthe "copyright" line and a pointer to where the full notice is found.
Privacy Friendly App for playing Sudoku. Copyright (C) 2016-2018 Christopher Beckmann and Timm Lippert
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a shortnotice like this when it starts in an interactive mode:
Privacy Friendly Apps Copyright (C) 2016-2018 Christopher Beckmann and Timm Lippert This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriateparts of the General Public License. Of course, your program's commandsmight be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,if any, to sign a "copyright disclaimer" for the program, if necessary.For more information on this, and how to apply and follow the GNU GPL, see<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your programinto proprietary programs. If your program is a subroutine library, youmay consider it more useful to permit linking proprietary applications withthe library. If this is what you want to do, use the GNU Lesser GeneralPublic License instead of this License. But first, please read<http://www.gnu.org/philosophy/why-not-lgpl.html>.12345678910{ "schema_version": 1, "instance_id": "android/secuso-privacy-friendly-sudoku", "platform": "android", "repo": "https://github.com/SecUSo/privacy-friendly-sudoku", "commit": "17fa5880ef6c81f6da52617dc9ea794a452f5568", "patches": [], "package": "org.secuso.privacyfriendlysudoku", "license": null}123456789#!/usr/bin/env bash# TEMPLATE (rb_unify) — review before use.set -euo pipefail: "${RB_PACKAGE:?must be exported by the runner from instance.json}"D="$(cd "$(dirname "$0")" && pwd)"; SER="${DEVICE_SERIAL:-emulator-5554}"APK="$(find "$D" -name '*.apk' | head -1)"[ -n "$APK" ] || { echo "ERROR: no apk found; extract reference.tar.gz first" >&2; exit 1; }adb -s "$SER" install -r -g "$APK"adb -s "$SER" shell monkey -p "$RB_PACKAGE" -c android.intent.category.LAUNCHER 1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222{ "module": "computation", "total": 20, "passed": 20, "failed": 0, "pass_rate": 1.0, "rule": { "total": 10, "passed": 10, "failed": 0, "pass_rate": 1.0 }, "vlm": { "total": 10, "passed": 10, "failed": 0, "pass_rate": 1.0 }, "vlm_ratio": 1.0, "audit": { "kit_api_version": 1, "existence": 0, "liveness": 0, "interactive": 20, "depth_ge1": 6, "depth_ge2": 0, "value": 20, "vlm_fine": 9 }, "results": [ { "test": "computation_difficulty_easy", "passed": true, "message": "", "depth": 0, "jump_kind": "value", "tier": 3, "expect": "difficultyText='Easy'" }, { "test": "computation_difficulty_moderate", "passed": true, "message": "", "depth": 0, "jump_kind": "value", "tier": 3, "expect": "difficultyText='Moderate'" }, { "test": "computation_difficulty_hard", "passed": true, "message": "", "depth": 0, "jump_kind": "value", "tier": 3, "expect": "difficultyText='Hard'" }, { "test": "computation_difficulty_challenge", "passed": true, "message": "", "depth": 0, "jump_kind": "value", "tier": 3, "expect": "difficultyText='Challenge'" }, { "test": "computation_difficulty_challenge_stars_vlm", "passed": true, "message": "VLM: Q='Are all four stars of the difficulty rating bar filled solid blue (fully coloured, not grey outlines)?' A=YES expect=YES", "depth": 0, "jump_kind": "value", "tier": 3, "expect": "VLM YES: Are all four stars of the difficulty rating bar filled solid blue (fully coloured, not grey outlines)?", "tag": "color" }, { "test": "computation_difficulty_easy_stars_vlm", "passed": true, "message": "VLM: Q='In the difficulty rating bar, is exactly ONE star filled solid blue while the remaining three stars are grey?' A=YES expect=YES", "depth": 0, "jump_kind": "value", "tier": 3, "expect": "VLM YES: In the difficulty rating bar, is exactly ONE star filled solid blue while the remaining three stars are grey?", "tag": "color" }, { "test": "computation_difficulty_moderate_stars_vlm", "passed": true, "message": "VLM: Q='In the difficulty rating bar, are exactly TWO stars filled solid blue while the other two stars are grey?' A=YES expect=YES", "depth": 0, "jump_kind": "value", "tier": 3, "expect": "VLM YES: In the difficulty rating bar, are exactly TWO stars filled solid blue while the other two stars are grey?", "tag": "color" }, { "test": "computation_difficulty_hard_stars_vlm", "passed": true, "message": "VLM: Q='In the difficulty rating bar, are exactly THREE stars filled solid blue while one star is grey?' A=YES expect=YES", "depth": 0, "jump_kind": "value", "tier": 3, "expect": "VLM YES: In the difficulty rating bar, are exactly THREE stars filled solid blue while one star is grey?", "tag": "color" }, { "test": "computation_levelcount_format", "passed": true, "message": "", "depth": 0, "jump_kind": "value", "tier": 3, "expect": "level_count matches 'Levels available: <int>'" }, { "test": "computation_levelcount_recomputes", "passed": true, "message": "", "depth": 0, "jump_kind": "value", "tier": 3, "expect": "level_count differs Easy vs Challenge" }, { "test": "computation_carousel_default_9x9", "passed": true, "message": "", "depth": 0, "jump_kind": "value", "tier": 3, "expect": "section_label='Sudoku 9x9'" }, { "test": "computation_carousel_right_12x12", "passed": true, "message": "", "depth": 0, "jump_kind": "value", "tier": 3, "expect": "section_label='Sudoku 12x12'" }, { "test": "computation_carousel_right_16x16", "passed": true, "message": "", "depth": 0, "jump_kind": "value", "tier": 3, "expect": "section_label='Sudoku 16x16'" }, { "test": "computation_carousel_left_back_12x12", "passed": true, "message": "", "depth": 0, "jump_kind": "value", "tier": 3, "expect": "section_label='Sudoku 12x12'" }, { "test": "computation_place_top_1_vlm", "passed": true, "message": "VLM: Q='Do three or more cells in the TOP ROW (the uppermost horizontal line) of the Sudoku grid display the digit 1?' A=YES expect=YES", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "VLM YES: Do three or more cells in the TOP ROW (the uppermost horizontal line) of the Sudoku grid display the digit 1?", "tag": "position" }, { "test": "computation_place_top_9_vlm", "passed": true, "message": "VLM: Q='Do three or more cells in the TOP ROW (the uppermost horizontal line) of the Sudoku grid display the digit 9?' A=YES expect=YES", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "VLM YES: Do three or more cells in the TOP ROW (the uppermost horizontal line) of the Sudoku grid display the digit 9?", "tag": "position" }, { "test": "computation_place_top_5_vlm", "passed": true, "message": "VLM: Q='Do three or more cells in the TOP ROW (the uppermost horizontal line) of the Sudoku grid display the digit 5?' A=YES expect=YES", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "VLM YES: Do three or more cells in the TOP ROW (the uppermost horizontal line) of the Sudoku grid display the digit 5?", "tag": "position" }, { "test": "computation_place_top_7_vlm", "passed": true, "message": "VLM: Q='Do three or more cells in the TOP ROW (the uppermost horizontal line) of the Sudoku grid display the digit 7?' A=YES expect=YES", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "VLM YES: Do three or more cells in the TOP ROW (the uppermost horizontal line) of the Sudoku grid display the digit 7?", "tag": "position" }, { "test": "computation_place_leftcol_1_vlm", "passed": true, "message": "VLM: Q='Do three or more cells in the LEFT-MOST vertical column of the Sudoku grid display the digit 1?' A=YES expect=YES", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "VLM YES: Do three or more cells in the LEFT-MOST vertical column of the Sudoku grid display the digit 1?", "tag": "position" }, { "test": "computation_place_persist_9_vlm", "passed": true, "message": "VLM: Q='Is the digit 9 clearly written inside multiple cells of the top row of the Sudoku grid?' A=YES expect=YES", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "VLM YES: Is the digit 9 clearly written inside multiple cells of the top row of the Sudoku grid?", "tag": "content" } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195{ "module": "interaction", "total": 17, "passed": 17, "failed": 0, "pass_rate": 1.0, "rule": { "total": 7, "passed": 7, "failed": 0, "pass_rate": 1.0 }, "vlm": { "total": 10, "passed": 10, "failed": 0, "pass_rate": 1.0 }, "vlm_ratio": 1.4286, "audit": { "kit_api_version": 1, "existence": 0, "liveness": 0, "interactive": 17, "depth_ge1": 17, "depth_ge2": 4, "value": 11, "vlm_fine": 1 }, "results": [ { "test": "interaction_create_value_vlm", "passed": true, "message": "VLM: Q='In the TOP row of this Sudoku 9x9 grid, are there THREE OR MORE cells each showing the large digit 5?' A=YES expect=YES", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "VLM YES: In the TOP row of this Sudoku 9x9 grid, are there THREE OR MORE cells each showing the large digit 5?", "tag": "content" }, { "test": "interaction_edit_value_vlm", "passed": true, "message": "VLM: Q='In the TOP row of this Sudoku 9x9 grid, are there now THREE OR MORE cells each showing the large digit 8?' A=YES expect=YES", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "VLM YES: In the TOP row of this Sudoku 9x9 grid, are there now THREE OR MORE cells each showing the large digit 8?", "tag": "content" }, { "test": "interaction_create_and_edit", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "top row shows many 5s, then many 8s after re-entry" }, { "test": "interaction_undo_removes_vlm", "passed": true, "message": "VLM: Q='In the TOP row of this Sudoku 9x9 grid, are there THREE OR MORE cells each showing the large digit 5?' A=NO expect=NO", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM NO: In the TOP row of this Sudoku 9x9 grid, are there THREE OR MORE cells each showing the large digit 5?", "tag": "content" }, { "test": "interaction_redo_restores_vlm", "passed": true, "message": "VLM: Q='In the TOP row of this Sudoku 9x9 grid, are there again THREE OR MORE cells each showing the large digit 5?' A=YES expect=YES", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "VLM YES: In the TOP row of this Sudoku 9x9 grid, are there again THREE OR MORE cells each showing the large digit 5?", "tag": "content" }, { "test": "interaction_delete_placed7_vlm", "passed": true, "message": "VLM: Q='In the TOP row of this Sudoku 9x9 grid, are there THREE OR MORE cells each showing the large digit 7?' A=YES expect=YES", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "VLM YES: In the TOP row of this Sudoku 9x9 grid, are there THREE OR MORE cells each showing the large digit 7?", "tag": "content" }, { "test": "interaction_delete_cleared_vlm", "passed": true, "message": "VLM: Q='In the TOP row of this Sudoku 9x9 grid, are there THREE OR MORE cells each showing the large digit 7?' A=NO expect=NO", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM NO: In the TOP row of this Sudoku 9x9 grid, are there THREE OR MORE cells each showing the large digit 7?", "tag": "content" }, { "test": "interaction_delete_clears", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "top row shows many 7s, then none after delete" }, { "test": "interaction_note_multi_vlm", "passed": true, "message": "VLM: Q='In the TOP row of this Sudoku 9x9 grid, do MULTIPLE cells contain SMALL corner pencil-mark notes showing both the digit 3 and the digit 5 (tiny marks in the cell corners, not one big centered digit)?' A=YES expect=YES", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "VLM YES: In the TOP row of this Sudoku 9x9 grid, do MULTIPLE cells contain SMALL corner pencil-mark notes showing both the digit 3 and the digit 5 (tiny marks in the cell corners, not one big centered digit)?", "tag": "content" }, { "test": "interaction_note_delete_vlm", "passed": true, "message": "VLM: Q='In the TOP row of this Sudoku 9x9 grid, are the cells now free of SMALL corner pencil-mark notes (no tiny 3/5 marks left in the empty cells)?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: In the TOP row of this Sudoku 9x9 grid, are the cells now free of SMALL corner pencil-mark notes (no tiny 3/5 marks left in the empty cells)?", "tag": "content" }, { "test": "interaction_two_placements_vlm", "passed": true, "message": "VLM: Q='In this Sudoku 9x9 grid, does the TOP row contain multiple cells showing the large digit 1, AND the SECOND row (just below it) contain multiple cells showing the large digit 2 — i.e. two different digits in two different rows?' A=YES expect=YES", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "VLM YES: In this Sudoku 9x9 grid, does the TOP row contain multiple cells showing the large digit 1, AND the SECOND row (just below it) contain multiple cells showing the large digit 2 — i.e. two different digits in two different rows?", "tag": "position" }, { "test": "interaction_two_placements", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "row0 has many 1s and row1 has many 2s" }, { "test": "interaction_redo_no_undo_vlm", "passed": true, "message": "VLM: Q='In the TOP row of this Sudoku 9x9 grid, are there still THREE OR MORE cells each showing the large digit 4?' A=YES expect=YES", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "VLM YES: In the TOP row of this Sudoku 9x9 grid, are there still THREE OR MORE cells each showing the large digit 4?", "tag": "content" }, { "test": "interaction_multi_saved_games", "passed": true, "message": "", "depth": 2, "jump_kind": "value", "tier": 3, "expect": ">=2 saved-game rows (saw 2)" }, { "test": "interaction_persist_after_kill", "passed": true, "message": "", "depth": 2, "jump_kind": "value", "tier": 3, "expect": "saved game persisted after kill (saw 1 row(s))" }, { "test": "interaction_resume_saved_game", "passed": true, "message": "", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "LoadGame row -> GameActivity (resumed)" }, { "test": "interaction_longpress_menu", "passed": true, "message": "", "depth": 2, "jump_kind": "transition", "tier": 2, "expect": "context menu/dialog appeared after long-press on a saved row" } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227{ "module": "navigation", "total": 21, "passed": 21, "failed": 0, "pass_rate": 1.0, "rule": { "total": 15, "passed": 15, "failed": 0, "pass_rate": 1.0 }, "vlm": { "total": 6, "passed": 6, "failed": 0, "pass_rate": 1.0 }, "vlm_ratio": 0.4, "audit": { "kit_api_version": 1, "existence": 6, "liveness": 0, "interactive": 15, "depth_ge1": 15, "depth_ge2": 10, "value": 0, "vlm_fine": 1 }, "results": [ { "test": "nav_reach_daily", "passed": true, "message": "", "depth": 2, "jump_kind": "reach", "tier": 2, "expect": "'Daily Sudoku' title appeared and home 'NEW GAME' left the surface" }, { "test": "nav_reach_daily_vlm", "passed": true, "message": "VLM: Q='Does this Daily Sudoku screen show, on the left, a preview grid with a difficulty label and stars under it, and on the right a stats block listing hints / completed games / total time?' A=YES expect=YES", "depth": 2, "jump_kind": "none", "tier": 0, "expect": "VLM YES: Does this Daily Sudoku screen show, on the left, a preview grid with a difficulty label and stars under it, and on the right a stats block listing hints / completed games / total time?", "tag": "layout" }, { "test": "nav_reach_highscore", "passed": true, "message": "", "depth": 2, "jump_kind": "reach", "tier": 2, "expect": "'Highscore' title appeared and home 'NEW GAME' left the surface" }, { "test": "nav_reach_highscore_vlm", "passed": true, "message": "VLM: Q='Does this Highscore screen show a top row of game-size tabs (like SUDOKU 6X6 / 9X9 / 12X12 / 16X16) and below a table of difficulty rows (Easy, Moderate, Hard, Challenge) with time columns?' A=YES expect=YES", "depth": 2, "jump_kind": "none", "tier": 0, "expect": "VLM YES: Does this Highscore screen show a top row of game-size tabs (like SUDOKU 6X6 / 9X9 / 12X12 / 16X16) and below a table of difficulty rows (Easy, Moderate, Hard, Challenge) with time columns?", "tag": "layout" }, { "test": "nav_reach_settings", "passed": true, "message": "", "depth": 2, "jump_kind": "reach", "tier": 2, "expect": "'Settings' title appeared (toggle Switches present) and home 'NEW GAME' left" }, { "test": "nav_reach_help", "passed": true, "message": "", "depth": 2, "jump_kind": "reach", "tier": 2, "expect": "'Help' title appeared and home 'NEW GAME' left the surface" }, { "test": "nav_reach_about", "passed": true, "message": "", "depth": 2, "jump_kind": "reach", "tier": 2, "expect": "'About' appeared with app name / 'Version:' label; home 'NEW GAME' left" }, { "test": "nav_reach_tutorial", "passed": true, "message": "", "depth": 2, "jump_kind": "reach", "tier": 2, "expect": "Tutorial 'Welcome!' slide appeared (SKIP/NEXT present); home 'NEW GAME' left" }, { "test": "nav_reach_tutorial_vlm", "passed": true, "message": "VLM: Q='Is this a full-screen intro/tutorial slide with a solid blue background, a large 'Welcome!' heading, an app logo in the middle, and SKIP and NEXT buttons at the bottom corners?' A=YES expect=YES", "depth": 2, "jump_kind": "none", "tier": 0, "expect": "VLM YES: Is this a full-screen intro/tutorial slide with a solid blue background, a large 'Welcome!' heading, an app logo in the middle, and SKIP and NEXT buttons at the bottom corners?", "tag": "layout" }, { "test": "nav_reach_game", "passed": true, "message": "", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "Top surface flipped MainActivity->GameActivity; 'NEW GAME' left the live screen" }, { "test": "nav_reach_game_vlm", "passed": true, "message": "VLM: Q='Is a 9x9 Sudoku grid of square cells shown filling most of the screen, with a number pad of digit buttons 1 to 9 below it?' A=YES expect=YES", "depth": 1, "jump_kind": "none", "tier": 0, "expect": "VLM YES: Is a 9x9 Sudoku grid of square cells shown filling most of the screen, with a number pad of digit buttons 1 to 9 below it?", "tag": "layout" }, { "test": "nav_reach_import_dialog", "passed": true, "message": "", "depth": 2, "jump_kind": "reach", "tier": 2, "expect": "Import dialog 'IMPORT'/'CANCEL' buttons appeared over the drawer/menu" }, { "test": "nav_reach_import_dialog_vlm", "passed": true, "message": "VLM: Q='Is a white modal dialog box shown centered over a dimmed background, asking to enter the link of the sudoku to import, with CANCEL and IMPORT buttons at the bottom-right?' A=YES expect=YES", "depth": 2, "jump_kind": "none", "tier": 0, "expect": "VLM YES: Is a white modal dialog box shown centered over a dimmed background, asking to enter the link of the sudoku to import, with CANCEL and IMPORT buttons at the bottom-right?", "tag": "position" }, { "test": "nav_import_dialog_cancel_returns", "passed": true, "message": "", "depth": 2, "jump_kind": "reach", "tier": 2, "expect": "After CANCEL: home 'NEW GAME' reappeared and dialog 'IMPORT' left" }, { "test": "nav_reach_continue", "passed": true, "message": "", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "'Continue Game' title appeared with a saved 'Sudoku 9x9' row; home 'NEW GAME' left" }, { "test": "nav_reach_continue_vlm", "passed": true, "message": "VLM: Q='Does this Continue Game screen show a vertical list of saved-game rows, each with a small grid thumbnail on the left, a 'Sudoku 9x9' label with stars, and a time on the right?' A=YES expect=YES", "depth": 1, "jump_kind": "none", "tier": 0, "expect": "VLM YES: Does this Continue Game screen show a vertical list of saved-game rows, each with a small grid thumbnail on the left, a 'Sudoku 9x9' label with stars, and a time on the right?", "tag": "layout" }, { "test": "nav_continue_row_resumes_game", "passed": true, "message": "", "depth": 2, "jump_kind": "reach", "tier": 2, "expect": "Saved-row tap flipped list->GameActivity; 'Continue Game' title left" }, { "test": "nav_back_settings_to_home", "passed": true, "message": "", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "One BACK popped Settings: home 'NEW GAME' reappeared and 'Settings' left" }, { "test": "nav_back_about_to_home", "passed": true, "message": "", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "One BACK popped About: home 'NEW GAME' reappeared and 'About' left" }, { "test": "nav_back_daily_to_home", "passed": true, "message": "", "depth": 1, "jump_kind": "reach", "tier": 2, "expect": "One BACK popped Daily Sudoku: home 'NEW GAME' reappeared and 'Daily Sudoku' left" }, { "test": "nav_chain_settings_back_about", "passed": true, "message": "", "depth": 3, "jump_kind": "reach", "tier": 2, "expect": "drawer->Settings, BACK to home, drawer->About: 'About' appeared, 'NEW GAME' gone" } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242{ "module": "states", "total": 22, "passed": 22, "failed": 0, "pass_rate": 1.0, "rule": { "total": 10, "passed": 10, "failed": 0, "pass_rate": 1.0 }, "vlm": { "total": 12, "passed": 12, "failed": 0, "pass_rate": 1.0 }, "vlm_ratio": 1.2, "audit": { "kit_api_version": 1, "existence": 0, "liveness": 0, "interactive": 22, "depth_ge1": 22, "depth_ge2": 0, "value": 2, "vlm_fine": 11 }, "results": [ { "test": "states_deactivate_timer_toggle", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "Deactivate Timer checked false->true" }, { "test": "states_timer_reset_toggle", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "Timer Reset checked true->false" }, { "test": "states_timer_reset_roundtrip", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "Timer Reset checked true->false->true" }, { "test": "states_note_deletion_toggle", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "Note deletion checked true->false" }, { "test": "states_keep_screen_on_toggle", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "Keep Screen On checked true->false" }, { "test": "states_dark_theme_toggle", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "Dark Theme checked false->true; screen repaints dark" }, { "test": "states_dark_theme_toggle_vlm", "passed": true, "message": "VLM: Q='Is the screen background very dark (near-black) with light coloured text, i.e. a dark theme?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Is the screen background very dark (near-black) with light coloured text, i.e. a dark theme?", "tag": "color" }, { "test": "states_dark_theme_disables_auto", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "'Automatically by system' enabled true->false when Dark Theme ON" }, { "test": "states_deactivate_timer_persists", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "Deactivate Timer persisted checked=true after process death" }, { "test": "states_dark_theme_persists", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "Dark Theme persisted checked=true after process death" }, { "test": "states_stats_tab_selected", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "tab selection Sudoku 6x6->Sudoku 9x9" }, { "test": "states_stats_tab_selected_vlm", "passed": true, "message": "VLM: Q='In the row of tabs near the top (SUDOKU 6X6 / 9X9 / 12X12 / 16X16), is the 'SUDOKU 9X9' tab the highlighted/selected one (brighter text with an underline indicator beneath it)?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: In the row of tabs near the top (SUDOKU 6X6 / 9X9 / 12X12 / 16X16), is the 'SUDOKU 9X9' tab the highlighted/selected one (brighter text with an underline indicator beneath it)?", "tag": "layout" }, { "test": "states_undo_before_vlm", "passed": true, "message": "VLM: Q='Look at the bottom-left special button (a curved arrow pointing LEFT, the undo button). Is it GREYED-OUT / disabled (grey background), rather than blue?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Look at the bottom-left special button (a curved arrow pointing LEFT, the undo button). Is it GREYED-OUT / disabled (grey background), rather than blue?", "tag": "color" }, { "test": "states_undo_enable_vlm", "passed": true, "message": "VLM: Q='Look at the bottom-left special button (a curved arrow pointing LEFT, the undo button). Is it now BLUE / enabled (blue background), rather than grey?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Look at the bottom-left special button (a curved arrow pointing LEFT, the undo button). Is it now BLUE / enabled (blue background), rather than grey?", "tag": "color" }, { "test": "states_redo_before_vlm", "passed": true, "message": "VLM: Q='Look at the special button that is a curved arrow pointing RIGHT (the redo button, second from the left in the bottom special-button row). Is it GREYED-OUT / disabled (grey background), rather than blue?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Look at the special button that is a curved arrow pointing RIGHT (the redo button, second from the left in the bottom special-button row). Is it GREYED-OUT / disabled (grey background), rather than blue?", "tag": "color" }, { "test": "states_redo_enable_vlm", "passed": true, "message": "VLM: Q='Look at the special button that is a curved arrow pointing RIGHT (the redo button, second from the left in the bottom special-button row). Is it now BLUE / enabled (blue background), rather than grey?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Look at the special button that is a curved arrow pointing RIGHT (the redo button, second from the left in the bottom special-button row). Is it now BLUE / enabled (blue background), rather than grey?", "tag": "color" }, { "test": "states_note_off_vlm", "passed": true, "message": "VLM: Q='Look at the rightmost special button in the bottom row (a pencil icon, the note toggle). Is it in its NORMAL state — a plain blue button with a black border and NO yellow/gold highlight border?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Look at the rightmost special button in the bottom row (a pencil icon, the note toggle). Is it in its NORMAL state — a plain blue button with a black border and NO yellow/gold highlight border?", "tag": "color" }, { "test": "states_note_on_vlm", "passed": true, "message": "VLM: Q='Look at the rightmost special button in the bottom row (the pencil / note toggle). Is it now HIGHLIGHTED with a YELLOW / gold border around it (note mode ON)?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Look at the rightmost special button in the bottom row (the pencil / note toggle). Is it now HIGHLIGHTED with a YELLOW / gold border around it (note mode ON)?", "tag": "color" }, { "test": "states_note_off_again_vlm", "passed": true, "message": "VLM: Q='Look at the rightmost special button in the bottom row (the pencil / note toggle). Is it back to its NORMAL state — a plain blue button with a black border and NO yellow/gold highlight border?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Look at the rightmost special button in the bottom row (the pencil / note toggle). Is it back to its NORMAL state — a plain blue button with a black border and NO yellow/gold highlight border?", "tag": "color" }, { "test": "states_cell_none_vlm", "passed": true, "message": "VLM: Q='Look at the sudoku board grid. Are ALL the cells plain white with NO cell highlighted green and NO row or column highlighted yellow?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Look at the sudoku board grid. Are ALL the cells plain white with NO cell highlighted green and NO row or column highlighted yellow?", "tag": "color" }, { "test": "states_cell_select_vlm", "passed": true, "message": "VLM: Q='Look at the sudoku board grid. Is there a cell highlighted GREEN whose entire row and entire column are highlighted YELLOW?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Look at the sudoku board grid. Is there a cell highlighted GREEN whose entire row and entire column are highlighted YELLOW?", "tag": "color" }, { "test": "states_samenumber_highlight_vlm", "passed": true, "message": "VLM: Q='Look at the sudoku board grid. Are MULTIPLE cells that contain the same digit highlighted with an ORANGE / gold background?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Look at the sudoku board grid. Are MULTIPLE cells that contain the same digit highlighted with an ORANGE / gold background?", "tag": "color" } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173{ "module": "structure", "total": 15, "passed": 15, "failed": 0, "pass_rate": 1.0, "rule": { "total": 9, "passed": 9, "failed": 0, "pass_rate": 1.0 }, "vlm": { "total": 6, "passed": 6, "failed": 0, "pass_rate": 1.0 }, "vlm_ratio": 0.6667, "audit": { "kit_api_version": 1, "existence": 5, "liveness": 0, "interactive": 10, "depth_ge1": 8, "depth_ge2": 0, "value": 0, "vlm_fine": 6 }, "results": [ { "test": "structure_gate_launch", "passed": true, "message": "", "depth": 0, "jump_kind": "none", "tier": 0, "expect": "" }, { "test": "structure_gate_toolbar_host", "passed": true, "message": "", "depth": 0, "jump_kind": "none", "tier": 0, "expect": "" }, { "test": "structure_gate_main_controls", "passed": true, "message": "", "depth": 0, "jump_kind": "none", "tier": 0, "expect": "" }, { "test": "structure_drawer_shape", "passed": true, "message": "", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "CheckedTextView 0->8 when drawer opens, back to 0 on close" }, { "test": "structure_import_dialog_shape", "passed": true, "message": "", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "EditText 0->1 when Import dialog opens, back to 0 on CANCEL" }, { "test": "structure_settings_switch_shape", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "Settings surface adds a column of ~7 Switch rows (menu has 0)" }, { "test": "structure_stats_rows_shape", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "Stats surface has 4 difficulty rows + 4 game-type selectors" }, { "test": "structure_tutorial_pager_shape", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "Tutorial surface adds SKIP + NEXT pager controls" }, { "test": "structure_game_surface_flip", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "Top surface flips MainActivity->GameActivity; menu subtree leaves the tree" }, { "test": "structure_game_surface_flip_vlm", "passed": true, "message": "VLM: Q='Is there a 9x9 Sudoku grid of square cells (nine rows and nine columns divided into 3x3 blocks) filling most of the screen?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Is there a 9x9 Sudoku grid of square cells (nine rows and nine columns divided into 3x3 blocks) filling most of the screen?", "tag": "shape" }, { "test": "structure_game_numberpad_shape_vlm", "passed": true, "message": "VLM: Q='Below the Sudoku grid, is there a row-based number pad showing the digit buttons 1 through 9?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: Below the Sudoku grid, is there a row-based number pad showing the digit buttons 1 through 9?", "tag": "shape" }, { "test": "structure_game_specialbar_shape_vlm", "passed": true, "message": "VLM: Q='At the very bottom of the screen, below the number pad, is there a horizontal bar containing several small icon buttons?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: At the very bottom of the screen, below the number pad, is there a horizontal bar containing several small icon buttons?", "tag": "position" }, { "test": "structure_game_toolbar_shape_vlm", "passed": true, "message": "VLM: Q='In the top toolbar of this Sudoku game, is the difficulty shown as a small row of star icons?' A=YES expect=YES", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "VLM YES: In the top toolbar of this Sudoku game, is the difficulty shown as a small row of star icons?", "tag": "shape" }, { "test": "structure_main_preview_shape_vlm", "passed": true, "message": "VLM: Q='On this main menu, is there a preview image of a square Sudoku grid (a grid of cells arranged in a square) above the difficulty text?' A=YES expect=YES", "depth": 0, "jump_kind": "none", "tier": 0, "expect": "VLM YES: On this main menu, is there a preview image of a square Sudoku grid (a grid of cells arranged in a square) above the difficulty text?", "tag": "shape" }, { "test": "structure_main_stars_shape_vlm", "passed": true, "message": "VLM: Q='On this main menu, near the difficulty label, is the difficulty level shown as a horizontal row of star-shaped icons?' A=YES expect=YES", "depth": 0, "jump_kind": "none", "tier": 0, "expect": "VLM YES: On this main menu, near the difficulty label, is the difficulty level shown as a horizontal row of star-shaped icons?", "tag": "shape" } ]}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910#!/usr/bin/env python3"""Android TestGen Kit — the single source of every test helper, so a test'sNAVIGATION DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded,and self-auditable.
LOCATION AT RUNTIME: alongside the generated test files (testgen: $TESTGEN_DIR/eval/,eval: the restored eval dir). READ-ONLY — never edit, copy, or reimplement it.`import` it from every test file:
import os, sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from android_testgen_kit import * # noqa: F403
WHY THIS EXISTS Helpers used to be re-emitted verbatim into every generated test file (~370 lines x 6 files). That blew the output-token ceiling, forced a "write the script in pieces" protocol, let each copy drift, and duplicated one API key into every file. Everything mechanical now lives here; prompts carry only judgement.
Two orthogonal properties decide whether a suite really exercises an app: * navigation DEPTH — how many SURFACES you cross before the assertion (0 = first screen, 1 = one page/dialog/sheet, 2+ = deeper) * jump RIGOR — what the assertion after the trigger actually checks Prose alone let these drift, so every behavioral test DECLARES both:
@and_test(expects=("interaction_create_note", "interaction_create_note_vlm")) def test_create_note(): ... record("interaction_create_note", ok, "behavior_wrong: ...", depth=1, jump_kind="value", expect="list shows 'Milk'")
jump_kind (verbatim strings — audit/stats key off them): "none" no trigger; existence/gate only -> tier 0 "liveness" only "did not crash / still foreground" -> tier 1 (weak; never ship) "reach" a real surface jump: the TARGET surface's element APPEARED *and* the SOURCE surface's DISAPPEARED -> tier 2 "transition" a state flip (checked/enabled/selected/mode) with before->after -> tier 2 "value" a specific expected value/content was asserted -> tier 3
WHAT A "SURFACE" IS ON ANDROID NOT the Activity — single-Activity Compose/Fragment apps never change it, so get_current_activity() cannot discriminate. A surface is the SET of visible discriminating element keys: and_showing() -> {"Button|Save", "TextView|Total"}. and_reach(before, after, target, source) therefore proves a real jump; reading a flat tree for an always-present element cannot fake it.
DETERMINISTIC DENOMINATOR Scoring is eval_pass_case / origin_total_case, so a test function MUST contribute the same number of records on every code path. @and_test(expects=(...)) owns the try/except and back-fills any declared-but-unrecorded name as a failure, and record() refuses duplicates. N is a literal in the decorator.
PORTABILITY (the same file scores the ORIGINAL and the RECREATION, whose packagename differs): always use the module-level PACKAGE (argv[1]). Never write a packagename, an .apk path, a /data/data path, or a pixel coordinate as a literal. python3 android_testgen_kit.py lint_sources <dir> # flags all of those
SELF-AUDIT (report-only — these are GOALS, never a gate that blocks delivery): python3 android_testgen_kit.py audit <results_dir> python3 android_testgen_kit.py lint <results_dir> python3 android_testgen_kit.py lint_sources <testgen_dir> python3 android_testgen_kit.py audit_depth <testgen_dir> [results_dir]"""from __future__ import annotations
import astimport base64import functoolsimport globimport hashlibimport jsonimport mathimport osimport reimport shleximport subprocessimport sysimport timeimport urllib.errorimport urllib.request
KIT_API_VERSION = 1
# ── Runtime context ────────────────────────────────────────────────────────────# argv[1] = package under test (ORIGINAL during testgen, RECREATION during eval).# argv[2] / $RESULTS_DIR = where the eval JSON + screenshots go.PACKAGE = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("PACKAGE", "")RESULTS_DIR = ( sys.argv[2] if len(sys.argv) > 2 else os.environ.get("RESULTS_DIR", "/workspace/testgen/eval"))ADB = os.environ.get("ADB_PATH", "adb")DEVICE = os.environ.get("DEVICE_SERIAL", "emulator-5554")
# Known emulator packages (from adb-tips). Used by type_text, never by tests.CLIPPER_PKG = "ca.zgrs.clipper"ADB_KEYBOARD_IME = "com.android.adbkeyboard/.AdbIME"
# ── Settling table (adb-tips §5). ANDROID_REMOTE=1 doubles it for tunnelled adb. ─_REMOTE = os.environ.get("ANDROID_REMOTE", "") in ("1", "true", "yes")_SETTLE_MULT = 2.0 if _REMOTE else 1.0SETTLE = { "launch": 3.0, "tap": 1.0, "key": 0.5, "keyboard": 0.5, "dump": 1.0, "ime": 0.5, "text": 0.5, "swipe": 1.0, "dump_retry": 2.0,}
JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3}
# Double-axis quota TARGETS (fractions). rb_audit REPORTS these; they are NOT a# gate. Tune here only — never restate them in a prompt.QUOTAS = { "existence_max": 0.30, # jump_kind=="none" share of ALL tests "interactive_min": 0.60, # reach|transition|value share of ALL tests "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests "depth_ge2_min": 0.15, # depth>=2 share of INTERACTIVE tests "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests # Suite-wide VLM budget, measured as vlm records / ALL records. The right # share is app-dependent (a chart/canvas app earns more than a list app) and # individual modules may legitimately contribute zero, so this is a BAND on # the whole suite, never a per-module requirement. "vlm_share_min": 0.30, "vlm_share_max": 0.50, "vlm_fine_min": 0.66, # fine-grained share of VLM records}
# Depth family (naming convention — see and_audit_depth). A test "crosses a# surface" iff it calls a member of this family; and_back* pops one. Semantic# aliases (and_enter_settings, and_reach_detail) match BY PREFIX, so the kit stays# small and the authored tests stay diverse.DEPTH_FWD_RE = re.compile(r"^and_(enter|reach)[a-z0-9_]*$")DEPTH_BACK_RE = re.compile(r"^and_back[a-z0-9_]*$")DEPTH_RESET_RE = re.compile(r"^and_reset_depth$")
# VLM tags. The fine-grained ones test an exact rendered property; and_audit# computes the >=2/3 fine share from these instead of trusting self-report.VLM_FINE_TAGS = {"color", "shape", "position", "size"}VLM_TAGS = VLM_FINE_TAGS | {"layout", "content"}
# Failure-message taxonomy. and_lint flags a failed record that uses none of them.FAIL_PREFIXES = ("setup_failed:", "feature_missing:", "behavior_wrong:", "exception:")
# Never tap these (tests mutate real device state).DANGEROUS_TEXTS = [ "delete", "remove", "clear", "reset", "erase", "discard", "uninstall", "sign out", "log out", "logout", "format", "wipe", "revoke", "deactivate", "删除", "移除", "清空", "清除", "重置", "退出登录", "注销", "格式化",]
_MODULE_ALIAS = { "states": "states", "state": "states", "structure": "structure", "structures": "structure", "navigation": "navigation", "nav": "navigation", "interaction": "interaction", "interactions": "interaction", "computation": "computation", "computations": "computation", "text": "text", "texts": "text",}
_DEPTH = 0 # surface counter for and_enter/and_back_results: list[dict] = []_seen: set[str] = set()_module: str = ""_screen_info: dict | None = None
def require_kit(min_version: int) -> None: """Fail loudly at import time if the kit is older than the test expects.""" if KIT_API_VERSION < min_version: raise RuntimeError( f"android_testgen_kit v{KIT_API_VERSION} is older than the required " f"v{min_version}; the restored testcase bundle and the kit disagree" )
def _infer_module() -> str: stem = os.path.splitext(os.path.basename(sys.argv[0] or ""))[0] if stem.startswith("test_android_"): return _MODULE_ALIAS.get(stem[len("test_android_"):], stem[len("test_android_"):]) return ""
def init(module: str = "", package: str = "", results_dir: str = "") -> None: """Optional. Overrides the values inferred from argv/env.""" global _module, PACKAGE, RESULTS_DIR if module: _module = _MODULE_ALIAS.get(module, module) if package: PACKAGE = package if results_dir: RESULTS_DIR = results_dir
_module = _infer_module()
def tier_of(jump_kind: str) -> int: return JUMP_KINDS.get(jump_kind, 2)
def settle(kind: str = "tap") -> None: """Sleep the calibrated settling time for `kind` (see SETTLE).""" time.sleep(SETTLE.get(kind, 1.0) * _SETTLE_MULT)
# ══════════════════════════════════════════════════════════════════════════════# (1) Results / recording# ══════════════════════════════════════════════════════════════════════════════
def record(test_name, passed, message="", *, depth=None, jump_kind="none", expect="", tag=None, backfilled=False) -> bool: """Record ONE test result. Returns bool(passed).
The three positional parameters are unchanged from the legacy inline helper. Everything new is keyword-only with a default, so old call sites still work.
depth surfaces this test crossed before asserting (see and_enter/and_reach) jump_kind none | liveness | reach | transition | value expect MANDATORY for reach/transition/value — the exact target you OBSERVED on the original app (and_lint flags an empty one) tag for VLM records: color|shape|position|size|layout|content message on failure, start it with setup_failed: / feature_missing: / behavior_wrong: / exception: """ if test_name in _seen: print(f" [DUP ] {_module}:{test_name} refused (already recorded) — " f"a duplicate would drift the denominator") return bool(passed) if jump_kind not in JUMP_KINDS: jump_kind = "none" d = _DEPTH if depth is None else int(depth) p = bool(passed) rec = { "test": test_name, "passed": p, "message": str(message), "depth": max(0, d), "jump_kind": jump_kind, "tier": tier_of(jump_kind), "expect": str(expect), } if tag: rec["tag"] = str(tag) if backfilled: rec["backfilled"] = True _results.append(rec) _seen.add(test_name) print(f" [{'PASS' if p else 'FAIL'}] {_module}:{test_name} " f"(depth={rec['depth']}, {jump_kind})" + (f" {message}" if message and not p else "")) _flush() return p
def _payload(module_name: str) -> dict: """The eval JSON. Shape is byte-compatible with the legacy helper: the aggregator reads module/total/passed/pass_rate, and the results extraction reads the rule/vlm sub-objects. New keys ride inside results[] + `audit`.""" rule = [r for r in _results if not r["test"].endswith("_vlm")] vlm = [r for r in _results if r["test"].endswith("_vlm")] rt, rp = len(rule), sum(1 for r in rule if r["passed"]) vt, vp = len(vlm), sum(1 for r in vlm if r["passed"]) total, passed = len(_results), sum(1 for r in _results if r["passed"]) fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS) inter = [r for r in _results if r["jump_kind"] in ("reach", "transition", "value")] return { "module": module_name, "total": total, "passed": passed, "failed": total - passed, "pass_rate": round(passed / total, 4) if total else 0, "rule": {"total": rt, "passed": rp, "failed": rt - rp, "pass_rate": round(rp / rt, 4) if rt else 0}, "vlm": {"total": vt, "passed": vp, "failed": vt - vp, "pass_rate": round(vp / vt, 4) if vt else 0}, "vlm_ratio": round(vt / rt, 4) if rt else 0, "audit": { "kit_api_version": KIT_API_VERSION, "existence": sum(1 for r in _results if r["jump_kind"] == "none"), "liveness": sum(1 for r in _results if r["jump_kind"] == "liveness"), "interactive": len(inter), "depth_ge1": sum(1 for r in inter if r["depth"] >= 1), "depth_ge2": sum(1 for r in inter if r["depth"] >= 2), "value": sum(1 for r in inter if r["jump_kind"] == "value"), "vlm_fine": fine, }, "results": _results, }
def _write_json(path: str, data: dict) -> None: """Atomic write, so a mid-run SIGKILL never leaves a truncated JSON.""" os.makedirs(os.path.dirname(path) or ".", exist_ok=True) tmp = path + ".tmp" with open(tmp, "w") as f: json.dump(data, f, indent=2, ensure_ascii=False) os.replace(tmp, path)
def _flush() -> None: """Persist after EVERY record, so a timeout/emulator hang leaves N results instead of zero. save_results() stays the documented finalizer.""" if not _module: return try: _write_json(os.path.join(RESULTS_DIR, f"android_{_module}_eval.json"), _payload(_module)) except Exception: pass
def save_results(module_name: str) -> dict: """MANDATORY finalizer. Authoritatively rewrites the eval JSON under the confirmed module name, prints the summary, and runs the in-process audit. Idempotent.""" global _module _module = _MODULE_ALIAS.get(module_name, module_name) out = _payload(_module) path = os.path.join(RESULTS_DIR, f"android_{_module}_eval.json") _write_json(path, out) print(f"Results: {out['passed']}/{out['total']} passed " f"(rule: {out['rule']['passed']}/{out['rule']['total']}, " f"vlm: {out['vlm']['passed']}/{out['vlm']['total']}) -> {path}") try: and_audit(RESULTS_DIR) and_lint(RESULTS_DIR) except Exception as exc: print(f"[audit] skipped: {exc}") return out
def declared_names() -> list[str]: """Every record name produced so far. The eval run MUST produce this same set against the recreation — a missing feature FAILS, it never vanishes from the denominator.""" return [r["test"] for r in _results]
def and_test(*, expects, module: str = ""): """Wrap a test function so it contributes EXACTLY len(expects) records on every code path — the deterministic-denominator guarantee.
Any name in `expects` still unrecorded when the function returns or raises is back-filled as a failure. The literal also lets and_audit_depth attribute records to this function exactly.
@and_test(expects=("states_toggle_dark", "states_toggle_dark_vlm")) def test_toggle_dark(): ... """ names = tuple(expects)
def deco(fn): @functools.wraps(fn) def wrapper(*a, **kw): if module: init(module=module) err = "" try: return fn(*a, **kw) except Exception as exc: err = f"{type(exc).__name__}: {exc}" print(f" [EXC ] {fn.__name__}: {err}") return None finally: for n in names: if n not in _seen: record(n, False, f"exception: not_reached ({err})" if err else "setup_failed: not_reached (no exception raised)", backfilled=True) wrapper._and_expects = names return wrapper return deco
def run_suite(tests, module: str) -> dict: """Run every test, then finalize. Each test owns its own entry point, so one failure never cascades.""" init(module=module) n_fix = len(fixture_names()) print(f"=== {module}: {len(tests)} tests | package={PACKAGE}" + (f" | fixtures={n_fix}" if n_fix else "") + " ===") if n_fix and not push_fixtures(): print(" [fixtures] WARNING: not all fixtures reached the device — every " "test that opens one will record setup_failed") for t in tests: and_reset_depth() try: t() except Exception as exc: print(f" [EXC ] {getattr(t, '__name__', t)}: {exc}") return save_results(module)
# ══════════════════════════════════════════════════════════════════════════════# (2) Device & adb primitives# ══════════════════════════════════════════════════════════════════════════════
def adb_shell(*args, timeout: int = 30) -> str: """`adb -s $DEVICE shell ...` -> stdout. The -s serial is ALWAYS injected, so a multi-device host can never dispatch to the wrong emulator.""" try: r = subprocess.run([ADB, "-s", DEVICE, "shell", *[str(a) for a in args]], capture_output=True, text=True, timeout=timeout) return r.stdout.strip() except subprocess.TimeoutExpired: return "" except Exception: return ""
def adb_raw(*args, timeout: int = 30) -> str: """`adb -s $DEVICE ...` (no `shell`) — for install/pull/exec-out.""" try: r = subprocess.run([ADB, "-s", DEVICE, *[str(a) for a in args]], capture_output=True, text=True, timeout=timeout) return r.stdout.strip() except Exception: return ""
def device_online() -> bool: try: out = subprocess.run([ADB, "devices"], capture_output=True, text=True, timeout=15).stdout except Exception: return False return any(ln.startswith(DEVICE) and ln.rstrip().endswith("device") for ln in out.splitlines()[1:])
def get_screen_info() -> dict: """Cached screen geometry. EVERY coordinate must be derived from this, never written as a literal — density and font scale differ across devices.""" global _screen_info if _screen_info: return _screen_info m = re.search(r"(\d+)x(\d+)", adb_shell("wm", "size")) w, h = (int(m.group(1)), int(m.group(2))) if m else (1080, 2400) md = re.search(r"(\d+)", adb_shell("wm", "density")) _screen_info = {"width": w, "height": h, "density": int(md.group(1)) if md else 440, "center_x": w // 2, "center_y": h // 2} return _screen_info
def screencap(path: str) -> bool: """Screenshot to a local path. exec-out first; falls back to on-device screencap + pull, which is what survives a tunnelled adb connection.""" os.makedirs(os.path.dirname(path) or ".", exist_ok=True) try: with open(path, "wb") as f: subprocess.run([ADB, "-s", DEVICE, "exec-out", "screencap", "-p"], stdout=f, timeout=20) if os.path.getsize(path) > 0: return True except Exception: pass remote = "/sdcard/_kit_shot.png" adb_shell("screencap", "-p", remote) adb_raw("pull", remote, path, timeout=40) adb_shell("rm", "-f", remote) return os.path.exists(path) and os.path.getsize(path) > 0
# ── Fixtures: sample files a file/image/document app needs to have anything to# open. These MUST be a pipeline artifact, not something you push by hand while# exploring: testgen and eval run in DIFFERENT jobs on DIFFERENT emulators, so a# hand-pushed file is gone by eval and every test that opens it records# setup_failed — blaming the recreation for a harness gap.## authoring (once, during recon): write the files into <EVAL_OUT>/fixtures/# consuming (every test run): run_suite() pushes them before the first test## The directory rides along with the test files into the testcases bank, so the# bytes are restored on every later eval. Sub-directories are preserved, so# fixtures/docs/a.pdf lands at /sdcard/Download/docs/a.pdf.FIXTURES_DEVICE_DIR = "/sdcard/Download"_fixtures_pushed = False
def fixtures_dir() -> str: """The host fixtures directory, or "" when this app needs none.
The script's own directory comes FIRST: at eval, RESULTS_DIR is a separate eval_results/ dir, while the fixtures were restored next to the test files. """ for cand in (os.environ.get("FIXTURES_DIR", ""), os.path.join(os.path.dirname(os.path.abspath(sys.argv[0] or ".")), "fixtures"), os.path.join(RESULTS_DIR, "fixtures")): if cand and os.path.isdir(cand): return cand return ""
def fixture_names() -> list[str]: """Fixture paths relative to fixtures_dir(), e.g. ["doc.pdf", "docs/b.epub"].""" src = fixtures_dir() if not src: return [] out = [] for root, _dirs, files in os.walk(src): for fn in sorted(files): if fn.startswith("."): continue out.append(os.path.relpath(os.path.join(root, fn), src)) return sorted(out)
def fixture_on_device(name: str, dest: str = FIXTURES_DEVICE_DIR) -> str: """Where `name` lives on the device after push_fixtures().""" return f"{dest.rstrip('/')}/{name}"
def push_fixtures(dest: str = FIXTURES_DEVICE_DIR, *, force: bool = False) -> bool: """Mirror the host fixtures onto the device. Idempotent and safe to call from every test — a file already there with the same size is not re-pushed, so the six module processes cost one real push between them.
Returns True when the device holds every fixture (including the vacuous case of an app that needs none). """ global _fixtures_pushed if _fixtures_pushed and not force: return True src = fixtures_dir() names = fixture_names() if not src or not names: _fixtures_pushed = True return True ok = True pushed = 0 for rel in names: local = os.path.join(src, rel) remote = fixture_on_device(rel, dest) try: want = os.path.getsize(local) except OSError: ok = False continue got = adb_shell("stat", "-c", "%s", remote) if not force and got.isdigit() and int(got) == want: continue parent = remote.rsplit("/", 1)[0] if parent: adb_shell("mkdir", "-p", parent) adb_raw("push", local, remote, timeout=120) check = adb_shell("stat", "-c", "%s", remote) if check.isdigit() and int(check) == want: pushed += 1 else: ok = False print(f" [fixtures] FAILED to push {rel} -> {remote}") if pushed: # Make the files visible to gallery/media-backed pickers. Both forms are # API-level dependent and neither is required for plain SAF browsing, so # failures here are not fatal. adb_shell("content", "call", "--uri", "content://media/external/file", "--method", "scan_volume", "--arg", "external_primary") adb_shell("am", "broadcast", "-a", "android.intent.action.MEDIA_SCANNER_SCAN_FILE", "-d", f"file://{dest}") print(f" [fixtures] pushed {pushed}/{len(names)} fixture(s) to {dest}") _fixtures_pushed = ok return ok
# ══════════════════════════════════════════════════════════════════════════════# (3) UI tree query & element matching# ══════════════════════════════════════════════════════════════════════════════
def dump_xml(retries: int = 3, settle_first: bool = True) -> str: """uiautomator dump -> XML text. Retries because the dump fails outright while an animation is in flight.""" if settle_first: settle("dump") remote = "/sdcard/_kit_ui.xml" for attempt in range(retries): adb_shell("uiautomator", "dump", remote) xml = adb_shell("cat", remote, timeout=60) if "<node" in xml: return xml settle("dump_retry") return ""
def parse_nodes(xml_str: str) -> list[dict]: """XML -> list of attribute dicts, each with _bounds and _center.""" nodes = [] for m in re.finditer(r"<node\s+([^>]+?)/?>", xml_str): attrs_str = m.group(1) attrs = {am.group(1): am.group(2) for am in re.finditer(r'([\w-]+)="([^"]*)"', attrs_str)} b = re.search(r'bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"', attrs_str) if b: x1, y1, x2, y2 = (int(v) for v in b.groups()) attrs["_bounds"] = (x1, y1, x2, y2) attrs["_center"] = ((x1 + x2) // 2, (y1 + y2) // 2) nodes.append(attrs) return nodes
def ui(retries: int = 3) -> list[dict]: """THE entry point for a fresh tree. Call it again after ANY state change — a scroll, navigation, dialog, or keyboard invalidates every prior coordinate.""" return parse_nodes(dump_xml(retries=retries))
def find_nodes(nodes, **criteria) -> list[dict]: """Nodes matching ALL criteria, EXACT string match. `True`/`False` match the "true"/"false" attribute strings. Underscores in keys become dashes (content_desc -> content-desc).""" out = [] for n in nodes: ok = True for k, v in criteria.items(): key = k.replace("_", "-") if "_" in k and k != "class" else k if key not in n: ok = False break if v is True and n[key] != "true": ok = False break if v is False and n[key] != "false": ok = False break if v is not True and v is not False and n[key] != v: ok = False break if ok: out.append(n) return out
def find_node(nodes, **criteria) -> dict | None: f = find_nodes(nodes, **criteria) return f[0] if f else None
def find_by_class(nodes, widget_class: str) -> list[dict]: """Partial class-name match, e.g. "Switch", "EditText", "RecyclerView".""" return [n for n in nodes if widget_class in n.get("class", "")]
def find_node_ci(nodes, text: str) -> dict | None: """Case-insensitive text or content-desc match. Use for user-visible labels whose casing a faithful recreation may legitimately differ on.""" t = text.strip().lower() for n in nodes: if (n.get("text", "").strip().lower() == t or n.get("content-desc", "").strip().lower() == t): return n return None
def node_by_id(nodes, rid_suffix: str) -> dict | None: """Match the LAST segment of resource-id, so the package prefix (which differs between original and recreation) is never compared.""" for n in nodes: rid = n.get("resource-id", "") if rid and rid.rsplit("/", 1)[-1] == rid_suffix: return n return None
def find_closest_match(nodes, original_node) -> dict | None: """Re-locate a node in a fresh dump by similarity (class/text/desc/position).""" best, best_score = None, 0 for n in nodes: score = 0 if n.get("class") == original_node.get("class"): score += 3 if n.get("text") and n.get("text") == original_node.get("text"): score += 5 if (n.get("content-desc") and n.get("content-desc") == original_node.get("content-desc")): score += 4 if "_center" in n and "_center" in original_node: if (abs(n["_center"][0] - original_node["_center"][0]) < 100 and abs(n["_center"][1] - original_node["_center"][1]) < 100): score += 2 if score > best_score: best, best_score = n, score return best if best_score >= 3 else None
def node_key(n: dict) -> str: """"{shortClass}|{identity}" — the surface-membership key. Identity priority: text -> content-desc -> resource-id suffix. Returns "" for anonymous nodes (pure layout containers), which are excluded from a surface.""" cls = n.get("class", "").rsplit(".", 1)[-1] ident = (n.get("text", "").strip() or n.get("content-desc", "").strip() or n.get("resource-id", "").rsplit("/", 1)[-1]) return f"{cls}|{ident}" if ident else ""
def and_showing(nodes=None) -> set[str]: """Snapshot the current SURFACE as a set of discriminating element keys. Only on-screen, non-degenerate, identity-bearing nodes count. Take one before and one after a trigger and feed them to and_reach().""" nodes = ui() if nodes is None else nodes s = get_screen_info() out = set() for n in nodes: b = n.get("_bounds") if not b: continue x1, y1, x2, y2 = b if (x2 - x1) < 5 or (y2 - y1) < 5: continue if x2 <= 0 or y2 <= 0 or x1 >= s["width"] or y1 >= s["height"]: continue k = node_key(n) if k: out.add(k) return out
def and_reach(before, after, target: str, source: str | None = None) -> bool: """TRUE-JUMP verdict: the TARGET surface's element newly APPEARED and (if given) the SOURCE surface's element DISAPPEARED. This is what separates a real surface jump from reading an element that was in the tree all along.""" before, after = set(before or []), set(after or []) t = target.strip().lower() appeared = any(t in k.lower() for k in (after - before)) if source is None: return appeared s = source.strip().lower() return (appeared and any(s in k.lower() for k in before) and not any(s in k.lower() for k in after))
def surface_changed(before, after, min_delta: int = 2) -> bool: """Weaker than and_reach: the surface changed materially but you are not naming the target. Use for shape deltas, never to claim a `reach`.""" return len(set(before or []) ^ set(after or [])) >= min_delta
def and_surface_id(nodes=None) -> str: """A stable-ish fingerprint of the current surface, for "did this change?".""" keys = sorted(and_showing(nodes)) return f"{len(keys)}:{hash(tuple(keys)) & 0xFFFFFF:06x}"
# ══════════════════════════════════════════════════════════════════════════════# (4) Interaction# ══════════════════════════════════════════════════════════════════════════════
def tap(x, y) -> None: adb_shell("input", "tap", int(x), int(y)) settle("tap")
def tap_node(node) -> bool: """Tap a node's centre, validating bounds against the real screen first.""" if not node or "_center" not in node: return False x, y = node["_center"] s = get_screen_info() if x < 0 or x > s["width"] or y < 0 or y > s["height"]: return False if "_bounds" in node: x1, y1, x2, y2 = node["_bounds"] if (x2 - x1) < 5 or (y2 - y1) < 5: return False tap(x, y) return True
def tap_text(nodes, text: str) -> bool: n = find_node(nodes, text=text) or find_node_ci(nodes, text) return tap_node(n) if n else False
def is_safe(node) -> bool: """False for destructive controls. Tests mutate real device state, so every exploratory tap must go through this.""" blob = " ".join([node.get("text", ""), node.get("content-desc", ""), node.get("resource-id", "")]).lower() return not any(d in blob for d in DANGEROUS_TEXTS)
def safe_tap(node) -> bool: return tap_node(node) if node and is_safe(node) else False
def long_press(node, ms: int = 800) -> bool: """Long-press = a zero-distance swipe with a duration.""" if not node or "_center" not in node: return False x, y = node["_center"] adb_shell("input", "swipe", x, y, x, y, int(ms)) settle("tap") return True
def swipe(x1, y1, x2, y2, ms: int = 300) -> None: adb_shell("input", "swipe", int(x1), int(y1), int(x2), int(y2), int(ms)) settle("swipe")
def scroll_down(frac: float = 0.5) -> None: s = get_screen_info() swipe(s["center_x"], int(s["height"] * 0.7), s["center_x"], int(s["height"] * (0.7 - frac)))
def scroll_up(frac: float = 0.5) -> None: s = get_screen_info() swipe(s["center_x"], int(s["height"] * 0.3), s["center_x"], int(s["height"] * (0.3 + frac)))
def open_drawer() -> None: s = get_screen_info() swipe(5, s["center_y"], int(s["width"] * 0.8), s["center_y"], ms=400)
def scroll_into_view(text: str, max_swipes: int = 4) -> dict | None: """Scroll until `text` is on screen, RE-DUMPING between swipes. This encodes "after a scroll every previous coordinate is invalid" as code.""" for _ in range(max_swipes + 1): nodes = ui() n = find_node(nodes, text=text) or find_node_ci(nodes, text) if n: return n scroll_down(0.4) return None
def press_key(keycode) -> None: adb_shell("input", "keyevent", keycode) settle("key")
def back() -> None: """Raw BACK. Use and_back() when you are leaving a surface you entered.""" press_key("KEYCODE_BACK")
def home() -> None: press_key("KEYCODE_HOME")
def enter() -> None: press_key("KEYCODE_ENTER")
def keyboard_visible() -> bool: return "mInputShown=true" in adb_shell("dumpsys", "input_method")
def hide_keyboard() -> bool: """Dismiss the soft keyboard without navigating away. Tries, in order: the collapse affordance, an empty region, then BACK — and BACK is only accepted if the surface did NOT change, because BACK can navigate instead.""" if not keyboard_visible(): return True nodes = ui() for n in nodes: blob = (n.get("content-desc", "") + n.get("resource-id", "")).lower() if any(w in blob for w in ("hide", "collapse", "close_keyboard", "back")): if tap_node(n): settle("keyboard") if not keyboard_visible(): return True s = get_screen_info() tap(s["center_x"], int(s["height"] * 0.12)) # top strip is rarely interactive settle("keyboard") if not keyboard_visible(): return True sid = and_surface_id() back() settle("keyboard") if keyboard_visible(): return False if and_surface_id() != sid: print(" [warn] hide_keyboard: BACK also changed the surface") return True
def _quote_for_device(text: str) -> str: """Quote a string for the on-device shell (adb joins argv with spaces).""" return shlex.quote(text)
def type_text(node, text: str, *, method: str = "auto", verify_focus: bool = True) -> bool: """Type into an EditText, safely.
An unfocused EditText silently swallows ALL input (including paste and the ADB-Keyboard broadcast), so this taps the field, re-dumps, and asserts focused="true" before typing — retrying the tap once.
Routing: pure ASCII -> `input text`. Non-ASCII -> Clipper broadcast + paste. method="ime" -> ADB Keyboard, which needs a re-tap after the IME switch (the switch drops focus) and ALWAYS restores the original IME in a finally. """ if not node: return False target = node if verify_focus: ok = False for _ in range(2): if not tap_node(target): return False settle("keyboard") fresh = find_closest_match(ui(), target) or target if fresh.get("focused") == "true": target, ok = fresh, True break target = fresh if not ok: print(" [warn] type_text: field never reported focused=true") else: tap_node(target) settle("keyboard")
is_ascii = all(ord(c) < 128 for c in text) use = method if use == "auto": use = "input" if is_ascii else "clipper"
if use == "input": adb_shell("input", "text", _quote_for_device(text.replace(" ", "%s"))) settle("text") return True
if use == "clipper": adb_shell("am", "broadcast", "-a", "clipper.set", "-e", "text", _quote_for_device(text)) settle("text") press_key(279) # KEYCODE_PASTE settle("text") return True
# method="ime": ADB Keyboard. Some custom views ignore paste, this is the fallback. original = adb_shell("settings", "get", "secure", "default_input_method") try: adb_shell("ime", "set", ADB_KEYBOARD_IME) settle("ime") tap_node(target) # IME switch dropped focus settle("keyboard") adb_shell("am", "broadcast", "-a", "ADB_INPUT_TEXT", "--es", "msg", _quote_for_device(text)) settle("text") return True finally: if original and "null" not in original.lower(): adb_shell("ime", "set", original) # NEVER leave it switched settle("ime")
# ══════════════════════════════════════════════════════════════════════════════# (5) Navigation & the depth family# ══════════════════════════════════════════════════════════════════════════════
def and_reset_depth() -> None: global _DEPTH _DEPTH = 0
def and_enter(surface: str = "") -> int: """Call right AFTER your test navigates into a new surface. This is what backs a declared depth>=1 — and_audit_depth looks for a call from the and_enter*/and_reach* family.""" global _DEPTH _DEPTH += 1 return _DEPTH
def and_back() -> int: """Press BACK and pop one surface.""" global _DEPTH back() _DEPTH = max(0, _DEPTH - 1) return _DEPTH
def and_enter_surface(nodes, target_text: str = "", content_desc: str = "", rid: str = "") -> tuple[bool, str]: """Tap a named trigger, then confirm the surface changed. Counts one surface on success. Returns (ok, note). Prefer and_reach_surface when you can name the destination — that yields jump_kind="reach".""" n = None if target_text: n = find_node(nodes, text=target_text) or find_node_ci(nodes, target_text) if n is None and content_desc: n = find_node(nodes, content_desc=content_desc) if n is None and rid: n = node_by_id(nodes, rid) if n is None: return False, f"setup_failed: trigger not found ({target_text or content_desc or rid})" before = and_showing(nodes) if not tap_node(n): return False, "setup_failed: trigger not tappable" after = and_showing() if not surface_changed(before, after): return False, "behavior_wrong: surface did not change after tapping the trigger" and_enter(target_text or content_desc or rid) return True, ""
def and_reach_surface(node, target: str, source: str | None = None) -> bool: """Tap `node`, then PROVE the jump: `target` appeared and `source` vanished. Counts one surface. This is the only honest way to claim jump_kind="reach".""" before = and_showing() if not tap_node(node): return False after = and_showing() ok = and_reach(before, after, target, source) if ok: and_enter(target) return ok
# ══════════════════════════════════════════════════════════════════════════════# (6) App lifecycle — always keyed on PACKAGE (argv[1]), never a literal# ══════════════════════════════════════════════════════════════════════════════
def launch_app() -> None: adb_shell("monkey", "-p", PACKAGE, "-c", "android.intent.category.LAUNCHER", "1") settle("launch")
def force_stop() -> None: adb_shell("am", "force-stop", PACKAGE) settle("key")
def clear_data() -> None: """Wipe app data. Use to guarantee a clean entry point, never mid-assertion.""" adb_shell("pm", "clear", PACKAGE) settle("key")
def restart_app() -> None: force_stop() launch_app()
def force_stop_and_relaunch() -> None: """The persistence probe: kill the process, relaunch, then assert the state survived. An in-memory-only recreation fails this.""" force_stop() settle("key") launch_app()
def get_current_activity() -> str: out = adb_shell("dumpsys", "activity", "activities") m = re.search(r"mResumedActivity.*?\{[^}]*?([\w.]+/[\w.$]+)", out) if m: return m.group(1) m = re.search(r"mCurrentFocus=.*?\{[^}]*?([\w.]+/[\w.$]+)", adb_shell("dumpsys", "window")) return m.group(1) if m else ""
def is_app_foreground() -> bool: return PACKAGE in get_current_activity() or PACKAGE in adb_shell("dumpsys", "window")
def wait_for_foreground(timeout: int = 10) -> bool: deadline = time.time() + timeout while time.time() < deadline: if is_app_foreground(): return True time.sleep(0.5) return False
# ══════════════════════════════════════════════════════════════════════════════# (7) VLM# ══════════════════════════════════════════════════════════════════════════════
# OpenAI-compatible endpoint. Hardcoded on purpose: the public DashScope native# endpoint rejected the key that pods are provisioned with, so every generated# suite either lost its whole VLM track or shipped a hand-rolled `dashscope.py`# shim to reroute it. This speaks plain chat/completions over the standard library# only — no `pip install`, and the stale shims in the testcases bank can no longer# shadow the transport because nothing imports `dashscope` any more.VLM_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"_VLM_DEFAULT_KEY = "sk-bd0c3f375649439bba62b5b0e8c13057"# Attempts per key. 3 covers the blips seen in practice (empty body, gateway 5xx,# rate-limit bursts) without turning a genuine outage into a 10-minute stall.VLM_RETRIES = int(os.environ.get("VLM_RETRIES", "3"))# Repeating these cannot help: the request itself is wrong (malformed, missing,# too large, or semantically rejected). Everything else 4xx/5xx is worth a retry._VLM_TERMINAL_CODES = {400, 404, 413, 422}
def _vlm_key() -> str: """The judge model's API key: first non-empty of DASHSCOPE_API_KEY, VLM_API_KEY, JUDGE_API_KEY. Empty when none is set.""" for name in ("DASHSCOPE_API_KEY", "VLM_API_KEY", "JUDGE_API_KEY"): v = os.environ.get(name, "").strip() if v: return v return ""
def call_vlm(image_path: str, prompt: str, *, retries: int = 0) -> str | None: """Ask the VLM one question about a local screenshot. Returns the answer text.
Retries transient API failures (empty body, 429, 408/409/425, any 5xx) up to `retries` times — default VLM_RETRIES (3), overridable via the VLM_RETRIES env var. Terminal errors (bad key, malformed/oversized request) are not retried. """ retries = retries or VLM_RETRIES key = _vlm_key() or _VLM_DEFAULT_KEY try: with open(image_path, "rb") as f: b64 = base64.b64encode(f.read()).decode() except Exception as exc: print(f"[VLM] cannot read screenshot {image_path}: {exc}") return None mime = "image/jpeg" if image_path.lower().endswith((".jpg", ".jpeg")) else "image/png" body = json.dumps({ "model": os.environ.get("JUDGE_MODEL", "qwen3.7-plus"), "temperature": 0, "messages": [{"role": "user", "content": [ {"type": "image_url", "image_url": {"url": f"data:{mime};base64,{b64}"}}, {"type": "text", "text": prompt}, ]}], }).encode()
for attempt in range(retries): backoff = 2 * (attempt + 1) req = urllib.request.Request( f"{VLM_BASE_URL}/chat/completions", data=body, headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"}) try: with urllib.request.urlopen(req, timeout=120) as resp: data = json.loads(resp.read().decode()) text = (data["choices"][0]["message"]["content"] or "").strip() if text: return text print(f"[VLM] empty response (attempt {attempt + 1}/{retries})") except urllib.error.HTTPError as exc: detail = exc.read().decode(errors="replace")[:200] print(f"[VLM] HTTP {exc.code} (attempt {attempt + 1}/{retries}): {detail}") if exc.code in (401, 403) or exc.code in _VLM_TERMINAL_CODES: return None # repeating cannot help if exc.code == 429: backoff = 10 * (attempt + 1) # rate limit, not a blip except Exception as exc: # timeout, DNS, reset, bad JSON print(f"[VLM] call failed (attempt {attempt + 1}/{retries}): {exc}") if attempt < retries - 1: time.sleep(backoff) print(f"[VLM] giving up after {retries} attempt(s)") return None
def _vlm_log(results_dir: str, entry: dict) -> None: """Append one attempt to vlm_assertions.json. Called on EVERY vlm_assert exit path, including failures — a `_vlm` case with no entry here then provably never invoked the VLM, which is what build_manifest keys off.""" af = os.path.join(results_dir, "vlm_assertions.json") try: existing = json.load(open(af)) if os.path.exists(af) else [] if not isinstance(existing, list): existing = [] except Exception: existing = [] existing.append(entry) try: _write_json(af, existing) # type: ignore[arg-type] except Exception: try: with open(af, "w") as f: json.dump(existing, f, indent=2, ensure_ascii=False) except Exception as exc: print(f" [warn] vlm_assert: cannot write {af}: {exc}")
def vlm_assert(test_name, question, results_dir=None, expect="YES", *, depth=None, jump_kind="none", tag=None) -> bool: """Screenshot the current screen, ask the VLM one YES/NO question, record it.
`test_name` is auto-suffixed with `_vlm`, which is what routes it to the VLM track in save_results(). `tag` (color|shape|position|size|layout|content) lets and_audit compute the fine-grained share mechanically — always set it.
Ask about a SPECIFIC observable rendered property. A question that a blank screen or any app would pass is worthless. """ if not test_name.endswith("_vlm"): test_name += "_vlm" rd = results_dir or RESULTS_DIR if tag and tag not in VLM_TAGS: print(f" [warn] vlm_assert: unknown tag {tag!r}") ss_path = os.path.join(rd, "screenshots", f"{test_name}.png")
def _fail(msg: str, resp=None, answer="") -> bool: _vlm_log(rd, {"test_name": test_name, "question": question, "screenshot": ss_path, "vlm_response": resp, "vlm_answer": answer, "expected": expect, "passed": False, "tag": tag or "", "error": msg}) return record(test_name, False, msg, depth=depth, jump_kind=jump_kind, tag=tag)
if not screencap(ss_path): return _fail("setup_failed: screenshot capture failed")
prompt = ("Look at this Android app screenshot and answer the following question " "with ONLY 'YES' or 'NO'. Do not explain.\n\n" f"Question: {question}\n\nAnswer (YES or NO):") # An unparseable answer is the same class of flakiness as an empty body, so # re-ask rather than scoring harness noise against the VLM track. answer, resp = "", None for ask in range(VLM_RETRIES): resp = call_vlm(ss_path, prompt) if resp is None: return _fail("setup_failed: VLM API call failed") a = resp.strip().upper() # Whole-word match only: a bare `"NO" in a` also fires on CANNOT / NOT / # NONE / KNOW, turning "Maybe? I cannot tell." into a confident NO and # failing the test on harness noise instead of re-asking. has_yes = re.search(r"\bYES\b", a) is not None has_no = re.search(r"\bNO\b", a) is not None if a.startswith("YES"): answer = "YES" elif a.startswith("NO"): answer = "NO" elif has_yes and not has_no: answer = "YES" elif has_no and not has_yes: answer = "NO" if answer: break print(f"[VLM] unparseable answer {resp!r} (ask {ask + 1}/{VLM_RETRIES})") if not answer: return _fail(f"setup_failed: ambiguous VLM response after {VLM_RETRIES} " f"asks {resp!r}", resp=resp)
passed = answer == expect.upper() record(test_name, passed, (f"VLM: Q='{question}' A={answer} expect={expect}" if passed else f"behavior_wrong: VLM Q='{question}' A={answer} expect={expect}"), depth=depth, jump_kind=jump_kind, expect=f"VLM {expect}: {question}", tag=tag) _vlm_log(rd, {"test_name": test_name, "question": question, "screenshot": ss_path, "vlm_response": resp, "vlm_answer": answer, "expected": expect, "passed": passed, "tag": tag or ""}) return passed
# ══════════════════════════════════════════════════════════════════════════════# (8) Audit / lint — ALL report-only. None of these ever blocks delivery.# ══════════════════════════════════════════════════════════════════════════════
def _load_all(results_dir: str) -> list[dict]: recs, seen_files = [], set() for pat in (os.path.join(results_dir, "android_*_eval.json"), os.path.join(results_dir, "eval_results", "android_*_eval.json")): for path in glob.glob(pat): base = os.path.basename(path) if base in seen_files: continue seen_files.add(base) try: data = json.load(open(path)) except Exception: continue for t in data.get("results", []): if isinstance(t, dict) and "test" in t: recs.append(t) return recs
def and_audit(results_dir: str = "", quotas: dict | None = None) -> dict: """Aggregate declared depth/jump_kind/vlm-tag across the suite and report the quota TARGETS with the concrete gap. GOALS, not a gate.""" results_dir = results_dir or RESULTS_DIR q = quotas or QUOTAS recs = _load_all(results_dir) backfilled = [r for r in recs if r.get("backfilled")] recs = [r for r in recs if not r.get("backfilled")] n = len(recs) if not n: print(f"[and_audit] no records under {results_dir}") return {"total": 0} kinds = [r.get("jump_kind", "none") for r in recs] none_n = sum(1 for k in kinds if k == "none") live_n = sum(1 for k in kinds if k == "liveness") inter = [r for r in recs if r.get("jump_kind") in ("reach", "transition", "value")] ni = len(inter) or 1 d1 = sum(1 for r in inter if int(r.get("depth", 0)) >= 1) d2 = sum(1 for r in inter if int(r.get("depth", 0)) >= 2) val = sum(1 for r in inter if r.get("jump_kind") == "value") vlm = [r for r in recs if r["test"].endswith("_vlm")] fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS) vlm_share = len(vlm) / n
def line(label, got, need, kind): ok = got >= need if kind == "min" else got <= need return ok, (f" [{'ok ' if ok else 'GAP'}] {label}: {got:.0%} " f"({'>=' if kind == 'min' else '<='} {need:.0%})")
lo, hi = q["vlm_share_min"], q["vlm_share_max"] vlm_ok = lo <= vlm_share <= hi if vlm_share < lo: # each added vlm record also grows the denominator: (v+x)/(n+x) >= lo need_more = math.ceil((lo * n - len(vlm)) / (1 - lo)) vlm_hint = (f"under budget by ~{max(1, need_more)} record(s) — allocate more " f"per lane NEXT run; do not re-run to chase it") elif vlm_share > hi: vlm_hint = "over budget — allocate fewer per lane next run" else: vlm_hint = "in budget" vlm_msg = (f" [{'ok ' if vlm_ok else 'GAP'}] VLM BUDGET vlm/total: " f"{len(vlm)}/{n} = {vlm_share:.0%} (target {lo:.0%}-{hi:.0%}) " f"— {vlm_hint}")
checks = [ line("existence(none)/all", none_n / n, q["existence_max"], "max"), line("interactive/all", len(inter) / n, q["interactive_min"], "min"), line("depth>=1 /interactive", d1 / ni, q["depth_ge1_min"], "min"), line("depth>=2 /interactive", d2 / ni, q["depth_ge2_min"], "min"), line("value(tier3)/interactive", val / ni, q["value_min"], "min"), (vlm_ok, vlm_msg), line("vlm fine-grained/vlm", fine / (len(vlm) or 1), q["vlm_fine_min"], "min"), ] print(f"[and_audit] {results_dir} total={n} interactive={len(inter)} " f"none={none_n} liveness={live_n} depth>=1={d1} depth>=2={d2} " f"value={val} vlm={len(vlm)} vlm_fine={fine}") if backfilled: print(f" [!!!] {len(backfilled)} record(s) never reached their assertion " f"(back-filled as failures) — excluded from the ratios above; the " f"100%-pass gate on the original app must catch these") for _ok, msg in checks: print(msg) passed = all(ok for ok, _ in checks) print("[and_audit] " + ("ALL TARGETS MET" if passed else "some targets below — this is a REPORT, not a task: finalize now and fix " "the shortfall in the NEXT run's plan. Re-running the suite to move these " "numbers costs hours and changes nothing about the app under test")) return {"total": n, "interactive": len(inter), "none": none_n, "liveness": live_n, "depth_ge1": d1, "depth_ge2": d2, "value": val, "vlm": len(vlm), "vlm_fine": fine, "vlm_share": round(vlm_share, 4), "backfilled": len(backfilled), "passed": passed, "checks": [m for _o, m in checks]}
def and_lint(results_dir: str = "") -> list[str]: """Flag weak or inconsistent DECLARATIONS.""" results_dir = results_dir or RESULTS_DIR issues, names = [], set() for r in _load_all(results_dir): jk, nm = r.get("jump_kind", "none"), r.get("test", "?") if nm in names: issues.append(f"{nm}: duplicate record name (drifts the denominator)") names.add(nm) if jk not in JUMP_KINDS: issues.append(f"{nm}: unknown jump_kind {jk!r}") if jk in ("reach", "transition", "value") and not str(r.get("expect", "")).strip(): issues.append(f"{nm}: jump_kind={jk} but empty expect " f"(name the specific observed target)") if jk == "liveness": issues.append(f"{nm}: liveness is tier1 — assert the app-authored effect instead") if int(r.get("depth", 0)) < 0: issues.append(f"{nm}: negative depth") msg = str(r.get("message", "")) if not r.get("passed") and not msg.startswith(FAIL_PREFIXES): issues.append(f"{nm}: failure message must start with one of " f"{'/'.join(FAIL_PREFIXES)} (got {msg[:40]!r})") if nm.endswith("_vlm") and not r.get("tag") and not r.get("backfilled"): issues.append(f"{nm}: VLM record has no tag " f"(color|shape|position|size|layout|content)") if issues: print(f"[and_lint] {len(issues)} issue(s):") for i in issues: print(" - " + i) else: print("[and_lint] no issues") return issues
# Non-portable source patterns: they pass on the ORIGINAL app and break on the# RECREATION (different package, different install path). Each is a hard defect._BAD_SOURCE_PATTERNS = [ (r"""["'][a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*){2,}["']""", "hardcodes a package name; use the module-level PACKAGE (argv[1]) — the " "recreation's package differs", ("android.", "androidx.", "java.", "javax.", "com.android.adbkeyboard", "ca.zgrs.clipper", "android.intent.", "com.google.android.inputmethod")), (r"""["'][^"']*\.apk["']|clean\.apk""", "names an APK path; the test must never install or locate the app", ()), (r"/data/data/|/sdcard/Android/data/", "uses a per-package data path, which breaks when the recreation's package " "differs; drive state through the GUI", ()), (r"\btap\(\s*\d{2,}\s*,\s*\d{2,}", "taps a hardcoded pixel coordinate; derive it from a node's _center or " "get_screen_info()", ()), (r"\bpm\s+grant\b|\bappops\s+set\b|\bsettings\s+put\b|\bcontent\s+insert\b", "seeds state outside the GUI; the recreation may not honor it — drive the " "same state through the UI", ()), (r"am\s+start\s+-n\s", "deep-links straight to a component: not portable, and not navigation " "(it cannot back a depth claim)", ()), (r"emulator-\d{4}|127\.0\.0\.1:\d{4}", "hardcodes a device serial; use the module-level DEVICE", ()),]
def and_lint_sources(testgen_dir: str = "") -> list[str]: """Scan authored test/helper .py for NON-PORTABLE patterns and for kit API drift. A clean result means the suite will actually drive the recreation, not just the original.""" testgen_dir = testgen_dir or RESULTS_DIR kit_base = os.path.basename(__file__) py = [p for p in (glob.glob(os.path.join(testgen_dir, "*.py")) + glob.glob(os.path.join(testgen_dir, "tests", "*.py"))) if os.path.basename(p) != kit_base] kit_names = set(globals().keys()) # A sample file the app is supposed to OPEN. Testgen and eval run on DIFFERENT # emulators, so naming one without pushing it means it only ever existed # because someone put it there by hand while exploring. _DEV_PATH_RE = re.compile(r"/sdcard/|/storage/emulated/|\bDCIM\b", re.I) _DOC_RE = re.compile( r"""["'][^"']*\.(?:pdf|epub|mobi|djvu|zim|mp3|mp4|mkv|wav|ogg)["']""", re.I) _fix_files = [f for f in glob.glob(os.path.join(testgen_dir, "fixtures", "**"), recursive=True) if os.path.isfile(f)] issues = [] srcs = {} for p in py: try: srcs[p] = open(p, errors="replace").read() except Exception: continue suite_pushes = any(re.search(r"\b(push_fixtures|fixture_on_device)\b", s) for s in srcs.values()) if _fix_files and not suite_pushes: issues.append( f"fixtures/: {len(_fix_files)} fixture file(s) are authored but NO test " f"calls push_fixtures() — they never reach the device, so every test " f"that opens one records setup_failed. Call it once via run_suite(), " f"or drop the directory.") for p, src in srcs.items(): base = os.path.basename(p) # Strip comments AND docstrings: prose describing the app under test names # files it opens, which is not the same as the code depending on one. scan = re.sub(r'"""[\s\S]*?"""|\'\'\'[\s\S]*?\'\'\'', '""', src) scan = re.sub(r"#[^\n]*", "", scan) # adb is called argv-style — adb_shell("am", "start", "-n", x) — so collapse # the quote-comma-quote separators to read those calls as command lines. flat = re.sub(r"""["']\s*,\s*["']""", " ", scan) if not suite_pushes: for ln in scan.splitlines(): m = _DEV_PATH_RE.search(ln) or _DOC_RE.search(ln) if m: issues.append( f"{base}: needs a sample file on the device " f"[{ln.strip()[:60]}] but the suite never calls " f"push_fixtures() — testgen and eval run on DIFFERENT " f"emulators, so at eval the file is absent. Author the bytes " f"into {os.path.join(testgen_dir, 'fixtures')}/ and let " f"run_suite() push them.") break for pat, why, allow in _BAD_SOURCE_PATTERNS: hit = None for form in (scan, flat): for m in re.finditer(pat, form): cand = m.group(0) if allow and any(a in cand for a in allow): continue hit = cand break if hit: break if hit: issues.append(f"{base}: {why} [{hit[:48]}]") # kit API drift — an import/attr the kit does not define imported: list[str] = [] for m in re.finditer( r"from\s+android_testgen_kit\s+import\s+\(([^)]*)\)", scan, re.S): imported += m.group(1).split(",") for m in re.finditer( r"from\s+android_testgen_kit\s+import\s+([^\n(]+)", scan): imported += m.group(1).split(",") for raw in imported: nm = raw.strip().split(" as ")[0].strip() if nm and nm != "*" and nm not in kit_names: issues.append(f"{base}: imports android_testgen_kit.{nm} which the " f"kit does not define (would ImportError at eval)") for m in re.finditer(r"\bkit\.(\w+)\s*\(", scan): if m.group(1) not in kit_names: issues.append(f"{base}: calls kit.{m.group(1)}() which the kit does " f"not define (would AttributeError at eval)") if issues: print(f"[and_lint_sources] {len(issues)} portability issue(s):") for i in issues: print(" - " + i) else: print("[and_lint_sources] no portability issues") return issues
# ── MEASURED depth cross-check (report-only): does the SOURCE back the DECLARE? ─def _ast_call_name(node) -> str: f = node.func if isinstance(f, ast.Attribute): return f.attr if isinstance(f, ast.Name): return f.id return ""
def _string_locals(fn_node) -> dict[str, str]: """`name = "states_toggle"` inside a test — so record(name, ...) resolves.""" out = {} for n in ast.walk(fn_node): if isinstance(n, ast.Assign) and isinstance(n.value, ast.Constant) \ and isinstance(n.value.value, str): for t in n.targets: if isinstance(t, ast.Name): out[t.id] = n.value.value return out
def _record_names(fn_node) -> list[str]: """Literal record()/vlm_assert() names in this function, preferring the @and_test(expects=(...)) literal when present.""" for dec in getattr(fn_node, "decorator_list", []): if isinstance(dec, ast.Call) and _ast_call_name(dec) == "and_test": for kw in dec.keywords: if kw.arg == "expects" and isinstance(kw.value, (ast.Tuple, ast.List)): return [e.value for e in kw.value.elts if isinstance(e, ast.Constant) and isinstance(e.value, str)] slocals = _string_locals(fn_node) names = [] for n in ast.walk(fn_node): if not (isinstance(n, ast.Call) and _ast_call_name(n) in ("record", "vlm_assert")): continue if not n.args: continue a0 = n.args[0] if isinstance(a0, ast.Constant) and isinstance(a0.value, str): names.append(a0.value) elif isinstance(a0, ast.Name) and a0.id in slocals: names.append(slocals[a0.id]) return names
def _depth_calls(fn_node, local_funcs, budget: int = 2, seen=None): """(fwd, back, reach) depth-family calls, descending `budget` levels into file-local helpers. Cycle-guarded. A LOWER BOUND — never an over-claim.""" seen = seen if seen is not None else set() fwd = bk = rch = 0 relaunch = False for node in ast.walk(fn_node): if not isinstance(node, ast.Call): continue cn = _ast_call_name(node) if DEPTH_FWD_RE.match(cn): fwd += 1 if cn.startswith("and_reach"): rch += 1 elif DEPTH_BACK_RE.match(cn): bk += 1 elif cn in ("launch_app", "restart_app", "force_stop_and_relaunch"): relaunch = True elif budget > 0 and cn in local_funcs and cn not in seen: seen.add(cn) f, b, r = _depth_calls(local_funcs[cn], local_funcs, budget - 1, seen)[:3] fwd, bk, rch = fwd + f, bk + b, rch + r return fwd, bk, rch, relaunch
def and_audit_depth(testgen_dir: str = "", results_dir: str = "") -> list[str]: """MEASURE navigation depth from the test SOURCE (AST) and cross-check the DECLARED depth/jump_kind — so a test cannot just TYPE depth=2. REPORT-ONLY.
Flags a declared depth>=1 or jump_kind="reach" with NO backing call from the depth family and_enter*/and_reach* (directly, in a file-local helper it calls, or anywhere in the module for variable-named records), plus a "reach" that was achieved by relaunching the app rather than navigating. """ testgen_dir = testgen_dir or RESULTS_DIR results_dir = results_dir or testgen_dir files = [p for p in (glob.glob(os.path.join(testgen_dir, "test_android_*.py")) + glob.glob(os.path.join(testgen_dir, "tests", "test_android_*.py")))] per_record, per_module = {}, {} for p in files: try: tree = ast.parse(open(p, errors="replace").read()) except Exception: continue stem = os.path.basename(p)[len("test_android_"):-len(".py")] mod = _MODULE_ALIAS.get(stem, stem) local_funcs = {n.name: n for n in ast.walk(tree) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))} module_backing = any( isinstance(n, ast.Call) and DEPTH_FWD_RE.match(_ast_call_name(n)) for n in ast.walk(tree)) per_module[mod] = {"module_backing": module_backing} for fn in local_funcs.values(): if not fn.name.startswith("test_"): continue fwd, bk, rch, relaunch = _depth_calls(fn, local_funcs) measured = max(0, max((fwd - rch) - bk, 1 if rch >= 1 else 0)) for nm in _record_names(fn): per_record[(mod, nm)] = {"measured_depth": measured, "backing": fwd >= 1, "n_reach": rch, "relaunch": relaunch, "fn": fn.name} issues = [] for r in _load_all(results_dir): nm, jk = r.get("test", "?"), r.get("jump_kind", "none") depth = int(r.get("depth", 0) or 0) strong = depth >= 1 or jk == "reach" hit = None for (mod, rname), v in per_record.items(): if rname == nm: hit = v break if hit is not None: if strong and not hit["backing"]: issues.append(f"{nm} ({hit['fn']}): declared depth={depth}/" f"jump_kind={jk} but NO backing and_enter*/and_reach* " f"call (fake depth)") elif jk == "reach" and hit["n_reach"] == 0: issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but no " f"and_reach* call in its code") elif jk == "reach" and hit["relaunch"]: issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but the function " f"relaunches the app — that is not navigation") elif strong and not any(v.get("module_backing", True) for v in per_module.values()): issues.append(f"{nm}: declared depth={depth}/jump_kind={jk} but no " f"and_enter*/and_reach* call anywhere (fake depth)") if issues: print(f"[and_audit_depth] {len(issues)} fake-depth issue(s) (REPORT-ONLY — " f"fix by adding the and_reach/and_enter you navigated with, or lower " f"the declared depth):") for i in issues: print(" - " + i) else: print("[and_audit_depth] no fake-depth issues " "(declared depth/reach backed by nav calls)") return issues
# ══════════════════════════════════════════════════════════════════════════════# (9) Frozen manifest — the FIXED denominator (ported from RecreationBench v7.2)## Without this, the eval denominator is whatever the candidate happened to emit:# a recreation that crashes a module SHRINKS its own denominator instead of# counting the missing behaviour as failures. The manifest is frozen ONCE per# task from the ORIGINAL app's run and is the denominator authority for every# candidate. Missing tests are injected as `not_run`; extra tests are ignored.# ══════════════════════════════════════════════════════════════════════════════
MANIFEST_NAME = "test_manifest.json"MANIFEST_VERSION = 1
def qualify_name(module: str, test: str) -> str: """`module::test` — two modules may legitimately reuse a short test name.""" return test if "::" in test else f"{module}::{test}"
def _record_status(rec: dict) -> str: if rec.get("status") in ("passed", "failed", "error", "skipped", "not_run"): return rec["status"] return "passed" if rec.get("passed") else "failed"
def _load_by_module(results_dir: str) -> list[tuple[str, dict]]: """Like _load_all but keeps the owning module, so names can be qualified.""" out, seen_files = [], set() for pat in (os.path.join(results_dir, "android_*_eval.json"), os.path.join(results_dir, "eval_results", "android_*_eval.json")): for path in sorted(glob.glob(pat)): base = os.path.basename(path) if base in seen_files: continue seen_files.add(base) try: data = json.load(open(path)) except Exception: continue mod = data.get("module") or base[len("android_"):-len("_eval.json")] for t in data.get("results", []): if isinstance(t, dict) and "test" in t: out.append((str(mod), t)) return out
def _vlm_logged_names(results_dir: str) -> tuple[set[str], bool]: """(names with >=1 logged VLM attempt, whether any log file was found).
Checks the root AND eval_results/ — the agent's self-validation run drives test_verify.sh with --output-dir, which puts the log one level down. """ names, found = set(), False for sub in ("", "eval_results"): p = os.path.join(results_dir, sub, "vlm_assertions.json") if not os.path.isfile(p): continue found = True try: for x in json.load(open(p)): if isinstance(x, dict) and x.get("test_name"): names.add(str(x["test_name"])) except Exception: pass return names, found
def build_manifest(results_dir: str = "", *, task_id: str = "", baseline_model: str = "", out_path: str = "") -> dict: """Freeze the ORIGINAL app's PASSING tests as the denominator.
A test that fails on the original is not a signal about any recreation, so it is moved to `ignored[reason=baseline_fail]` instead of counting against every candidate. This is the only denominator-shrinking mechanism, and it is applied identically to all candidates. """ results_dir = results_dir or RESULTS_DIR logged, log_found = _vlm_logged_names(results_dir) tests, ignored, vlm_assertions = [], [], [] n_unverified = 0 for mod, rec in _load_by_module(results_dir): name = qualify_name(mod, str(rec.get("test", ""))) status = _record_status(rec) entry = {"name": name, "module": mod, "baseline_status": status} is_vlm = name.endswith("_vlm") # A passing _vlm case with no logged attempt never provably reached the # judge on the original app — it must not sit in the VLM denominator that # every recreation is scored against. if is_vlm and status == "passed" and str(rec.get("test", "")) not in logged: n_unverified += 1 ignored.append({"name": name, "module": mod, "reason": "vlm_unverified", "baseline_status": status, "message": "no attempt in vlm_assertions.json — the VLM " "was never provably invoked for this case"}) continue if status == "passed": tests.append(entry) if is_vlm: vlm_assertions.append({"name": name, "module": mod, "tag": rec.get("tag", "")}) else: ignored.append({"name": name, "module": mod, "reason": "baseline_fail", "baseline_status": status, "message": str(rec.get("message", ""))[:300]}) tests.sort(key=lambda t: t["name"]) ignored.sort(key=lambda t: t["name"]) payload = "\n".join(t["name"] for t in tests) pkg = (os.environ.get("ORIG_PACKAGE") or os.environ.get("PACKAGE") or (PACKAGE if "." in PACKAGE else "")) manifest = { "manifest_version": MANIFEST_VERSION, "kit_api_version": KIT_API_VERSION, "task_id": task_id or os.environ.get("INSTANCE_ID", ""), "baseline_model": baseline_model or os.environ.get("MODEL", ""), "baseline_package": pkg, "total": len(tests), "manifest_sha": hashlib.sha256(payload.encode()).hexdigest()[:12], "tests": tests, "ignored": ignored, "vlm_assertions": vlm_assertions, "vlm_total": len(vlm_assertions), "n_vlm_unverified": n_unverified, "vlm_log_found": log_found, } dest = out_path or os.path.join(results_dir, MANIFEST_NAME) tmp = dest + ".tmp" with open(tmp, "w") as f: json.dump(manifest, f, indent=2, ensure_ascii=False) os.replace(tmp, dest) print(f"[build_manifest] {dest} total={manifest['total']} " f"vlm={manifest['vlm_total']} ignored={len(ignored)} " f"sha={manifest['manifest_sha']}") if n_unverified: print(f" [!!!] {n_unverified} passing _vlm case(s) EXCLUDED as " f"vlm_unverified — no attempt logged in vlm_assertions.json" + ("" if log_found else " (no log file found at all — the suite may " "have bypassed the kit's vlm_assert)") + ". They are out of the VLM denominator; fix the VLM path rather " "than accepting the smaller denominator.") base_fail = [i for i in ignored if i["reason"] == "baseline_fail"] if base_fail: print(f" {len(base_fail)} baseline failure(s) excluded from the denominator " f"(they say nothing about a recreation):") for i in base_fail[:20]: print(f" - {i['name']}: {i['message'][:120]}") return manifest
def load_manifest(d: str = "") -> dict | None: """Return the frozen manifest from `d` (or its eval_results/), else None.""" d = d or RESULTS_DIR for p in (os.path.join(d, MANIFEST_NAME), os.path.join(d, "eval_results", MANIFEST_NAME)): if os.path.isfile(p): try: m = json.load(open(p)) except Exception: continue if isinstance(m, dict) and m.get("tests"): return m return None
def score_against_manifest(results_dir: str = "", manifest: dict | None = None) -> dict: """Score a candidate run against the frozen denominator.
denominator = len(manifest["tests"]) regardless of what the candidate emitted. A manifest test the candidate never reported is injected as `not_run` (a non-pass); a test the candidate invented is excluded. A module that crashed on import therefore scores 0/full instead of vanishing. """ results_dir = results_dir or RESULTS_DIR manifest = manifest or load_manifest(results_dir) if not manifest: return {} expected = {t["name"]: t for t in manifest["tests"]} got = {} for mod, rec in _load_by_module(results_dir): got[qualify_name(mod, str(rec.get("test", "")))] = rec
per_test, by_module = {}, {} injected = 0 for name, meta in expected.items(): rec = got.get(name) if rec is None: status, msg = "not_run", "not_run: absent from the candidate's output" injected += 1 else: status, msg = _record_status(rec), str(rec.get("message", "")) per_test[name] = {"status": status, "message": msg[:300]} m = by_module.setdefault(meta.get("module", "?"), {"total": 0, "passed": 0, "not_run": 0}) m["total"] += 1 m["passed"] += status == "passed" m["not_run"] += status == "not_run"
unexpected = sorted(set(got) - set(expected)) total = len(expected) passed = sum(1 for v in per_test.values() if v["status"] == "passed") vlm_names = {a["name"] for a in manifest.get("vlm_assertions", [])} vlm_total = len(vlm_names) vlm_passed = sum(1 for n in vlm_names if per_test.get(n, {}).get("status") == "passed") rule_total = total - vlm_total rule_passed = passed - vlm_passed for m in by_module.values(): m["pass_rate"] = round(m["passed"] / m["total"], 4) if m["total"] else 0.0
out = { "scored_against": "manifest", "manifest_sha": manifest.get("manifest_sha", ""), "manifest_total": total, "total": total, "passed": passed, "pass_rate": round(passed / total, 4) if total else 0.0, "n_injected_not_run": injected, "n_unexpected": len(unexpected), "unexpected": unexpected[:50], "rule": {"total": rule_total, "passed": rule_passed, "pass_rate": round(rule_passed / rule_total, 4) if rule_total else 0.0}, "vlm": {"total": vlm_total, "passed": vlm_passed, "pass_rate": round(vlm_passed / vlm_total, 4) if vlm_total else 0.0}, "by_module": by_module, "per_test": per_test, } print(f"[score_against_manifest] sha={out['manifest_sha']} " f"{passed}/{total} = {out['pass_rate']:.4f} " f"(injected_not_run={injected} unexpected={len(unexpected)}) " f"rule={rule_passed}/{rule_total} vlm={vlm_passed}/{vlm_total}") return out
if __name__ == "__main__": _fns = {"audit": and_audit, "lint": and_lint, "lint_sources": and_lint_sources, "build_manifest": build_manifest} _argv = sys.argv[1:] if _argv[:1] == ["audit_depth"] and len(_argv) >= 2: and_audit_depth(_argv[1], _argv[2] if len(_argv) >= 3 else "") elif _argv[:1] == ["score"] and len(_argv) >= 2: _m = load_manifest(_argv[2]) if len(_argv) >= 3 else load_manifest(_argv[1]) _out = score_against_manifest(_argv[1], _m) if not _out: print("no manifest found — cannot score against a fixed denominator", file=sys.stderr) sys.exit(2) print(json.dumps(_out, ensure_ascii=False)) elif len(_argv) >= 2 and _argv[0] in _fns: _fns[_argv[0]](_argv[1]) else: print("usage: android_testgen_kit.py {audit|lint|lint_sources|build_manifest} <dir>\n" " android_testgen_kit.py audit_depth <testgen_dir> [results_dir]\n" " android_testgen_kit.py score <results_dir> [manifest_dir]")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293{ "module": "text", "total": 29, "passed": 29, "failed": 0, "pass_rate": 1.0, "rule": { "total": 29, "passed": 29, "failed": 0, "pass_rate": 1.0 }, "vlm": { "total": 0, "passed": 0, "failed": 0, "pass_rate": 0 }, "vlm_ratio": 0.0, "audit": { "kit_api_version": 1, "existence": 0, "liveness": 0, "interactive": 29, "depth_ge1": 21, "depth_ge2": 0, "value": 24, "vlm_fine": 0 }, "results": [ { "test": "text_toolbar_title", "passed": true, "message": "", "depth": 0, "jump_kind": "value", "tier": 3, "expect": "toolbar title == 'Sudoku'" }, { "test": "text_play_button_label", "passed": true, "message": "", "depth": 0, "jump_kind": "value", "tier": 3, "expect": "playButton label == 'NEW GAME'" }, { "test": "text_continue_button_label", "passed": true, "message": "", "depth": 0, "jump_kind": "value", "tier": 3, "expect": "continueButton label == 'CONTINUE GAME'" }, { "test": "text_level_count_format", "passed": true, "message": "", "depth": 0, "jump_kind": "value", "tier": 3, "expect": "level_count matches ^Levels available: \\d+$" }, { "test": "text_section_label_carousel_right", "passed": true, "message": "", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "section_label 'Sudoku 9x9' -> 'Sudoku 12x12'" }, { "test": "text_section_label_carousel_16", "passed": true, "message": "", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "section_label 'Sudoku 9x9' -> 'Sudoku 16x16'" }, { "test": "text_difficulty_label_easy", "passed": true, "message": "", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "difficultyText 'Moderate' -> 'Easy'" }, { "test": "text_difficulty_label_challenge", "passed": true, "message": "", "depth": 0, "jump_kind": "transition", "tier": 2, "expect": "difficultyText 'Moderate' -> 'Challenge'" }, { "test": "text_drawer_items_core", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "drawer items: Main Menu, Daily Sudoku, Import Sudoku, Highscore" }, { "test": "text_drawer_items_secondary", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "drawer items: Tutorial, Settings, Help, About" }, { "test": "text_daily_title", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "Daily screen title == 'Daily Sudoku'" }, { "test": "text_daily_labels", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "labels: Used hints, Completed games, Total time played:" }, { "test": "text_daily_time_format", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "numb_of_total_time matches ^\\d{2}:\\d{2}:\\d{2}$" }, { "test": "text_stats_title", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "Stats screen title == 'Highscore'" }, { "test": "text_stats_difficulty_rows", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "rows: Easy, Moderate, Hard, Challenge" }, { "test": "text_stats_stat_labels", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "first_av_text 'Ø-time:', first_min_text 'Best time:'" }, { "test": "text_help_summaries", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "Help: 'Undoes the last action', 'Redoes the last undone action'" }, { "test": "text_help_titles", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "Help titles: Hint button, Delete button, Note toggle button" }, { "test": "text_about_appname", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "appName == 'Privacy Friendly Sudoku'" }, { "test": "text_about_labels", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "textFieldVersion 'Version:', textFieldAuthor 'Authors:'" }, { "test": "text_about_links", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "secusoWebsite 'SECUSO-Website', githubURL 'Github-Repo'" }, { "test": "text_import_prompt", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "message == 'Enter the link of the sudoku you wish to import:'" }, { "test": "text_import_buttons", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "buttons 'CANCEL' and 'IMPORT'" }, { "test": "text_tutorial_welcome", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "slide 1: 'Welcome!' and 'Welcome to Privacy Friendly Sudoku!'" }, { "test": "text_tutorial_buttons", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "buttons 'SKIP' and 'NEXT'" }, { "test": "text_tutorial_next_slide", "passed": true, "message": "", "depth": 1, "jump_kind": "transition", "tier": 2, "expect": "slide heading changes 'Welcome!' -> next slide heading" }, { "test": "text_loadgame_gametype", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "a saved row shows gametype 'Sudoku 9x9'" }, { "test": "text_loadgame_time_format", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "loadgame_listentry_timeplayed matches ^\\d{2}:\\d{2}:\\d{2}$" }, { "test": "text_loadgame_relative_time", "passed": true, "message": "", "depth": 1, "jump_kind": "value", "tier": 3, "expect": "loadgame_listentry_lasttimeplayed contains 'ago'/'minute'" } ]}android/secuso-privacy-friendly-2048/LICENSEAdded+676
android/secuso-privacy-friendly-2048/instance.jsonAdded+10
android/secuso-privacy-friendly-2048/reference/launch.shAdded+9
android/secuso-privacy-friendly-2048/tests/android_computation_eval.jsonAdded+232
android/secuso-privacy-friendly-2048/tests/android_interaction_eval.jsonAdded+274
android/secuso-privacy-friendly-2048/tests/android_navigation_eval.jsonAdded+283
android/secuso-privacy-friendly-2048/tests/android_states_eval.jsonAdded+229
android/secuso-privacy-friendly-2048/tests/android_structure_eval.jsonAdded+202
android/secuso-privacy-friendly-2048/tests/android_testgen_kit.pyAdded+1910
android/secuso-privacy-friendly-2048/tests/android_text_eval.jsonAdded+196
android/secuso-privacy-friendly-2048/tests/conftest.pyAdded+1
android/secuso-privacy-friendly-2048/tests/requirements.txtAdded+2
android/secuso-privacy-friendly-2048/tests/test_android_computation.pyAdded+1075
android/secuso-privacy-friendly-2048/tests/test_android_interaction.pyAdded+1012
android/secuso-privacy-friendly-2048/tests/test_android_navigation.pyAdded+599
android/secuso-privacy-friendly-2048/tests/test_android_states.pyAdded+984
android/secuso-privacy-friendly-2048/tests/test_android_structure.pyAdded+403
android/secuso-privacy-friendly-2048/tests/test_android_text.pyAdded+697
android/secuso-privacy-friendly-2048/tests/test_manifest.jsonAdded+857
android/secuso-privacy-friendly-2048/vlm_assertions.jsonAdded+743
android/secuso-privacy-friendly-pedometer/LICENSEAdded+675
android/secuso-privacy-friendly-pedometer/instance.jsonAdded+10
android/secuso-privacy-friendly-pedometer/reference/launch.shAdded+9
android/secuso-privacy-friendly-pedometer/tests/android_computation_eval.jsonAdded+215
android/secuso-privacy-friendly-pedometer/tests/android_interaction_eval.jsonAdded+192
android/secuso-privacy-friendly-pedometer/tests/android_navigation_eval.jsonAdded+209
android/secuso-privacy-friendly-pedometer/tests/android_states_eval.jsonAdded+266
android/secuso-privacy-friendly-pedometer/tests/android_structure_eval.jsonAdded+229
android/secuso-privacy-friendly-pedometer/tests/android_testgen_kit.pyAdded+1910
android/secuso-privacy-friendly-pedometer/tests/android_text_eval.jsonAdded+196
android/secuso-privacy-friendly-pedometer/tests/conftest.pyAdded+1
android/secuso-privacy-friendly-pedometer/tests/requirements.txtAdded+2
android/secuso-privacy-friendly-pedometer/tests/test_android_computation.pyAdded+498
android/secuso-privacy-friendly-pedometer/tests/test_android_interaction.pyAdded+768
android/secuso-privacy-friendly-pedometer/tests/test_android_navigation.pyAdded+401
android/secuso-privacy-friendly-pedometer/tests/test_android_states.pyAdded+1145
android/secuso-privacy-friendly-pedometer/tests/test_android_structure.pyAdded+495
android/secuso-privacy-friendly-pedometer/tests/test_android_text.pyAdded+618
android/secuso-privacy-friendly-pedometer/tests/test_manifest.jsonAdded+792
android/secuso-privacy-friendly-pedometer/vlm_assertions.jsonAdded+723
android/secuso-privacy-friendly-sudoku/LICENSE.mdAdded+674
android/secuso-privacy-friendly-sudoku/instance.jsonAdded+10
android/secuso-privacy-friendly-sudoku/reference/launch.shAdded+9
android/secuso-privacy-friendly-sudoku/tests/android_computation_eval.jsonAdded+222
android/secuso-privacy-friendly-sudoku/tests/android_interaction_eval.jsonAdded+195
android/secuso-privacy-friendly-sudoku/tests/android_navigation_eval.jsonAdded+227
android/secuso-privacy-friendly-sudoku/tests/android_states_eval.jsonAdded+242
android/secuso-privacy-friendly-sudoku/tests/android_structure_eval.jsonAdded+173
android/secuso-privacy-friendly-sudoku/tests/android_testgen_kit.pyAdded+1910
android/secuso-privacy-friendly-sudoku/tests/android_text_eval.jsonAdded+293